diff --git a/multichat/pom.xml b/multichat/pom.xml index a405ea17..fe1f0695 100644 --- a/multichat/pom.xml +++ b/multichat/pom.xml @@ -5,7 +5,7 @@ xyz.olivermartin.multichat multichat - 1.7.5 + 1.8 diff --git a/multichat/releases/1.8/multichat-1.8-alpha1.jar b/multichat/releases/1.8/multichat-1.8-alpha1.jar new file mode 100644 index 00000000..2c08a5b4 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha10.jar b/multichat/releases/1.8/multichat-1.8-alpha10.jar new file mode 100644 index 00000000..2a655592 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha10.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha11.jar b/multichat/releases/1.8/multichat-1.8-alpha11.jar new file mode 100644 index 00000000..b82f59f1 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha11.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha12.jar b/multichat/releases/1.8/multichat-1.8-alpha12.jar new file mode 100644 index 00000000..86654594 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha12.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha13.jar b/multichat/releases/1.8/multichat-1.8-alpha13.jar new file mode 100644 index 00000000..1903955a Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha13.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha14.jar b/multichat/releases/1.8/multichat-1.8-alpha14.jar new file mode 100644 index 00000000..5a79f0ec Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha14.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha15.jar b/multichat/releases/1.8/multichat-1.8-alpha15.jar new file mode 100644 index 00000000..ec4bcc4a Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha15.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha16.jar b/multichat/releases/1.8/multichat-1.8-alpha16.jar new file mode 100644 index 00000000..b09b65d4 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha16.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha17.jar b/multichat/releases/1.8/multichat-1.8-alpha17.jar new file mode 100644 index 00000000..db55313d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha17.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha18.jar b/multichat/releases/1.8/multichat-1.8-alpha18.jar new file mode 100644 index 00000000..dd3a3a9a Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha18.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha19.jar b/multichat/releases/1.8/multichat-1.8-alpha19.jar new file mode 100644 index 00000000..e52edbf7 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha19.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha2.jar b/multichat/releases/1.8/multichat-1.8-alpha2.jar new file mode 100644 index 00000000..1ce99ab4 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha20.jar b/multichat/releases/1.8/multichat-1.8-alpha20.jar new file mode 100644 index 00000000..41104271 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha20.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha3.jar b/multichat/releases/1.8/multichat-1.8-alpha3.jar new file mode 100644 index 00000000..8c274d6d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha3.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha4.jar b/multichat/releases/1.8/multichat-1.8-alpha4.jar new file mode 100644 index 00000000..6ece020c Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha4.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha5.jar b/multichat/releases/1.8/multichat-1.8-alpha5.jar new file mode 100644 index 00000000..ca692953 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha5.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha6.jar b/multichat/releases/1.8/multichat-1.8-alpha6.jar new file mode 100644 index 00000000..e83a1a0d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha6.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha7.jar b/multichat/releases/1.8/multichat-1.8-alpha7.jar new file mode 100644 index 00000000..831d8007 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha7.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha8.jar b/multichat/releases/1.8/multichat-1.8-alpha8.jar new file mode 100644 index 00000000..3995902e Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha8.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-alpha9.jar b/multichat/releases/1.8/multichat-1.8-alpha9.jar new file mode 100644 index 00000000..99071287 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-alpha9.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-beta-1.jar b/multichat/releases/1.8/multichat-1.8-beta-1.jar new file mode 100644 index 00000000..f1c86af3 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-beta-1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-beta-2.jar b/multichat/releases/1.8/multichat-1.8-beta-2.jar new file mode 100644 index 00000000..1f27ec36 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-beta-2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-beta-3.jar b/multichat/releases/1.8/multichat-1.8-beta-3.jar new file mode 100644 index 00000000..3b6ee0e0 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-beta-3.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-beta-4.jar b/multichat/releases/1.8/multichat-1.8-beta-4.jar new file mode 100644 index 00000000..74e782b3 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-beta-4.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-pre-1.jar b/multichat/releases/1.8/multichat-1.8-pre-1.jar new file mode 100644 index 00000000..37fa457d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-pre-1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-1.1.jar b/multichat/releases/1.8/multichat-1.8-snapshot-1.1.jar new file mode 100644 index 00000000..c3be009d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-1.1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-1.2.jar b/multichat/releases/1.8/multichat-1.8-snapshot-1.2.jar new file mode 100644 index 00000000..3d957d4d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-1.2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-1.3.jar b/multichat/releases/1.8/multichat-1.8-snapshot-1.3.jar new file mode 100644 index 00000000..e5f03a23 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-1.3.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-1.4.jar b/multichat/releases/1.8/multichat-1.8-snapshot-1.4.jar new file mode 100644 index 00000000..4268f2f7 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-1.4.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-2.1.jar b/multichat/releases/1.8/multichat-1.8-snapshot-2.1.jar new file mode 100644 index 00000000..43023bb0 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-2.1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.1.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.1.jar new file mode 100644 index 00000000..67a04b1a Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.2.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.2.jar new file mode 100644 index 00000000..0314ba0f Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.3.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.3.jar new file mode 100644 index 00000000..d7b083e4 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.3.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.4.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.4.jar new file mode 100644 index 00000000..47b19e85 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.4.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.5.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.5.jar new file mode 100644 index 00000000..d9403149 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.5.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.6.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.6.jar new file mode 100644 index 00000000..874f4bed Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.6.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.7.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.7.jar new file mode 100644 index 00000000..3e48f572 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.7.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-3.8.jar b/multichat/releases/1.8/multichat-1.8-snapshot-3.8.jar new file mode 100644 index 00000000..a7342e61 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-3.8.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.1.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.1.jar new file mode 100644 index 00000000..e734a7b0 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.10.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.10.jar new file mode 100644 index 00000000..9a7cdf4a Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.10.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.11.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.11.jar new file mode 100644 index 00000000..30e7544b Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.11.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.12.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.12.jar new file mode 100644 index 00000000..8f4adb94 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.12.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.13.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.13.jar new file mode 100644 index 00000000..a472d3aa Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.13.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.14.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.14.jar new file mode 100644 index 00000000..5a079bc1 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.14.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.15.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.15.jar new file mode 100644 index 00000000..244b5213 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.15.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.16.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.16.jar new file mode 100644 index 00000000..931c9cd6 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.16.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.17.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.17.jar new file mode 100644 index 00000000..74e782b3 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.17.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.2.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.2.jar new file mode 100644 index 00000000..d7671d19 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.3.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.3.jar new file mode 100644 index 00000000..913750a3 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.3.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.4.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.4.jar new file mode 100644 index 00000000..ee7e126d Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.4.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.5.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.5.jar new file mode 100644 index 00000000..7e5e8a0f Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.5.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.6.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.6.jar new file mode 100644 index 00000000..c1529c79 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.6.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.7.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.7.jar new file mode 100644 index 00000000..f29fc923 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.7.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.8.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.8.jar new file mode 100644 index 00000000..91373274 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.8.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-4.9.jar b/multichat/releases/1.8/multichat-1.8-snapshot-4.9.jar new file mode 100644 index 00000000..85056a4c Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-4.9.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-5.1.jar b/multichat/releases/1.8/multichat-1.8-snapshot-5.1.jar new file mode 100644 index 00000000..cea5fc18 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-5.1.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-5.2.jar b/multichat/releases/1.8/multichat-1.8-snapshot-5.2.jar new file mode 100644 index 00000000..af51ec9e Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-5.2.jar differ diff --git a/multichat/releases/1.8/multichat-1.8-snapshot-5.3.jar b/multichat/releases/1.8/multichat-1.8-snapshot-5.3.jar new file mode 100644 index 00000000..ff20cbc2 Binary files /dev/null and b/multichat/releases/1.8/multichat-1.8-snapshot-5.3.jar differ diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java index 5ab3ee2c..5efede3b 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/BungeeComm.java @@ -182,7 +182,7 @@ public static void sendPlayerChannelMessage(String playerName, String channel, C @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")) ) { + 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; } @@ -227,12 +227,12 @@ public static void onPluginMessage(PluginMessageEvent ev) { DebugManager.log("{multichat:chat} Got player successfully! Name = " + player.getName()); - synchronized (player) { + //synchronized (player) { - DebugManager.log("{multichat:chat} Global Channel Available? = " + (Channel.getGlobalChannel() != null)); - Channel.getGlobalChannel().sendMessage(player, message, format); + 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"); @@ -440,5 +440,57 @@ public static void onPluginMessage(PluginMessageEvent ev) { } } + + + if (ev.getTag().equals("multichat:pxe")) { + + 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")) { + + 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(); + } + + } + } } 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 dde37c26..2159d81f 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/ConsoleManager.java @@ -9,11 +9,11 @@ import net.md_5.bungee.api.chat.TextComponent; public class ConsoleManager { - + public static void log(String message) { logToConsole(message); } - + public static void logDisplayMessage(String message) { logToConsole(MessageManager.getMessage("console_display_prefix") + message); } @@ -23,25 +23,37 @@ public static void logChat(String message) { logToConsole(MessageManager.getMessage("console_chat_prefix") + message); } - + public static void logModChat(String message) { + if (!MultiChat.logStaffChat) { + return; + } + logToConsole(MessageManager.getMessage("console_modchat_prefix") + message); } - + public static void logGroupChat(String message) { + if (!MultiChat.logGroupChat) { + return; + } + logToConsole(MessageManager.getMessage("console_groupchat_prefix") + message); } - + public static void logAdminChat(String message) { + if (!MultiChat.logStaffChat) { + return; + } + logToConsole(MessageManager.getMessage("console_adminchat_prefix") + message); } - + public static void logHelpMe(String message) { logToConsole(MessageManager.getMessage("console_helpme_prefix") + message); @@ -54,11 +66,15 @@ public static void logBasicChat(String prefix, String message) { logToConsole(MessageManager.getMessage("console_chat_prefix") + prefix, message); } - + public static void logSocialSpy(String p1, String p2, String message) { - + + if (!MultiChat.logPMs) { + return; + } + logToConsole(MessageManager.getMessage("console_socialspy_prefix") + "(" + p1 + " -> " + p2 + ") " + message); - + } private static void logToConsole(String message, String 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 545ec341..86eb7637 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/Events.java @@ -313,66 +313,66 @@ public void onChat(ChatEvent event) { if ((!event.isCancelled()) && (!event.isCommand())) { - if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("global") == true) { + //TODO? I removed these checks... I think thats good... 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())) { + //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) { - BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); - } - - if ((!MultiChat.frozen) || (player.hasPermission("multichat.chat.always"))) { + if (ConfigManager.getInstance().getHandler("config.yml").getConfig().getBoolean("fetch_spigot_display_names") == true) { + BungeeComm.sendMessage(player.getName(), player.getServer().getInfo()); + } - String message = event.getMessage(); + if ((!MultiChat.frozen) || (player.hasPermission("multichat.chat.always"))) { - if (ChatControl.isMuted(player.getUniqueId(), "global_chat")) { - MessageManager.sendMessage(player, "mute_cannot_send_message"); - event.setCancelled(true); - return; - } + String message = event.getMessage(); - DebugManager.log(player.getName() + "- about to check for spam"); + if (ChatControl.isMuted(player.getUniqueId(), "global_chat")) { + MessageManager.sendMessage(player, "mute_cannot_send_message"); + event.setCancelled(true); + return; + } - if (ChatControl.handleSpam(player, message, "global_chat")) { - DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); - event.setCancelled(true); - return; - } + DebugManager.log(player.getName() + "- about to check for spam"); - Optional crm; + if (ChatControl.handleSpam(player, message, "global_chat")) { + DebugManager.log(player.getName() + " - chat message being cancelled due to spam"); + event.setCancelled(true); + return; + } - crm = ChatControl.applyChatRules(message, "global_chat", player.getName()); + Optional crm; - 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); - } + crm = ChatControl.applyChatRules(message, "global_chat", player.getName()); - // 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"))); + if (crm.isPresent()) { + message = crm.get(); + event.setMessage(message); + } else { + event.setCancelled(true); + return; + } - // Message passes through to spigot here + if (!player.hasPermission("multichat.chat.link")) { + message = ChatControl.replaceLinks(message); + event.setMessage(message); + } - if (hiddenStaff.contains(player.getUniqueId())) { - hiddenStaff.remove(player.getUniqueId()); - } + // 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"))); - } else { - MessageManager.sendMessage(player, "freezechat_frozen"); - event.setCancelled(true); - } + // Message passes through to spigot here + if (hiddenStaff.contains(player.getUniqueId())) { + hiddenStaff.remove(player.getUniqueId()); } + + } else { + MessageManager.sendMessage(player, "freezechat_frozen"); + event.setCancelled(true); } + } + //TODO ?} + //TODO? } } @EventHandler @@ -428,9 +428,9 @@ public void onLogin(PostLoginEvent event) { //ConsoleManager.log("Created new global chat entry for " + player.getName()); } - + if (MultiChat.forceChannelOnJoin) { - + boolean globalMode; if (!MultiChat.defaultChannel.equalsIgnoreCase("local")) { globalMode = true; @@ -438,7 +438,7 @@ public void onLogin(PostLoginEvent event) { globalMode = false; } ChatModeManager.getInstance().registerPlayer(uuid, globalMode); - + } // Set player to appropriate channels @@ -463,20 +463,37 @@ public void onLogin(PostLoginEvent event) { 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"); + } for (ProxiedPlayer onlineplayer : ProxyServer.getInstance().getPlayers()) { if (!player.hasPermission("multichat.staff.silentjoin")) { - if (firstJoin && ConfigManager.getInstance().getHandler("joinmessages.yml").getConfig().getBoolean("welcome")) { + 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 { 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 9198e16a..7c4552e7 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/bungee/MultiChat.java @@ -37,11 +37,12 @@ */ public class MultiChat extends Plugin implements Listener { - public static final String LATEST_VERSION = "1.7.5"; + public static final String LATEST_VERSION = "1.8"; public static final String[] ALLOWED_VERSIONS = new String[] { LATEST_VERSION, + "1.7.5", "1.7.4", "1.7.3", "1.7.2", @@ -81,6 +82,10 @@ public class MultiChat extends Plugin implements Listener { 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 MultiChat getInstance() { @@ -255,6 +260,8 @@ public void onEnable() { 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(); @@ -267,7 +274,7 @@ public void onEnable() { if (!configversion.equals(LATEST_VERSION)) { getLogger().info("[!!!] [WARNING] YOUR CONFIG FILES ARE NOT THE LATEST VERSION"); - getLogger().info("[!!!] [WARNING] MULTICHAT 1.7 INTRODUCES SEVERAL NEW FEATURES WHICH ARE NOT IN YOUR OLD FILE"); + 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"); @@ -290,6 +297,8 @@ public void onEnable() { 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 @@ -307,6 +316,12 @@ public void onEnable() { ChatControl.linkMessage = chatcontrolYML.getString("link_removal_message"); } + 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"); + } + // Set default channel defaultChannel = configYML.getString("default_channel"); forceChannelOnJoin = configYML.getBoolean("force_channel_on_join"); 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 8bc0e302..7eec0622 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 @@ -1,10 +1,20 @@ package xyz.olivermartin.multichat.bungee.commands; +import java.util.Optional; + 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.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; /** * Global Command @@ -15,20 +25,83 @@ */ public class GlobalCommand extends Command { - private static String[] aliases = new String[] {}; - public GlobalCommand() { - super("global", "multichat.chat.mode", aliases); + 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)) { - ChatModeManager.getInstance().setGlobal(((ProxiedPlayer)sender).getUniqueId()); + 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); + } + + // 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"))); + + // 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"); + } + + } + } - MessageManager.sendMessage(sender, "command_global_enabled_1"); - MessageManager.sendMessage(sender, "command_global_enabled_2"); + } } else { MessageManager.sendMessage(sender, "command_global_only_players"); 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 66c5bdca..7813753c 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,10 +1,20 @@ package xyz.olivermartin.multichat.bungee.commands; +import java.util.Optional; + 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.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; /** * Local Chat Command @@ -15,20 +25,75 @@ */ public class LocalCommand extends Command { - private static String[] aliases = new String[] {}; - public LocalCommand() { - super("local", "multichat.chat.mode", aliases); + 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)) { - ChatModeManager.getInstance().setLocal(((ProxiedPlayer)sender).getUniqueId()); + 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"))) { + + 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); + } + + // 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"))); + + // Message passes through to spigot here + // Send message directly to local chat... + + BungeeComm.sendPlayerCommandMessage("!SINGLE L 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"); + } - MessageManager.sendMessage(sender, "command_local_enabled_1"); - MessageManager.sendMessage(sender, "command_local_enabled_2"); + } } else { MessageManager.sendMessage(sender, "command_local_only_players"); 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 9637f8d0..8807ab57 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 @@ -107,6 +107,8 @@ public void execute(CommandSender sender, String[] args) { 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(); @@ -115,13 +117,19 @@ public void execute(CommandSender sender, String[] args) { 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("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"); + } + // 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"); 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 b89ae55f..c2bdb7fb 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 @@ -65,6 +65,8 @@ public void execute(CommandSender sender, String[] args) { message = message + arg + " "; } } + + message = message.trim(); for (ServerInfo s : ProxyServer.getInstance().getServers().values()) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseManager.java new file mode 100644 index 00000000..9f80c07f --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseManager.java @@ -0,0 +1,262 @@ +package xyz.olivermartin.multichat.database; + +import java.io.File; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +public class DatabaseManager { + + private static DatabaseManager instance; + + public static DatabaseManager getInstance() { + return instance; + } + + static { + instance = new DatabaseManager(); + } + + /* END STATIC */ + + private File databasePathSQLite; + private String databaseURLMySQL; + private String databaseUsernameMySQL; + private String databasePasswordMySQL; + + private DatabaseMode databaseMode = DatabaseMode.SQLite; + + private Map databases; + + private DatabaseManager() { + databases = new HashMap(); + } + + //////////// + + public static void main(String args[]) throws SQLException { + + DatabaseManager.getInstance().setPathSQLite(new File("C:\\multichat\\db\\")); + DatabaseManager.getInstance().createDatabase("multichat.db"); + + Optional odb = DatabaseManager.getInstance().getDatabase("multichat.db"); + + if (odb.isPresent()) { + + GenericDatabase db = odb.get(); + UUID uuid1 = UUID.randomUUID(); + UUID uuid2 = UUID.randomUUID(); + + try { + db.connectToDatabase(); + db.execute("DROP TABLE IF EXISTS name_data;"); + db.execute("DROP TABLE IF EXISTS nick_data;"); + + db.update("CREATE TABLE IF NOT EXISTS name_data(id VARCHAR(128), f_name VARCHAR(255), u_name VARCHAR(255), PRIMARY KEY (id));"); + db.update("CREATE TABLE IF NOT EXISTS nick_data(id VARCHAR(128), u_nick VARCHAR(255), f_nick VARCHAR(255), PRIMARY KEY (id));"); + + db.update("INSERT INTO name_data VALUES ('" + uuid1.toString() + "', 'Revilo410', 'revilo410');"); + db.update("INSERT INTO nick_data VALUES ('" + uuid1.toString() + "', '&3Revi', 'revi');"); + db.update("INSERT INTO name_data VALUES ('" + uuid2.toString() + "', 'Revilo510', 'revilo510');"); + ResultSet results = db.query("SELECT * FROM name_data;"); + while (results.next()) { + System.out.println(results.getString("id")); + } + + results = db.query("SELECT * FROM nick_data;"); + while (results.next()) { + System.out.println(results.getString("id")); + } + + results = db.query("SELECT * FROM name_data INNER JOIN nick_data ON name_data.id = nick_data.id;"); + while (results.next()) { + System.out.println(results.getString("id")); + } + + results = db.query("SELECT * FROM name_data LEFT JOIN nick_data ON name_data.id = nick_data.id;"); + while (results.next()) { + System.out.println(results.getString("id")); + if (results.getString("f_nick") == null) { + System.out.println(results.getString("f_name")); + } else { + System.out.println(results.getString("f_nick")); + } + } + + results = db.query("SELECT f_name, f_nick FROM name_data LEFT JOIN nick_data ON name_data.id = nick_data.id WHERE name_data.id = '" + uuid1.toString() + "';"); + while (results.next()) { + if (results.getString("f_nick") == null) { + System.out.println(results.getString("f_name")); + } else { + System.out.println(results.getString("f_nick")); + } + } + + db.disconnectFromDatabase(); + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + /*DatabaseManager.getInstance().setPathSQLite(new File("C:\\multichat\\db\\")); + DatabaseManager.getInstance().createDatabase("multichat.db"); + + Optional odb = DatabaseManager.getInstance().getDatabase("multichat.db"); + + if (odb.isPresent()) { + + GenericDatabase db = odb.get(); + UUID uuid1 = UUID.randomUUID(); + + try { + db.connectToDatabase(); + db.execute("DROP TABLE IF EXISTS muted_users;"); + db.execute("DROP TABLE IF EXISTS ignored_users;"); + // TODO Announcements + // TODO Bulletins + // TODO Casts + // TODO Mod & Admin Chat Preferences + // TODO Group Chat Info + // TODO Group Spy Info + // TODO Social Spy Info + // TODO Global Chat Info + + db.update("CREATE TABLE muted_users(id VARCHAR(128) PRIMARY KEY);"); + db.update("CREATE TABLE ignored_users(ignorer_id VARCHAR(128) PRIMARY KEY, ignoree_id VARCHAR(128));"); + + db.update("INSERT INTO muted_users VALUES ('" + uuid1.toString() + "');"); + ResultSet results = db.query("SELECT * FROM muted_users;"); + while (results.next()) { + System.out.println(results.getString("id")); + } + db.disconnectFromDatabase(); + } catch (SQLException e) { + e.printStackTrace(); + } + + /*SQLNameManager sqlnm = new SQLNameManager(); + System.out.println(sqlnm.getCurrentName(uuid1)); + System.out.println(sqlnm.getName(uuid1)); + + //if (sqlnm.getUUIDFromUnformattedNickname("Test").isPresent()) System.out.println(":("); + //if (sqlnm.getUUIDFromUnformattedNickname("revilo").isPresent()) System.out.println(":)"); + + System.out.println(sqlnm.getUUIDFromName("Revilo410").get()); + + System.out.println(sqlnm.getUUIDFromNickname("Revilo").get()); + + System.out.println("!!!"); + + UUID uuid2 = UUID.randomUUID(); + sqlnm.testRegisterFakePlayer(uuid2, "Johno"); + + System.out.println(sqlnm.getUUIDFromName("Johno").get()); + + sqlnm.testRegisterFakePlayer(uuid2, "Johno2"); + + System.out.println(sqlnm.getUUIDFromName("Johno2").get()); + + sqlnm.setNickname(uuid2, "JonnyBoy"); + + System.out.println(sqlnm.getCurrentName(uuid2)); + + sqlnm.removeNickname(uuid2); + + System.out.println(sqlnm.getCurrentName(uuid2)); + + }*/ + + } + + //////////// + + public void setPathSQLite(File path) { + this.databasePathSQLite = path; + } + + public void setURLMySQL(String url) { + this.databaseURLMySQL = url; + } + + public void setUsernameMySQL(String user) { + this.databaseUsernameMySQL = user; + } + + public void setPasswordMySQL(String pass) { + this.databasePasswordMySQL = pass; + } + + public void setMode(DatabaseMode dbm) { + databaseMode = dbm; + } + + public GenericDatabase createDatabase(String name) throws SQLException { + return createDatabase(name, name); + } + + public boolean isReady() { + switch (databaseMode) { + case MySQL: + if (databaseURLMySQL != null && databaseUsernameMySQL != null && databasePasswordMySQL != null) { + return true; + } else { + return false; + } + case SQLite: + default: + return databasePathSQLite != null; + } + + } + + /** + * Generic class to create a sqlite database + * @throws SQLException + */ + public GenericDatabase createDatabase(String databaseName, String fileName) throws SQLException { + + if (!isReady()) throw new RuntimeException("MultiChat Database Manager Not Ready!"); + + switch (databaseMode) { + case MySQL: + + databases.put(databaseName.toLowerCase(), new MySQLDatabase(databaseURLMySQL, fileName, databaseUsernameMySQL, databasePasswordMySQL)); + + return databases.get(databaseName.toLowerCase()); + + case SQLite: + default: + + if (!databasePathSQLite.exists()) { + databasePathSQLite.mkdirs(); + } + + databases.put(databaseName.toLowerCase(), new SQLiteDatabase(databasePathSQLite, fileName)); + + return databases.get(databaseName.toLowerCase()); + + } + + } + + public Optional getDatabase(String databaseName) { + if (databases.containsKey(databaseName.toLowerCase())) { + return Optional.of(databases.get(databaseName.toLowerCase())); + } else { + return Optional.empty(); + } + } + + public void removeDatabase(String databaseName) throws SQLException { + if (databases.containsKey(databaseName.toLowerCase())) { + GenericDatabase gdb = databases.get(databaseName.toLowerCase()); + gdb.disconnectFromDatabase(); + databases.remove(databaseName.toLowerCase()); + } + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseMode.java b/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseMode.java new file mode 100644 index 00000000..78c87be1 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/database/DatabaseMode.java @@ -0,0 +1,8 @@ +package xyz.olivermartin.multichat.database; + +public enum DatabaseMode { + + SQLite, + MySQL + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/database/GenericDatabase.java b/multichat/src/main/java/xyz/olivermartin/multichat/database/GenericDatabase.java new file mode 100644 index 00000000..8ed8aba5 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/database/GenericDatabase.java @@ -0,0 +1,55 @@ +package xyz.olivermartin.multichat.database; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public abstract class GenericDatabase { + + protected String url; + private boolean ready; + + protected String username; + protected String password; + + public GenericDatabase(String url) throws SQLException { + this.url = url; + ready = setupDatabase(url); + } + + public GenericDatabase(String url, String user, String pass) throws SQLException { + this.url = url; + this.username = user; + this.password = pass; + ready = setupDatabase(url); + } + + public String getURL() { + return this.url; + } + + public boolean isReady() { + return this.ready; + } + + protected abstract boolean setupDatabase(String url) throws SQLException; + + protected abstract void disconnect() throws SQLException; + + protected abstract boolean connect() throws SQLException; + + public abstract ResultSet query(String sql) throws SQLException; + + public abstract void update(String sql) throws SQLException; + + public abstract void execute(String sql) throws SQLException; + + public void connectToDatabase() throws SQLException { + this.ready = connect(); + } + + public void disconnectFromDatabase() throws SQLException { + disconnect(); + this.ready = false; + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/database/MySQLDatabase.java b/multichat/src/main/java/xyz/olivermartin/multichat/database/MySQLDatabase.java new file mode 100644 index 00000000..b5e4cf4d --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/database/MySQLDatabase.java @@ -0,0 +1,97 @@ +package xyz.olivermartin.multichat.database; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class MySQLDatabase extends GenericDatabase { + + private static final String URL_PREFIX = "jdbc:mysql:"; + private Connection conn; + + public MySQLDatabase(String url, String databaseName, String username, String password) throws SQLException { + super(URL_PREFIX + "//" + url + "/" + databaseName, username, password); + //System.out.println(URL_PREFIX + "//" + url + "/" + databaseName); + //System.out.println(username); + //System.out.println(password); + } + + @Override + protected boolean setupDatabase(String url) throws SQLException { + + Connection conn = DriverManager.getConnection(url, username, password); + + if (conn != null) { + //DatabaseMetaData meta = conn.getMetaData(); + //System.out.println("The driver name is " + meta.getDriverName()); + //System.out.println("A new database has been created."); + + this.conn = conn; + + // Database successfully created + + return true; + } else { + return false; + } + + } + + @Override + protected void disconnect() throws SQLException { + + if (conn != null) { + try { + if (!conn.isClosed()) { + conn.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + } + + @Override + protected boolean connect() throws SQLException { + + if (conn == null) { + return setupDatabase(url); + } else if (conn.isClosed()) { + try { + return setupDatabase(url); + } catch (SQLException e) { + return false; + } + } + + // Already connected + return true; + } + + @Override + public ResultSet query(String sql) throws SQLException { + + ResultSet results = conn.createStatement().executeQuery(sql); + return results; + + } + + @Override + public void update(String sql) throws SQLException { + + conn.createStatement().executeUpdate(sql); + + } + + @Override + public void execute(String sql) throws SQLException { + + conn.createStatement().execute(sql); + + } + + + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/database/SQLiteDatabase.java b/multichat/src/main/java/xyz/olivermartin/multichat/database/SQLiteDatabase.java new file mode 100644 index 00000000..185194a7 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/database/SQLiteDatabase.java @@ -0,0 +1,96 @@ +package xyz.olivermartin.multichat.database; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class SQLiteDatabase extends GenericDatabase { + + private static final String URL_PREFIX = "jdbc:sqlite:"; + private Connection conn; + + public SQLiteDatabase(File path, String filename) throws SQLException { + super(URL_PREFIX + path + File.separator + filename); + } + + protected boolean setupDatabase(String url) throws SQLException { + + Connection conn = DriverManager.getConnection(url); + + if (conn != null) { + //DatabaseMetaData meta = conn.getMetaData(); + //System.out.println("The driver name is " + meta.getDriverName()); + //System.out.println("A new database has been created."); + + this.conn = conn; + + // Database successfully created + + return true; + } else { + return false; + } + + } + + @Override + protected void disconnect() { + + if (conn != null) { + try { + if (!conn.isClosed()) { + conn.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + } + + @Override + protected boolean connect() throws SQLException { + + if (conn == null) { + + return setupDatabase(url); + + } else { + try { + if (conn.isClosed()) { + return setupDatabase(url); + } + } catch (SQLException e) { + return false; + } + } + + // Already connected + return true; + } + + @Override + public ResultSet query(String sql) throws SQLException { + + ResultSet results = conn.createStatement().executeQuery(sql); + return results; + + } + + @Override + public void update(String sql) throws SQLException { + + conn.createStatement().executeUpdate(sql); + + } + + @Override + public void execute(String sql) throws SQLException { + + conn.createStatement().execute(sql); + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/FileNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/FileNameManager.java new file mode 100644 index 00000000..05a4a4bf --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/FileNameManager.java @@ -0,0 +1,594 @@ +package xyz.olivermartin.multichat.spigotbridge; + +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.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.PatternSyntaxException; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +/** + * Player Name Manager + *

Manages players names, uuids and nicknames

+ * + * @author Oliver Martin (Revilo410) + * + */ +public class FileNameManager extends NameManager { + + private Map mapUUIDNick; + private Map mapUUIDName; + private Map mapNickUUID; + private Map mapNameUUID; + + private Map mapNickFormatted; + private Map mapNameFormatted; + + public FileNameManager() { + + super(); + + setDefaultData(); + + } + + private void setDefaultData() { + + mapUUIDNick = new HashMap(); + mapUUIDName = new HashMap(); + mapNickUUID = new HashMap(); + mapNameUUID = new HashMap(); + + mapNickFormatted = new HashMap(); + mapNameFormatted = new HashMap(); + + } + + public Map getMapUUIDName() { + return mapUUIDName; + } + public Map getMapUUIDNick() { + return mapUUIDNick; + } + public Map getMapNameFormatted() { + return mapNameFormatted; + } + public Map getMapNickFormatted() { + return mapNickFormatted; + } + + /** + * Returns the FORMATTED NICKNAME of a player if they have one set, otherwise returns their username + * + * @param uuid The Unique ID of the player to lookup + * @param withPrefix Should the nickname prefix also be returned if it is set? + * @return The NICKNAME of the player if it is set, otherwise their username + */ + public String getCurrentName(UUID uuid, boolean withPrefix) { + + synchronized (mapUUIDNick) { + if (mapUUIDNick.containsKey(uuid)) { + if (MultiChatSpigot.showNicknamePrefix && withPrefix) { + return MultiChatSpigot.nicknamePrefix + mapNickFormatted.get(mapUUIDNick.get(uuid)); + } else { + return mapNickFormatted.get(mapUUIDNick.get(uuid)); + } + } + } + + synchronized (mapUUIDName) { + if (mapUUIDName.containsKey(uuid)) { + return mapNameFormatted.get(mapUUIDName.get(uuid)); + } + } + + return ""; + } + + /** + * Returns the username of a player + * + * @param uuid The Unique ID of the player to lookup + * @return The username of the player + */ + public String getName(UUID uuid) { + + synchronized (mapUUIDName) { + if (mapUUIDName.containsKey(uuid)) { + return mapNameFormatted.get(mapUUIDName.get(uuid)); + } + } + + return ""; + + } + + /** + * Gets the UUID of a player from their UNFORMATTED nickname + * THIS MEANS THE NICKNAME PROVIDED MUST BE IN LOWERCASE WITH ALL FORMATTING CODES REMOVED + * + * @param nickname The UNFORMATTED nickname of the player + * @return An optional which may contain their UUID if the nickname was found in the system + */ + protected Optional getUUIDFromUnformattedNickname(String nickname) { + + nickname = nickname.toLowerCase(); + + synchronized (mapNickUUID) { + if (mapNickUUID.containsKey(nickname)) { + return Optional.of(mapNickUUID.get(nickname)); + } + } + + return Optional.empty(); + + } + + /** + * Returns a player's UUID given their username + * + * @param username The player's username + * @return An optional value which may contain their UUID if the username was found + */ + public Optional getUUIDFromName(String username) { + + username = username.toLowerCase(); + + synchronized (mapNameUUID) { + if (mapNameUUID.containsKey(username)) { + return Optional.of(mapNameUUID.get(username)); + } + } + + return Optional.empty(); + + } + + /** + * Register a player as online + *

Also performs any setup needed to equip nicknames etc.

+ * @param player + */ + public void registerPlayer(Player player) { + + UUID uuid = player.getUniqueId(); + String username = player.getName(); + String oldUsername; + + synchronized (mapUUIDName) { + + if (mapUUIDName.containsKey(uuid)) { + + oldUsername = mapUUIDName.get(uuid); + + if (!oldUsername.equalsIgnoreCase(username)) { + + synchronized (mapNameUUID) { + + mapUUIDName.remove(uuid); + mapUUIDName.put(uuid, username.toLowerCase()); + mapNameUUID.remove(oldUsername); + mapNameUUID.put(username.toLowerCase(), uuid); + + } + + } + + mapNameFormatted.remove(oldUsername); + mapNameFormatted.put(username.toLowerCase(), username); + + } else { + + synchronized (mapNameUUID) { + + mapUUIDName.put(uuid, username.toLowerCase()); + mapNameUUID.put(username.toLowerCase(), uuid); + mapNameFormatted.put(username.toLowerCase(), username); + + } + + } + + } + + online.add(uuid); + Bukkit.getLogger().info("[+] " + username + " has joined this server."); + + } + + /** + * Register a player into the system without them being online + *

Used mainly for legacy conversion of old nickname file

+ * @param uuid Player's UUID + */ + public void registerOfflinePlayerByUUID(UUID uuid, String username) { + + synchronized (mapUUIDName) { + + if (mapUUIDName.containsKey(uuid)) { + + /* + * EMPTY : Player does not need registering + */ + + } else { + + synchronized (mapNameUUID) { + + mapUUIDName.put(uuid, username.toLowerCase()); + mapNameUUID.put(username.toLowerCase(), uuid); + mapNameFormatted.put(username.toLowerCase(), username); + + } + + } + + } + + } + + /** + * Register a player as offline + * @param player + */ + public void unregisterPlayer(Player player) { + + online.remove(player.getUniqueId()); + Bukkit.getLogger().info("[-] " + player.getName() + " has left this server."); + + } + + /** + * Set the nickname of a player + * @param uuid + * @param nickname + */ + public void setNickname(UUID uuid, String nickname) { + + if (!mapUUIDName.containsKey(uuid)) { + return; + } + + if (mapUUIDNick.containsKey(uuid)) { + removeNickname(uuid); + } + + String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + + synchronized (mapNickUUID) { + + // Check for duplicates + if (mapNickUUID.containsKey(unformattedNickname)) { + if (mapNickUUID.get(unformattedNickname) != uuid) { + return; + } + } + + mapUUIDNick.put(uuid, unformattedNickname); + mapNickUUID.put(unformattedNickname, uuid); + mapNickFormatted.put(unformattedNickname, nickname); + + } + + } + + /** + * @param username + * @return If this player has logged into the server before + */ + public boolean existsPlayer(String username) { + return mapNameUUID.containsKey(username.toLowerCase()); + } + + /** + * @param nickname + * @return If this nickname is currently in use + */ + public boolean existsNickname(String nickname) { + return mapNickUUID.containsKey(stripAllFormattingCodes(nickname.toLowerCase())); + } + + /** + * Return the UUIDs of players who have nicknames containing characters provided in the nickname argument + * @param nickname The characters of the nickname to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public Optional> getPartialNicknameMatches(String nickname) { + + Set nickSet = mapNickUUID.keySet(); + nickname = stripAllFormattingCodes(nickname.toLowerCase()); + Set uuidSet = new HashSet(); + + for (String nick : nickSet) { + + if (nick.startsWith(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + for (String nick : nickSet) { + + if (nick.contains(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + try { + for (String nick : nickSet) { + + if (nick.matches(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + } catch (PatternSyntaxException e) { + /* + * Its not a valid regex, so we will just say there are no matches! + */ + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + return Optional.empty(); + + } + + /** + * Return the UUIDs of players who have names containing characters provided in the name argument + * @param name The characters of the name to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public Optional> getPartialNameMatches(String name) { + + Set nameSet = mapNameUUID.keySet(); + name = stripAllFormattingCodes(name.toLowerCase()); + Set uuidSet = new HashSet(); + + for (String n : nameSet) { + + if (n.startsWith(name)) { + uuidSet.add(mapNameUUID.get(n)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + for (String n : nameSet) { + + if (n.contains(name)) { + uuidSet.add(mapNameUUID.get(n)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + try { + for (String n : nameSet) { + + if (n.matches(name)) { + uuidSet.add(mapNameUUID.get(n)); + } + + } + } catch (PatternSyntaxException e) { + /* + * Its not a valid regex, so we will just say there are no matches! + */ + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + return Optional.empty(); + + } + + /** + * @param uuid + * @return If this player is currently online on the server + */ + public boolean isOnline(UUID uuid) { + return online.contains(uuid); + } + + /** + * Removes the nickname for a specified player + * @param uuid + */ + public void removeNickname(UUID uuid) { + + synchronized (mapUUIDNick) { + + if (!mapUUIDNick.containsKey(uuid)) { + return; + } + + String nickname = mapUUIDNick.get(uuid); + + mapUUIDNick.remove(uuid); + mapNickUUID.remove(nickname); + mapNickFormatted.remove(nickname); + + } + + } + + /** + * Save all persistent nickname data to file + * + * @param saveFile The file output stream to use + */ + public void saveNicknameData(FileOutputStream saveFile) { + + try { + + ObjectOutputStream out = new ObjectOutputStream(saveFile); + + out.writeObject(mapUUIDNick); + out.writeObject(mapUUIDName); + out.writeObject(mapNickUUID); + out.writeObject(mapNameUUID); + out.writeObject(mapNickFormatted); + out.writeObject(mapNameFormatted); + + out.close(); + Bukkit.getLogger().info("The nicknames file was successfully saved!"); + + } catch (IOException e) { + + Bukkit.getLogger().info("An error has occured writing the nicknames file!"); + e.printStackTrace(); + + } + + } + + // /** + // * Save all persistent nickname data to file + // * + // * @param configLoader Configuration file loader to use + // */ + // @SuppressWarnings("serial") + // public void SPONGE_saveNicknameData(ConfigurationLoader configLoader) { + // + // ConfigurationNode rootNode; + // + // rootNode = configLoader.createEmptyNode(); + // + // try { + // + // rootNode.getNode("nickname_uuidnick").setValue(new TypeToken>() {}, mapUUIDNick); + // rootNode.getNode("nickname_uuidname").setValue(new TypeToken>() {}, mapUUIDName); + // rootNode.getNode("nickname_nickuuid").setValue(new TypeToken>() {}, mapNickUUID); + // rootNode.getNode("nickname_nameuuid").setValue(new TypeToken>() {}, mapNameUUID); + // rootNode.getNode("nickname_nickformatted").setValue(new TypeToken>() {}, mapNickFormatted); + // rootNode.getNode("nickname_nameformatted").setValue(new TypeToken>() {}, mapNameFormatted); + // + // try { + // + // configLoader.save(rootNode); + // + // } catch (IOException e) { + // e.printStackTrace(); + // } + // + // } catch (ObjectMappingException e) { + // + // e.printStackTrace(); + // System.err.println("[MultiChatSponge] ERROR: Could not write nicknames :("); + // + // } + // + // } + + /** + * Load (or attempt to load) nickname data saved to file + * + * @param saveFile The file input stream to use + */ + @SuppressWarnings({ "unchecked" }) + public void loadNicknameData(FileInputStream saveFile) { + + try { + + ObjectInputStream in = new ObjectInputStream(saveFile); + + mapUUIDNick = (Map) in.readObject(); + mapUUIDName = (Map) in.readObject(); + mapNickUUID = (Map) in.readObject(); + mapNameUUID = (Map) in.readObject(); + mapNickFormatted = (Map) in.readObject(); + mapNameFormatted = (Map) in.readObject(); + + in.close(); + + Bukkit.getLogger().info("The nicknames file was successfully loaded!"); + + } catch (IOException|ClassNotFoundException e) { + + Bukkit.getLogger().info("An error has occured reading the nicknames file!"); + e.printStackTrace(); + + } + + } + + // /** + // * Load (or attempt to load) nickname data saved to file + // * + // * @param configLoader The configuration loader to use + // */ + // @SuppressWarnings("serial") + // public void SPONGE_loadNicknameData(ConfigurationLoader configLoader) { + // + // ConfigurationNode rootNode; + // + // try { + // + // rootNode = configLoader.load(); + // + // try { + // + // mapUUIDNick = (Map) rootNode.getNode("nickname_uuidnick").getValue(new TypeToken>() { /* EMPTY */ }); + // mapUUIDName = (Map) rootNode.getNode("nickname_uuidname").getValue(new TypeToken>() { /* EMPTY */ }); + // mapNickUUID = (Map) rootNode.getNode("nickname_nickuuid").getValue(new TypeToken>() { /* EMPTY */ }); + // mapNameUUID = (Map) rootNode.getNode("nickname_nameuuid").getValue(new TypeToken>() { /* EMPTY */ }); + // mapNickFormatted = (Map) rootNode.getNode("nickname_nickformatted").getValue(new TypeToken>() { /* EMPTY */ }); + // mapNameFormatted = (Map) rootNode.getNode("nickname_nameformatted").getValue(new TypeToken>() { /* EMPTY */ }); + // + // if (mapUUIDNick == null) mapUUIDNick = new HashMap(); + // if (mapUUIDName == null) mapUUIDName = new HashMap(); + // if (mapNickUUID == null) mapNickUUID = new HashMap(); + // if (mapNameUUID == null) mapNameUUID = new HashMap(); + // if (mapNickFormatted == null) mapNickFormatted = new HashMap(); + // if (mapNameFormatted == null) mapNameFormatted = new HashMap(); + // + // + // System.out.println("[MultiChatSponge] Nickname data loaded"); + // + // } catch (ClassCastException e) { + // + // setDefaultData(); + // + // } catch (ObjectMappingException e) { + // + // setDefaultData(); + // + // } + // + // try { + // + // configLoader.save(rootNode); + // + // } catch (IOException e) { + // + // e.printStackTrace(); + // + // } + // + // } catch (IOException e) { + // + // e.printStackTrace(); + // setDefaultData(); + // + // } + // + // } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/MultiChatSpigot.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/MultiChatSpigot.java index 5a1c2d44..0ef0dc10 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/MultiChatSpigot.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/MultiChatSpigot.java @@ -6,11 +6,13 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Queue; import java.util.Set; import java.util.UUID; @@ -22,6 +24,8 @@ import org.bukkit.plugin.java.JavaPlugin; import net.milkbowl.vault.chat.Chat; +import xyz.olivermartin.multichat.database.DatabaseManager; +import xyz.olivermartin.multichat.database.DatabaseMode; import xyz.olivermartin.multichat.spigotbridge.commands.CommandHandler; import xyz.olivermartin.multichat.spigotbridge.listeners.ChatListenerHighest; import xyz.olivermartin.multichat.spigotbridge.listeners.ChatListenerLowest; @@ -55,6 +59,8 @@ public class MultiChatSpigot extends JavaPlugin implements Listener { public static Map placeholderMap = new HashMap(); + public static Map> chatQueues = new HashMap>(); + public static Optional getVaultChat() { if (chat == null) return Optional.empty(); return Optional.of(chat); @@ -70,7 +76,7 @@ public static boolean hookedPAPI() { public static File configDir; - private static final String nameDataFile = "namedata.dat"; + public static final String nameDataFile = "namedata.dat"; private static File legacyNicknameFile; public static boolean setDisplayNameLastVal = false; @@ -89,14 +95,16 @@ public static boolean hookedPAPI() { public static String nicknamePrefix = "~"; public static List nicknameBlacklist = new ArrayList(); public static int nicknameMaxLength = 20; + public static int nicknameMinLength = 3; public static boolean nicknameLengthIncludeFormatting = false; + public static boolean nicknameSQL = false; @SuppressWarnings("unchecked") public void onEnable() { // Read nickname data - configDir = getDataFolder(); + configDir = getDataFolder().getAbsoluteFile(); legacyNicknameFile = new File(configDir, "Nicknames.dat"); if (!getDataFolder().exists()) { @@ -104,8 +112,16 @@ public void onEnable() { getDataFolder().mkdirs(); configDir = getDataFolder(); } + + String translationsDir = configDir.toString() + File.separator + "translations"; + if (!new File(translationsDir).exists()) { + getLogger().info(logPrefix + "Creating translations directory!"); + new File(translationsDir).mkdirs(); + } SpigotConfigManager.getInstance().registerHandler("spigotconfig.yml", configDir); + SpigotConfigManager.getInstance().registerHandler("spigotconfig_fr.yml", new File(translationsDir)); + Configuration config = SpigotConfigManager.getInstance().getHandler("spigotconfig.yml").getConfig(); if (config.contains("server_name")) { @@ -139,94 +155,177 @@ public void onEnable() { nicknameLengthIncludeFormatting = config.getBoolean("nickname_length_limit_formatting"); } - } + if (config.contains("nickname_length_min")) { - File f = new File(configDir, nameDataFile); + nicknameMinLength = config.getInt("nickname_length_min"); - if ((f.exists()) && (!f.isDirectory())) { + } + if (config.contains("nickname_sql")) { - getLogger().info(logPrefix + "Attempting startup load for Nicknames"); + nicknameSQL = config.getBoolean("nickname_sql"); - File file = new File(configDir, nameDataFile); - FileInputStream saveFile; - try { - saveFile = new FileInputStream(file); - NameManager.getInstance().loadNicknameData(saveFile); - } catch (FileNotFoundException e) { - getLogger().info(logPrefix + "[ERROR] Could not load nickname data"); - e.printStackTrace(); - } + if (nicknameSQL) { - getLogger().info(logPrefix + "Load completed!"); + if (config.getBoolean("mysql")) { - } else if (legacyNicknameFile.exists()) { + DatabaseManager.getInstance().setMode(DatabaseMode.MySQL); - // LEGACY NICKNAME FILE HANDLING -------------------------------------------- + DatabaseManager.getInstance().setURLMySQL(config.getString("mysql_url")); + DatabaseManager.getInstance().setUsernameMySQL(config.getString("mysql_user")); + DatabaseManager.getInstance().setPasswordMySQL(config.getString("mysql_pass")); - HashMap result = null; + try { - try { + if (config.contains("mysql_database")) { + DatabaseManager.getInstance().createDatabase("multichatspigot.db", config.getString("mysql_database")); + } else { + DatabaseManager.getInstance().createDatabase("multichatspigot.db", "multichatspigot"); + } + + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().connectToDatabase(); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().update("CREATE TABLE IF NOT EXISTS name_data(id VARCHAR(128), f_name VARCHAR(255), u_name VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().update("CREATE TABLE IF NOT EXISTS nick_data(id VARCHAR(128), u_nick VARCHAR(255), f_nick VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().disconnectFromDatabase(); - FileInputStream saveFile = new FileInputStream(legacyNicknameFile); - ObjectInputStream in = new ObjectInputStream(saveFile); - result = (HashMap) in.readObject(); - in.close(); - getLogger().info(logPrefix + "Loaded a legacy (pre 1.6) nicknames file. Attempting conversion..."); + NameManager.useSQL(nicknameSQL); - int counter = 0; + } catch (SQLException e) { + nicknameSQL = false; + NameManager.useSQL(false); + System.err.println("Could not enable database! Using files..."); + e.printStackTrace(); + } + + } else { + + DatabaseManager.getInstance().setMode(DatabaseMode.SQLite); - if (result != null) { + DatabaseManager.getInstance().setPathSQLite(configDir); - if (result.keySet() != null) { + try { - for (UUID u : result.keySet()) { + DatabaseManager.getInstance().createDatabase("multichatspigot.db"); - counter++; - NameManager.getInstance().registerOfflinePlayerByUUID(u, "NotJoinedYet"+String.valueOf(counter)); - NameManager.getInstance().setNickname(u, result.get(u)); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().connectToDatabase(); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().update("CREATE TABLE IF NOT EXISTS name_data(id VARCHAR(128), f_name VARCHAR(255), u_name VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().update("CREATE TABLE IF NOT EXISTS nick_data(id VARCHAR(128), u_nick VARCHAR(255), f_nick VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().disconnectFromDatabase(); + NameManager.useSQL(nicknameSQL); + + } catch (SQLException e) { + nicknameSQL = false; + NameManager.useSQL(false); + System.err.println("Could not enable database! Using files..."); + e.printStackTrace(); } } } + } + } + + // If we are using File Based name storage + if (NameManager.getInstance() instanceof FileNameManager) { + + File f = new File(configDir, nameDataFile); + + if ((f.exists()) && (!f.isDirectory())) { + + getLogger().info(logPrefix + "Attempting startup load for Nicknames"); + File file = new File(configDir, nameDataFile); - FileOutputStream saveFile2; + FileInputStream saveFile; try { - saveFile2 = new FileOutputStream(file); - NameManager.getInstance().saveNicknameData(saveFile2); + saveFile = new FileInputStream(file); + if (NameManager.getInstance() instanceof FileNameManager) { + ((FileNameManager)NameManager.getInstance()).loadNicknameData(saveFile); + } + } catch (FileNotFoundException e) { - getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); + getLogger().info(logPrefix + "[ERROR] Could not load nickname data"); e.printStackTrace(); } - getLogger().info(logPrefix + "The files were created!"); + getLogger().info(logPrefix + "Load completed!"); - } catch (IOException|ClassNotFoundException e) { + } else if (legacyNicknameFile.exists()) { - getLogger().info(logPrefix + "[ERROR] An error has occured reading the legacy nicknames file. Please delete it."); - e.printStackTrace(); + // LEGACY NICKNAME FILE HANDLING -------------------------------------------- - } + HashMap result = null; - } else { + try { - getLogger().info(logPrefix + "Name data files do not exist to load. Must be first startup!"); - getLogger().info(logPrefix + "Enabling Nicknames! :D"); - getLogger().info(logPrefix + "Attempting to create hash files!"); + FileInputStream saveFile = new FileInputStream(legacyNicknameFile); + ObjectInputStream in = new ObjectInputStream(saveFile); + result = (HashMap) in.readObject(); + in.close(); + getLogger().info(logPrefix + "Loaded a legacy (pre 1.6) nicknames file. Attempting conversion..."); - File file = new File(configDir, nameDataFile); - FileOutputStream saveFile; - try { - saveFile = new FileOutputStream(file); - NameManager.getInstance().saveNicknameData(saveFile); - } catch (FileNotFoundException e) { - getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); - e.printStackTrace(); - } + int counter = 0; - getLogger().info(logPrefix + "The files were created!"); + if (result != null) { + + if (result.keySet() != null) { + + for (UUID u : result.keySet()) { + + counter++; + NameManager.getInstance().registerOfflinePlayerByUUID(u, "NotJoinedYet"+String.valueOf(counter)); + NameManager.getInstance().setNickname(u, result.get(u)); + + } + + } + + } + + File file = new File(configDir, nameDataFile); + FileOutputStream saveFile2; + try { + saveFile2 = new FileOutputStream(file); + if (NameManager.getInstance() instanceof FileNameManager) { + ((FileNameManager)NameManager.getInstance()).saveNicknameData(saveFile2); + } + } catch (FileNotFoundException e) { + getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); + e.printStackTrace(); + } + + getLogger().info(logPrefix + "The files were created!"); + + } catch (IOException|ClassNotFoundException e) { + + getLogger().info(logPrefix + "[ERROR] An error has occured reading the legacy nicknames file. Please delete it."); + e.printStackTrace(); + + } + + } else { + + getLogger().info(logPrefix + "Name data files do not exist to load. Must be first startup!"); + getLogger().info(logPrefix + "Enabling Nicknames! :D"); + getLogger().info(logPrefix + "Attempting to create hash files!"); + + File file = new File(configDir, nameDataFile); + FileOutputStream saveFile; + try { + saveFile = new FileOutputStream(file); + if (NameManager.getInstance() instanceof FileNameManager) { + ((FileNameManager)NameManager.getInstance()).saveNicknameData(saveFile); + } + + } catch (FileNotFoundException e) { + getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); + e.printStackTrace(); + } + + getLogger().info(logPrefix + "The files were created!"); + + } } @@ -239,6 +338,8 @@ public void onEnable() { 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", MultiChatPluginMessageListener.getInstance()); getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:chat", MultiChatPluginMessageListener.getInstance()); getServer().getMessenger().registerIncomingPluginChannel(this, "multichat:act", MultiChatPluginMessageListener.getInstance()); @@ -262,6 +363,8 @@ public void onEnable() { this.getCommand("realname").setExecutor(CommandHandler.getInstance()); this.getCommand("username").setExecutor(CommandHandler.getInstance()); this.getCommand("multichatspigot").setExecutor(CommandHandler.getInstance()); + this.getCommand("pxe").setExecutor(CommandHandler.getInstance()); + this.getCommand("pexecute").setExecutor(CommandHandler.getInstance()); // Manage dependencies @@ -308,15 +411,28 @@ private boolean setupPAPI() { public void onDisable() { - File file = new File(configDir, nameDataFile); - FileOutputStream saveFile; - try { - saveFile = new FileOutputStream(file); - NameManager.getInstance().saveNicknameData(saveFile); - } catch (FileNotFoundException e) { - getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); - e.printStackTrace(); + if (nicknameSQL) { + try { + DatabaseManager.getInstance().getDatabase("multichatspigot.db").get().disconnectFromDatabase(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + } else { + + File file = new File(configDir, nameDataFile); + FileOutputStream saveFile; + try { + saveFile = new FileOutputStream(file); + if (NameManager.getInstance() instanceof FileNameManager) { + ((FileNameManager)NameManager.getInstance()).saveNicknameData(saveFile); + } + } catch (FileNotFoundException e) { + getLogger().info(logPrefix + "[ERROR] Could not save nickname data"); + e.printStackTrace(); + } + } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/NameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/NameManager.java index bff56e6c..efec793e 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/NameManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/NameManager.java @@ -1,22 +1,12 @@ package xyz.olivermartin.multichat.spigotbridge; -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.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.regex.Pattern; -import java.util.regex.PatternSyntaxException; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -30,50 +20,33 @@ * @author Oliver Martin (Revilo410) * */ -public class NameManager implements Listener { - +public abstract class NameManager implements Listener { + private static NameManager instance; static { - instance = new NameManager(); + instance = new FileNameManager(); } public static NameManager getInstance() { return instance; } + + public static void useSQL(boolean sql) { + if (sql) instance = new SQLNameManager(); + else instance = new FileNameManager(); + } // END OF STATIC DEFINITIONS - private Map mapUUIDNick; - private Map mapUUIDName; - private Map mapNickUUID; - private Map mapNameUUID; - - private Map mapNickFormatted; - private Map mapNameFormatted; - - private List online; + protected List online; - private NameManager() { - - setDefaultData(); + protected NameManager() { online = new ArrayList(); } - private void setDefaultData() { - - mapUUIDNick = new HashMap(); - mapUUIDName = new HashMap(); - mapNickUUID = new HashMap(); - mapNameUUID = new HashMap(); - - mapNickFormatted = new HashMap(); - mapNameFormatted = new HashMap(); - - } - /** * Returns the FORMATTED NICKNAME of a player if they have one set, otherwise returns their username * @@ -91,26 +64,7 @@ public String getCurrentName(UUID uuid) { * @param withPrefix Should the nickname prefix also be returned if it is set? * @return The NICKNAME of the player if it is set, otherwise their username */ - public String getCurrentName(UUID uuid, boolean withPrefix) { - - synchronized (mapUUIDNick) { - if (mapUUIDNick.containsKey(uuid)) { - if (MultiChatSpigot.showNicknamePrefix && withPrefix) { - return MultiChatSpigot.nicknamePrefix + mapNickFormatted.get(mapUUIDNick.get(uuid)); - } else { - return mapNickFormatted.get(mapUUIDNick.get(uuid)); - } - } - } - - synchronized (mapUUIDName) { - if (mapUUIDName.containsKey(uuid)) { - return mapNameFormatted.get(mapUUIDName.get(uuid)); - } - } - - return ""; - } + public abstract String getCurrentName(UUID uuid, boolean withPrefix); /** * Returns the username of a player @@ -118,17 +72,7 @@ public String getCurrentName(UUID uuid, boolean withPrefix) { * @param uuid The Unique ID of the player to lookup * @return The username of the player */ - public String getName(UUID uuid) { - - synchronized (mapUUIDName) { - if (mapUUIDName.containsKey(uuid)) { - return mapNameFormatted.get(mapUUIDName.get(uuid)); - } - } - - return ""; - - } + public abstract String getName(UUID uuid); /** * Gets the UUID of a player from their UNFORMATTED nickname @@ -137,19 +81,7 @@ public String getName(UUID uuid) { * @param nickname The UNFORMATTED nickname of the player * @return An optional which may contain their UUID if the nickname was found in the system */ - private Optional getUUIDFromUnformattedNickname(String nickname) { - - nickname = nickname.toLowerCase(); - - synchronized (mapNickUUID) { - if (mapNickUUID.containsKey(nickname)) { - return Optional.of(mapNickUUID.get(nickname)); - } - } - - return Optional.empty(); - - } + protected abstract Optional getUUIDFromUnformattedNickname(String nickname); /** * Returns a player's UUID given their username @@ -157,19 +89,7 @@ private Optional getUUIDFromUnformattedNickname(String nickname) { * @param username The player's username * @return An optional value which may contain their UUID if the username was found */ - public Optional getUUIDFromName(String username) { - - username = username.toLowerCase(); - - synchronized (mapNameUUID) { - if (mapNameUUID.containsKey(username)) { - return Optional.of(mapNameUUID.get(username)); - } - } - - return Optional.empty(); - - } + public abstract Optional getUUIDFromName(String username); /** * Gets a player's UUID from their nickname @@ -255,246 +175,53 @@ public Optional getFormattedNameFromName(String username) { *

Also performs any setup needed to equip nicknames etc.

* @param player */ - public void registerPlayer(Player player) { - - UUID uuid = player.getUniqueId(); - String username = player.getName(); - String oldUsername; - - synchronized (mapUUIDName) { - - if (mapUUIDName.containsKey(uuid)) { - - oldUsername = mapUUIDName.get(uuid); - - if (!oldUsername.equalsIgnoreCase(username)) { - - synchronized (mapNameUUID) { - - mapUUIDName.remove(uuid); - mapUUIDName.put(uuid, username.toLowerCase()); - mapNameUUID.remove(oldUsername); - mapNameUUID.put(username.toLowerCase(), uuid); - - } - - } - - mapNameFormatted.remove(oldUsername); - mapNameFormatted.put(username.toLowerCase(), username); - - } else { - - synchronized (mapNameUUID) { - - mapUUIDName.put(uuid, username.toLowerCase()); - mapNameUUID.put(username.toLowerCase(), uuid); - mapNameFormatted.put(username.toLowerCase(), username); - - } - - } - - } - - online.add(uuid); - Bukkit.getLogger().info("[+] " + username + " has joined this server."); - - } + public abstract void registerPlayer(Player player); /** * Register a player into the system without them being online *

Used mainly for legacy conversion of old nickname file

* @param uuid Player's UUID */ - public void registerOfflinePlayerByUUID(UUID uuid, String username) { - - synchronized (mapUUIDName) { - - if (mapUUIDName.containsKey(uuid)) { - - /* - * EMPTY : Player does not need registering - */ - - } else { - - synchronized (mapNameUUID) { - - mapUUIDName.put(uuid, username.toLowerCase()); - mapNameUUID.put(username.toLowerCase(), uuid); - mapNameFormatted.put(username.toLowerCase(), username); - - } - - } - - } - - } + public abstract void registerOfflinePlayerByUUID(UUID uuid, String username); /** * Register a player as offline * @param player */ - public void unregisterPlayer(Player player) { - - online.remove(player.getUniqueId()); - Bukkit.getLogger().info("[-] " + player.getName() + " has left this server."); - - } + public abstract void unregisterPlayer(Player player); /** * Set the nickname of a player * @param uuid * @param nickname */ - public void setNickname(UUID uuid, String nickname) { - - if (!mapUUIDName.containsKey(uuid)) { - return; - } - - if (mapUUIDNick.containsKey(uuid)) { - removeNickname(uuid); - } - - String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); - - synchronized (mapNickUUID) { - - // Check for duplicates - if (mapNickUUID.containsKey(unformattedNickname)) { - if (mapNickUUID.get(unformattedNickname) != uuid) { - return; - } - } - - mapUUIDNick.put(uuid, unformattedNickname); - mapNickUUID.put(unformattedNickname, uuid); - mapNickFormatted.put(unformattedNickname, nickname); - - } - - } + public abstract void setNickname(UUID uuid, String nickname); /** * @param username * @return If this player has logged into the server before */ - public boolean existsPlayer(String username) { - return mapNameUUID.containsKey(username.toLowerCase()); - } + public abstract boolean existsPlayer(String username); /** * @param nickname * @return If this nickname is currently in use */ - public boolean existsNickname(String nickname) { - return mapNickUUID.containsKey(stripAllFormattingCodes(nickname.toLowerCase())); - } + public abstract boolean existsNickname(String nickname); /** * Return the UUIDs of players who have nicknames containing characters provided in the nickname argument * @param nickname The characters of the nickname to check * @return An optional which might contain a players UUID if a partial match was found */ - public Optional> getPartialNicknameMatches(String nickname) { - - Set nickSet = mapNickUUID.keySet(); - nickname = stripAllFormattingCodes(nickname.toLowerCase()); - Set uuidSet = new HashSet(); - - for (String nick : nickSet) { - - if (nick.startsWith(nickname)) { - uuidSet.add(mapNickUUID.get(nick)); - } - - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - for (String nick : nickSet) { - - if (nick.contains(nickname)) { - uuidSet.add(mapNickUUID.get(nick)); - } - - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - try { - for (String nick : nickSet) { - - if (nick.matches(nickname)) { - uuidSet.add(mapNickUUID.get(nick)); - } - - } - } catch (PatternSyntaxException e) { - /* - * Its not a valid regex, so we will just say there are no matches! - */ - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - return Optional.empty(); - - } + public abstract Optional> getPartialNicknameMatches(String nickname); /** * Return the UUIDs of players who have names containing characters provided in the name argument * @param name The characters of the name to check * @return An optional which might contain a players UUID if a partial match was found */ - public Optional> getPartialNameMatches(String name) { - - Set nameSet = mapNameUUID.keySet(); - name = stripAllFormattingCodes(name.toLowerCase()); - Set uuidSet = new HashSet(); - - for (String n : nameSet) { - - if (n.startsWith(name)) { - uuidSet.add(mapNameUUID.get(n)); - } - - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - for (String n : nameSet) { - - if (n.contains(name)) { - uuidSet.add(mapNameUUID.get(n)); - } - - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - try { - for (String n : nameSet) { - - if (n.matches(name)) { - uuidSet.add(mapNameUUID.get(n)); - } - - } - } catch (PatternSyntaxException e) { - /* - * Its not a valid regex, so we will just say there are no matches! - */ - } - - if (!uuidSet.isEmpty()) return Optional.of(uuidSet); - - return Optional.empty(); - - } + public abstract Optional> getPartialNameMatches(String name); /** * @param uuid @@ -508,185 +235,7 @@ public boolean isOnline(UUID uuid) { * Removes the nickname for a specified player * @param uuid */ - public void removeNickname(UUID uuid) { - - synchronized (mapUUIDNick) { - - if (!mapUUIDNick.containsKey(uuid)) { - return; - } - - String nickname = mapUUIDNick.get(uuid); - - mapUUIDNick.remove(uuid); - mapNickUUID.remove(nickname); - mapNickFormatted.remove(nickname); - - } - - } - - /** - * Save all persistent nickname data to file - * - * @param saveFile The file output stream to use - */ - public void saveNicknameData(FileOutputStream saveFile) { - - try { - - ObjectOutputStream out = new ObjectOutputStream(saveFile); - - out.writeObject(mapUUIDNick); - out.writeObject(mapUUIDName); - out.writeObject(mapNickUUID); - out.writeObject(mapNameUUID); - out.writeObject(mapNickFormatted); - out.writeObject(mapNameFormatted); - - out.close(); - Bukkit.getLogger().info("The nicknames file was successfully saved!"); - - } catch (IOException e) { - - Bukkit.getLogger().info("An error has occured writing the nicknames file!"); - e.printStackTrace(); - - } - - } - - // /** - // * Save all persistent nickname data to file - // * - // * @param configLoader Configuration file loader to use - // */ - // @SuppressWarnings("serial") - // public void SPONGE_saveNicknameData(ConfigurationLoader configLoader) { - // - // ConfigurationNode rootNode; - // - // rootNode = configLoader.createEmptyNode(); - // - // try { - // - // rootNode.getNode("nickname_uuidnick").setValue(new TypeToken>() {}, mapUUIDNick); - // rootNode.getNode("nickname_uuidname").setValue(new TypeToken>() {}, mapUUIDName); - // rootNode.getNode("nickname_nickuuid").setValue(new TypeToken>() {}, mapNickUUID); - // rootNode.getNode("nickname_nameuuid").setValue(new TypeToken>() {}, mapNameUUID); - // rootNode.getNode("nickname_nickformatted").setValue(new TypeToken>() {}, mapNickFormatted); - // rootNode.getNode("nickname_nameformatted").setValue(new TypeToken>() {}, mapNameFormatted); - // - // try { - // - // configLoader.save(rootNode); - // - // } catch (IOException e) { - // e.printStackTrace(); - // } - // - // } catch (ObjectMappingException e) { - // - // e.printStackTrace(); - // System.err.println("[MultiChatSponge] ERROR: Could not write nicknames :("); - // - // } - // - // } - - /** - * Load (or attempt to load) nickname data saved to file - * - * @param saveFile The file input stream to use - */ - @SuppressWarnings({ "unchecked" }) - public void loadNicknameData(FileInputStream saveFile) { - - try { - - ObjectInputStream in = new ObjectInputStream(saveFile); - - mapUUIDNick = (Map) in.readObject(); - mapUUIDName = (Map) in.readObject(); - mapNickUUID = (Map) in.readObject(); - mapNameUUID = (Map) in.readObject(); - mapNickFormatted = (Map) in.readObject(); - mapNameFormatted = (Map) in.readObject(); - - in.close(); - - Bukkit.getLogger().info("The nicknames file was successfully loaded!"); - - } catch (IOException|ClassNotFoundException e) { - - Bukkit.getLogger().info("An error has occured reading the nicknames file!"); - e.printStackTrace(); - - } - - } - - // /** - // * Load (or attempt to load) nickname data saved to file - // * - // * @param configLoader The configuration loader to use - // */ - // @SuppressWarnings("serial") - // public void SPONGE_loadNicknameData(ConfigurationLoader configLoader) { - // - // ConfigurationNode rootNode; - // - // try { - // - // rootNode = configLoader.load(); - // - // try { - // - // mapUUIDNick = (Map) rootNode.getNode("nickname_uuidnick").getValue(new TypeToken>() { /* EMPTY */ }); - // mapUUIDName = (Map) rootNode.getNode("nickname_uuidname").getValue(new TypeToken>() { /* EMPTY */ }); - // mapNickUUID = (Map) rootNode.getNode("nickname_nickuuid").getValue(new TypeToken>() { /* EMPTY */ }); - // mapNameUUID = (Map) rootNode.getNode("nickname_nameuuid").getValue(new TypeToken>() { /* EMPTY */ }); - // mapNickFormatted = (Map) rootNode.getNode("nickname_nickformatted").getValue(new TypeToken>() { /* EMPTY */ }); - // mapNameFormatted = (Map) rootNode.getNode("nickname_nameformatted").getValue(new TypeToken>() { /* EMPTY */ }); - // - // if (mapUUIDNick == null) mapUUIDNick = new HashMap(); - // if (mapUUIDName == null) mapUUIDName = new HashMap(); - // if (mapNickUUID == null) mapNickUUID = new HashMap(); - // if (mapNameUUID == null) mapNameUUID = new HashMap(); - // if (mapNickFormatted == null) mapNickFormatted = new HashMap(); - // if (mapNameFormatted == null) mapNameFormatted = new HashMap(); - // - // - // System.out.println("[MultiChatSponge] Nickname data loaded"); - // - // } catch (ClassCastException e) { - // - // setDefaultData(); - // - // } catch (ObjectMappingException e) { - // - // setDefaultData(); - // - // } - // - // try { - // - // configLoader.save(rootNode); - // - // } catch (IOException e) { - // - // e.printStackTrace(); - // - // } - // - // } catch (IOException e) { - // - // e.printStackTrace(); - // setDefaultData(); - // - // } - // - // } + public abstract void removeNickname(UUID uuid); /* * Remove all colour / format codes from a string (using the '&' char) diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SQLNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SQLNameManager.java new file mode 100644 index 00000000..5696da6b --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SQLNameManager.java @@ -0,0 +1,676 @@ +package xyz.olivermartin.multichat.spigotbridge; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import xyz.olivermartin.multichat.database.DatabaseManager; +import xyz.olivermartin.multichat.database.GenericDatabase; + +public class SQLNameManager extends NameManager { + + private boolean connected; + private GenericDatabase spigotdatabase; + + public SQLNameManager() { + + super(); + + connected = getDatabase(); + + } + + private boolean getDatabase() { + + Optional ogdb = DatabaseManager.getInstance().getDatabase("multichatspigot.db"); + if (ogdb.isPresent()) { + spigotdatabase = ogdb.get(); + return true; + } else { + return false; + } + + } + + @Override + public String getCurrentName(UUID uuid, boolean withPrefix) { + + if (connected) { + + try { + + String name; + + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + ResultSet results = spigotdatabase.query("SELECT f_name, f_nick FROM name_data LEFT JOIN nick_data ON name_data.id = nick_data.id WHERE name_data.id = '" + uuid.toString() + "';"); + results.next(); + if (results.getString("f_nick") == null) { + name = results.getString("f_name"); + } else { + name = results.getString("f_nick"); + } + //spigotdatabase.disconnectFromDatabase(); + } + + if (MultiChatSpigot.showNicknamePrefix && withPrefix) { + return MultiChatSpigot.nicknamePrefix + name; + } else { + return name; + } + + } catch (SQLException e) { + e.printStackTrace(); + return ""; + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return ""; + } + + } + + @Override + public String getName(UUID uuid) { + + if (connected) { + + try { + String name; + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + ResultSet results = spigotdatabase.query("SELECT f_name FROM name_data WHERE id = '" + uuid.toString() + "';"); + results.next(); + name = results.getString("f_name"); + //spigotdatabase.disconnectFromDatabase(); + } + + return name; + + } catch (SQLException e) { + e.printStackTrace(); + return ""; + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return ""; + } + + } + + @Override + protected Optional getUUIDFromUnformattedNickname(String nickname) { + + nickname = nickname.toLowerCase(); + + if (connected) { + + try { + + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + ResultSet results = spigotdatabase.query("SELECT id FROM nick_data WHERE u_nick = '" + nickname + "';"); + if (results.next()) { + UUID id = UUID.fromString(results.getString("id")); + //spigotdatabase.disconnectFromDatabase(); + return Optional.of(id); + } else { + //spigotdatabase.disconnectFromDatabase(); + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + } + + @Override + public Optional getUUIDFromName(String username) { + + username = username.toLowerCase(); + + if (connected) { + + try { + + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + ResultSet results = spigotdatabase.query("SELECT id FROM name_data WHERE u_name = '" + username + "';"); + if (results.next() ) { + UUID id = UUID.fromString(results.getString("id")); + //spigotdatabase.disconnectFromDatabase(); + return Optional.of(id); + } else { + //spigotdatabase.disconnectFromDatabase(); + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + } + + @Override + public void registerPlayer(Player player) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + UUID uuid = player.getUniqueId(); + String username = player.getName(); + String oldUsername; + + if (existsUUID(uuid)) { + + oldUsername = getName(uuid); + + if (!oldUsername.equalsIgnoreCase(username)) { + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("UPDATE name_data SET u_name = '" + username.toLowerCase() + "', f_name = '" + username + "' WHERE id = '" + uuid.toString() + "';"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } else { + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase()+ "');"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + online.add(uuid); + Bukkit.getLogger().info("[+] " + username + " has joined this server."); + + } + + public void testRegisterFakePlayer(UUID uuid, String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + String oldUsername; + + if (existsUUID(uuid)) { + + oldUsername = getName(uuid); + + if (!oldUsername.equalsIgnoreCase(username)) { + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("UPDATE name_data SET u_name = '" + username.toLowerCase() + "', f_name = '" + username + "' WHERE id = '" + uuid.toString() + "';"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } else { + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase() + "');"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + online.add(uuid); + + } + + public boolean existsUUID(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT id FROM name_data WHERE id = '" + uuid.toString() + "';"); + if (results.next()) { //TODO fixed this line... + //spigotdatabase.disconnectFromDatabase(); + return true; + } else { + //spigotdatabase.disconnectFromDatabase(); + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public boolean hasNickname(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT id FROM nick_data WHERE id = '" + uuid.toString() + "';"); + if (results.next()) { //TODO fixed this line... + //spigotdatabase.disconnectFromDatabase(); + return true; + } else { + //spigotdatabase.disconnectFromDatabase(); + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public void registerMigratedPlayer(UUID uuid, String name, String formattedName, String nick, String formattedNick) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + // TODO remove debug + //System.out.println(name + "," + formattedName + "," + (nick == null ? "NULL!!!" : nick) + "," + (formattedNick == null ? "NULL!!!" : formattedNick) ); + + boolean setNick = (nick != null); + + // TODO remove debug + //System.out.println("SETNICK: " + setNick); + + if (existsUUID(uuid)) { + + synchronized (spigotdatabase) { + + try { + spigotdatabase.connectToDatabase(); + spigotdatabase.update("UPDATE name_data SET f_name = '" + formattedName + "', u_name = '" + name + "' WHERE id = '" + uuid.toString() + "';"); + + if (setNick) { + + if (hasNickname(uuid)) { + spigotdatabase.update("UPDATE nick_data SET u_nick = '" + nick + "', f_nick = '" + formattedNick + "' WHERE id = '" + uuid.toString() + "';"); + } else { + spigotdatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + nick + "', '" + formattedNick + "');"); + } + + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + } else { + + try { + synchronized (spigotdatabase) { + + spigotdatabase.connectToDatabase(); + spigotdatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + formattedName + "', '" + name + "');"); + + if (setNick) { + spigotdatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + nick + "', '" + formattedNick + "');"); + } + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } + + @Override + public void registerOfflinePlayerByUUID(UUID uuid, String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (existsUUID(uuid)) { + + /* + * EMPTY : Player does not need registering + */ + + } else { + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase() + "');"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } + + @Override + public void unregisterPlayer(Player player) { + + online.remove(player.getUniqueId()); + Bukkit.getLogger().info("[-] " + player.getName() + " has left this server."); + + } + + @Override + public void setNickname(UUID uuid, String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (!existsUUID(uuid)) { + return; + } + + String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + + if (otherPlayerHasNickname(unformattedNickname, uuid)) { + return; + } + + try { + synchronized (spigotdatabase) { + + if (hasNickname(uuid)) { + spigotdatabase.connectToDatabase(); + spigotdatabase.update("UPDATE nick_data SET u_nick = '" + unformattedNickname + "', f_nick = '" + nickname + "' WHERE id = '" + uuid.toString() + "';"); + } else { + spigotdatabase.connectToDatabase(); + spigotdatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + unformattedNickname + "', '" + nickname + "');"); + } + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + @Override + public boolean existsPlayer(String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT u_name FROM name_data WHERE u_name = '" + username.toLowerCase() + "';"); + if (results.next()) { + //spigotdatabase.disconnectFromDatabase(); + return true; + } else { + //spigotdatabase.disconnectFromDatabase(); + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + @Override + public boolean existsNickname(String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT u_nick FROM nick_data WHERE u_nick = '" + stripAllFormattingCodes(nickname.toLowerCase()) + "';"); + if (results.next()) { + //spigotdatabase.disconnectFromDatabase(); + return true; + } else { + //spigotdatabase.disconnectFromDatabase(); + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public boolean otherPlayerHasNickname(String nickname, UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT id, u_nick FROM nick_data WHERE u_nick = '" + stripAllFormattingCodes(nickname.toLowerCase()) + "';"); + if (results.next()) { + if (results.getString("id").equals(uuid.toString())) { + //spigotdatabase.disconnectFromDatabase(); + return false; + } else { + //spigotdatabase.disconnectFromDatabase(); + return true; + } + } else { + //spigotdatabase.disconnectFromDatabase(); + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + @Override + public Optional> getPartialNicknameMatches(String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT id FROM nick_data WHERE (u_nick LIKE '%" + stripAllFormattingCodes(nickname.toLowerCase()) + "%');"); + if (results.next()) { + Set uuids = new HashSet(); + uuids.add(UUID.fromString(results.getString("id"))); + + while (results.next()) { + uuids.add(UUID.fromString(results.getString("id"))); + } + + //spigotdatabase.disconnectFromDatabase(); + return Optional.of(uuids); + } else { + //spigotdatabase.disconnectFromDatabase(); + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } + + @Override + public Optional> getPartialNameMatches(String name) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + try { + synchronized (spigotdatabase) { + spigotdatabase.connectToDatabase(); + + ResultSet results = spigotdatabase.query("SELECT id, f_name FROM name_data WHERE (u_name LIKE '%" + name.toLowerCase() + "%');"); + if (results.next()) { + Set uuids = new HashSet(); + uuids.add(UUID.fromString(results.getString("id"))); + + while (results.next()) { + uuids.add(UUID.fromString(results.getString("id"))); + } + + //spigotdatabase.disconnectFromDatabase(); + return Optional.of(uuids); + } else { + //spigotdatabase.disconnectFromDatabase(); + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } + + @Override + public void removeNickname(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (!existsUUID(uuid)) { + return; + } + + try { + + synchronized (spigotdatabase) { + + if (!hasNickname(uuid)) { + return; + } + + spigotdatabase.connectToDatabase(); + + spigotdatabase.update("DELETE FROM nick_data WHERE id = '" + uuid.toString() + "';"); + + //spigotdatabase.disconnectFromDatabase(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SpigotCommunicationManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SpigotCommunicationManager.java index 88de0ac4..44210aa8 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SpigotCommunicationManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/SpigotCommunicationManager.java @@ -26,6 +26,37 @@ private SpigotCommunicationManager() { /* Empty */ } + public void sendProxyExecuteMessage(String command) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + out.writeUTF(command); + } catch (IOException e) { + e.printStackTrace(); + } + + ((PluginMessageRecipient)Bukkit.getServer().getOnlinePlayers().toArray()[0]).sendPluginMessage(Bukkit.getPluginManager().getPlugin(MultiChatSpigot.pluginName), "multichat:pxe", stream.toByteArray()); + + } + + public void sendProxyExecutePlayerMessage(String command, String player) { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + + try { + out.writeUTF(command); + out.writeUTF(player); + } catch (IOException e) { + e.printStackTrace(); + } + + ((PluginMessageRecipient)Bukkit.getServer().getOnlinePlayers().toArray()[0]).sendPluginMessage(Bukkit.getPluginManager().getPlugin(MultiChatSpigot.pluginName), "multichat:ppxe", stream.toByteArray()); + + } + public void sendPluginChannelMessage(String channel, UUID uuid, String message) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/commands/CommandHandler.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/commands/CommandHandler.java index 9bd33a02..ed926179 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/commands/CommandHandler.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/commands/CommandHandler.java @@ -1,5 +1,11 @@ package xyz.olivermartin.multichat.spigotbridge.commands; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Map; +import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -14,9 +20,12 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; +import xyz.olivermartin.multichat.spigotbridge.FileNameManager; import xyz.olivermartin.multichat.spigotbridge.MetaManager; import xyz.olivermartin.multichat.spigotbridge.MultiChatSpigot; import xyz.olivermartin.multichat.spigotbridge.NameManager; +import xyz.olivermartin.multichat.spigotbridge.SQLNameManager; +import xyz.olivermartin.multichat.spigotbridge.SpigotCommunicationManager; import xyz.olivermartin.multichat.spigotbridge.SpigotConfigManager; public class CommandHandler implements CommandExecutor { @@ -87,6 +96,11 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, MultiChatSpigot.nicknameLengthIncludeFormatting = config.getBoolean("nickname_length_limit_formatting"); } + if (config.contains("nickname_length_min")) { + + MultiChatSpigot.nicknameMinLength = config.getInt("nickname_length_min"); + + } } commandSender.sendMessage(ChatColor.GREEN + "The plugin has been reloaded!"); @@ -98,11 +112,163 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, return true; } + } else if (args[0].equalsIgnoreCase("migratetosql")) { + + if (commandSender instanceof Player) { + + commandSender.sendMessage(ChatColor.DARK_RED + "This command can only be executed from the server console for security reasons!"); + return true; + + } else { + + if (! (NameManager.getInstance() instanceof SQLNameManager)) { + commandSender.sendMessage(ChatColor.DARK_RED + "This command can only be used in SQL mode!"); + return true; + } + + File f = new File(MultiChatSpigot.configDir, MultiChatSpigot.nameDataFile); + FileNameManager fnm = new FileNameManager(); + + if ((f.exists()) && (!f.isDirectory())) { + + commandSender.sendMessage(ChatColor.GREEN + "Starting load of nickname file data..."); + + File file = new File(MultiChatSpigot.configDir, MultiChatSpigot.nameDataFile); + FileInputStream saveFile; + try { + saveFile = new FileInputStream(file); + fnm.loadNicknameData(saveFile); + commandSender.sendMessage(ChatColor.GREEN + "Successfully loaded nickname data..."); + + Map mapUUIDName = fnm.getMapUUIDName(); + Map mapUUIDNick = fnm.getMapUUIDNick(); + Map mapNameFormatted = fnm.getMapNameFormatted(); + Map mapNickFormatted = fnm.getMapNickFormatted(); + + commandSender.sendMessage(ChatColor.GREEN + "Starting migration"); + + int count = 0; + int max = mapUUIDName.size(); + int checkcount = 25; + int checkpoint = checkcount/100*max; + + for (Entry entry : mapUUIDName.entrySet()) { + + count++; + if (count > checkpoint) { + commandSender.sendMessage(ChatColor.GREEN + "Completed " + checkcount + "% of migration..."); + checkcount += 25; + checkpoint = checkcount/100*max; + } + + UUID uuid = entry.getKey(); + String name = entry.getValue(); + String formattedName = mapNameFormatted.get(name); + String nick; + String formattedNick; + if (mapUUIDNick.containsKey(uuid)) { + nick = mapUUIDNick.get(uuid); + formattedNick = mapNickFormatted.get(nick); + if (formattedNick.equals(formattedName)) { + nick = null; + formattedNick = null; + } + } else { + nick = null; + formattedNick = null; + } + + + + ((SQLNameManager)NameManager.getInstance()).registerMigratedPlayer(uuid, name, formattedName, nick, formattedNick); + + } + + commandSender.sendMessage(ChatColor.GREEN + "Successfully migrated: " + max + " records"); + + commandSender.sendMessage(ChatColor.GREEN + "Saving nickname data file..."); + + FileOutputStream saveFile2 = new FileOutputStream(file); + fnm.saveNicknameData(saveFile2); + + } catch (FileNotFoundException e) { + commandSender.sendMessage(ChatColor.DARK_RED + "[ERROR] Could not load nickname data!"); + e.printStackTrace(); + } + + } + + return true; + + } + } else { // Show usage return false; } + } else if (cmd.getName().equalsIgnoreCase("pxe") || cmd.getName().equalsIgnoreCase("pexecute")) { + + + /* PROXY EXECUTE */ + + // Show usage + if (args.length < 1) { + + return false; + + } else { + + boolean playerFlag = false; + String player = ".*"; + + // Handle flags + int index = 0; + + while (index < args.length) { + + if (args[index].equalsIgnoreCase("-p")) { + if (index+1 < args.length) { + playerFlag = true; + player = args[index+1]; + } + } else { + break; + } + + index = index+2; + + } + + if (index >= args.length) { + return false; // Show usage + } + + String message = ""; + for (String arg : args) { + if (index > 0) { + index--; + } else { + message = message + arg + " "; + } + } + + if (playerFlag) { + + SpigotCommunicationManager.getInstance().sendProxyExecutePlayerMessage(message, player); + + } else { + + SpigotCommunicationManager.getInstance().sendProxyExecuteMessage(message); + + } + + commandSender.sendMessage(ChatColor.GREEN + "SENT COMMAND TO PROXY SERVER"); + + return true; + + } + } if (cmd.getName().equalsIgnoreCase("nick")) { @@ -150,19 +316,28 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, if (MultiChatSpigot.nicknameLengthIncludeFormatting) { // Include formatting codes in the nickname length if (args[0].length() > MultiChatSpigot.nicknameMaxLength && !sender.hasPermission("multichatspigot.nick.anylength")) { - sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too long, max " + MultiChatSpigot.nicknameMaxLength + " characters! (Including format codes)"); return true; - + } + if (args[0].length() < MultiChatSpigot.nicknameMinLength && !sender.hasPermission("multichatspigot.nick.anylength")) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too short, min " + MultiChatSpigot.nicknameMinLength + " characters! (Including format codes)"); + return true; } } else { // Do not include formatting codes in the nickname length if (NameManager.getInstance().stripAllFormattingCodes(args[0]).length() > MultiChatSpigot.nicknameMaxLength && !sender.hasPermission("multichatspigot.nick.anylength")) { - sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too long, max " + MultiChatSpigot.nicknameMaxLength + " characters! (Excluding format codes)"); return true; - } + if (NameManager.getInstance().stripAllFormattingCodes(args[0]).length() < MultiChatSpigot.nicknameMinLength && !sender.hasPermission("multichatspigot.nick.anylength")) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too short, min " + MultiChatSpigot.nicknameMinLength + " characters! (Excluding format codes)"); + return true; + } + } + + if (NameManager.getInstance().stripAllFormattingCodes(args[0]).length() < 1) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname cannot be empty!"); + return true; } String targetNickname = NameManager.getInstance().stripAllFormattingCodes(NameManager.getInstance().getCurrentName(targetUUID)); @@ -187,7 +362,7 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, if (NameManager.getInstance().stripAllFormattingCodes(args[0]).matches(bl)) blacklisted = true; } - if (blacklisted) { + if (blacklisted && !sender.hasPermission("multichatspigot.nick.blacklist")) { sender.sendMessage(ChatColor.DARK_RED + "Sorry, this name is not allowed!"); return true; @@ -245,32 +420,41 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, if (MultiChatSpigot.nicknameLengthIncludeFormatting) { // Include formatting codes in the nickname length if (args[1].length() > MultiChatSpigot.nicknameMaxLength && !sender.hasPermission("multichatspigot.nick.anylength")) { - sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too long, max " + MultiChatSpigot.nicknameMaxLength + " characters! (Including format codes)"); return true; - + } + if (args[1].length() < MultiChatSpigot.nicknameMinLength && !sender.hasPermission("multichatspigot.nick.anylength")) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too short, min " + MultiChatSpigot.nicknameMinLength + " characters! (Including format codes)"); + return true; } } else { // Do not include formatting codes in the nickname length if (NameManager.getInstance().stripAllFormattingCodes(args[1]).length() > MultiChatSpigot.nicknameMaxLength && !sender.hasPermission("multichatspigot.nick.anylength")) { - sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too long, max " + MultiChatSpigot.nicknameMaxLength + " characters! (Excluding format codes)"); return true; - + } + if (NameManager.getInstance().stripAllFormattingCodes(args[1]).length() < MultiChatSpigot.nicknameMinLength && !sender.hasPermission("multichatspigot.nick.anylength")) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname is too short, min " + MultiChatSpigot.nicknameMinLength + " characters! (Excluding format codes)"); + return true; } } + if (NameManager.getInstance().stripAllFormattingCodes(args[1]).length() < 1) { + sender.sendMessage(ChatColor.DARK_RED + "Sorry your nickname cannot be empty!"); + return true; + } + String targetNickname = NameManager.getInstance().stripAllFormattingCodes(NameManager.getInstance().getCurrentName(targetUUID)); String targetName = NameManager.getInstance().getName(targetUUID); - if (NameManager.getInstance().existsNickname(args[1]) && !targetNickname.equalsIgnoreCase(NameManager.getInstance().stripAllFormattingCodes(args[0])) ) { //&& !sender.hasPermission("multichatspigot.nick.duplicate")) { + if (NameManager.getInstance().existsNickname(args[1]) && !targetNickname.equalsIgnoreCase(NameManager.getInstance().stripAllFormattingCodes(args[1])) ) { //&& !sender.hasPermission("multichatspigot.nick.duplicate")) { sender.sendMessage(ChatColor.DARK_RED + "Sorry, this nickname is already in use!"); return true; } - if (NameManager.getInstance().existsPlayer(args[1]) && !targetName.equalsIgnoreCase(NameManager.getInstance().stripAllFormattingCodes(args[0])) && !sender.hasPermission("multichatspigot.nick.impersonate")) { + if (NameManager.getInstance().existsPlayer(args[1]) && !targetName.equalsIgnoreCase(NameManager.getInstance().stripAllFormattingCodes(args[1])) && !sender.hasPermission("multichatspigot.nick.impersonate")) { sender.sendMessage(ChatColor.DARK_RED + "Sorry, a player already exists with this name!"); return true; @@ -282,7 +466,7 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, if (NameManager.getInstance().stripAllFormattingCodes(args[1]).matches(bl)) blacklisted = true; } - if (blacklisted) { + if (blacklisted && !sender.hasPermission("multichatspigot.nick.blacklist")) { sender.sendMessage(ChatColor.DARK_RED + "Sorry, this name is not allowed!"); return true; @@ -438,7 +622,7 @@ public boolean onCommand(CommandSender commandSender, Command cmd, String label, } - } + } return false; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseManager.java deleted file mode 100644 index 31de05a7..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseManager.java +++ /dev/null @@ -1,99 +0,0 @@ -package xyz.olivermartin.multichat.spigotbridge.database; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/* - * DROP TABLE IF EXISTS nicknames; - -CREATE TABLE nicknames(id VARCHAR(128) PRIMARY KEY, u_nick VARCHAR(255), f_nick VARCHAR(255)); - -INSERT INTO nicknames VALUES ('255-444-2221--11-11', 'revilo', '&4Revilo'); - -SELECT * FROM nicknames; - */ - -public class DatabaseManager { - - private static DatabaseManager instance; - - public static DatabaseManager getInstance() { - return instance; - } - - static { - instance = new DatabaseManager(); - } - - /* END STATIC */ - - private File databasePath; - private DatabaseMode databaseMode = DatabaseMode.SQLite; - - private Map databases; - - private DatabaseManager() { - databases = new HashMap(); - } - - //////////// - - public static void main(String args[]) { - DatabaseManager.getInstance().setPath(new File("C:\\multichat\\db\\")); - DatabaseManager.getInstance().createDatabase("testing.db"); - } - - //////////// - - public void setPath(File path) { - this.databasePath = path; - } - - public GenericDatabase createDatabase(String name) { - return createDatabase(name, name); - } - - public boolean isReady() { - return databasePath != null; - } - - /** - * Generic class to create a sqlite database - */ - public GenericDatabase createDatabase(String databaseName, String fileName) { - - if (!isReady()) throw new RuntimeException("MultiChat Database Manager Not Ready!"); - - if (!databasePath.exists()) { - databasePath.mkdirs(); - } - - switch (databaseMode) { - case SQLite: - default: - // TODO check doesnt already exist - databases.put(databaseName.toLowerCase(), new SQLiteDatabase(databasePath, fileName)); - return databases.get(databaseName.toLowerCase()); - } - - } - - public Optional getDatabase(String databaseName) { - if (databases.containsKey(databaseName.toLowerCase())) { - return Optional.of(databases.get(databaseName.toLowerCase())); - } else { - return Optional.empty(); - } - } - - public void removeDatabase(String databaseName) { - if (databases.containsKey(databaseName.toLowerCase())) { - GenericDatabase gdb = databases.get(databaseName.toLowerCase()); - gdb.disconnectFromDatabase(); - databases.remove(databaseName.toLowerCase()); - } - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseMode.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseMode.java deleted file mode 100644 index 1696d475..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/DatabaseMode.java +++ /dev/null @@ -1,7 +0,0 @@ -package xyz.olivermartin.multichat.spigotbridge.database; - -public enum DatabaseMode { - - SQLite - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/GenericDatabase.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/GenericDatabase.java deleted file mode 100644 index 2d31261d..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/GenericDatabase.java +++ /dev/null @@ -1,36 +0,0 @@ -package xyz.olivermartin.multichat.spigotbridge.database; - -public abstract class GenericDatabase { - - protected String url; - private boolean ready; - - public GenericDatabase(String url) { - this.url = url; - ready = setupDatabase(url); - } - - public String getURL() { - return this.url; - } - - public boolean isReady() { - return this.ready; - } - - protected abstract boolean setupDatabase(String url); - - protected abstract void disconnect(); - - protected abstract boolean connect(); - - public void connectToDatabase() { - this.ready = connect(); - } - - public void disconnectFromDatabase() { - disconnect(); - this.ready = false; - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/SQLiteDatabase.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/SQLiteDatabase.java deleted file mode 100644 index 4eeff0a3..00000000 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/database/SQLiteDatabase.java +++ /dev/null @@ -1,78 +0,0 @@ -package xyz.olivermartin.multichat.spigotbridge.database; - -import java.io.File; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class SQLiteDatabase extends GenericDatabase { - - private static final String URL_PREFIX = "jdbc:sqlite:"; - private Connection conn; - - public SQLiteDatabase(File path, String filename) { - super(URL_PREFIX + path + File.separator + filename); - } - - protected boolean setupDatabase(String url) { - - try (Connection conn = DriverManager.getConnection(url)) { - - if (conn != null) { - DatabaseMetaData meta = conn.getMetaData(); - System.out.println("The driver name is " + meta.getDriverName()); - System.out.println("A new database has been created."); - - this.conn = conn; - - // Database successfully created - return true; - } - - } catch (SQLException e) { - System.out.println(e.getMessage()); - } - - // Database not successfully created - return false; - - } - - @Override - protected void disconnect() { - - if (conn != null) { - try { - if (!conn.isClosed()) { - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - } - - @Override - protected boolean connect() { - - if (conn == null) { - - return setupDatabase(url); - - } else { - try { - if (conn.isClosed()) { - return setupDatabase(url); - } - } catch (SQLException e) { - return false; - } - } - - // Already connected - return true; - } - -} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerHighest.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerHighest.java index 33e40d5d..6eccf554 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerHighest.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerHighest.java @@ -57,6 +57,15 @@ public void onChat(final AsyncPlayerChatEvent event) { String channelName = MultiChatSpigot.playerChannels.get(event.getPlayer()); + // HACK for /local and /global + + if (MultiChatSpigot.chatQueues.containsKey(event.getPlayer().getName().toLowerCase())) { + String tempChannel = MultiChatSpigot.chatQueues.get(event.getPlayer().getName().toLowerCase()).peek(); + channelName = tempChannel.startsWith("!SINGLE L MESSAGE!") ? "local" : "global"; + } + + // END HACK + if (MultiChatSpigot.channelObjects.containsKey(channelName)) { PseudoChannel channelObject = MultiChatSpigot.channelObjects.get(channelName); @@ -96,10 +105,20 @@ public void onChat(final AsyncPlayerChatEvent event) { } if (MultiChatSpigot.playerChannels.containsKey(event.getPlayer())) { + + if (!MultiChatSpigot.globalChatServer) { + return; + } + + if (MultiChatSpigot.chatQueues.containsKey(event.getPlayer().getName().toLowerCase())) { + // Hack for /global /local direct messaging... + String tempChannel = MultiChatSpigot.chatQueues.get(event.getPlayer().getName().toLowerCase()).peek(); + if(tempChannel.startsWith("!SINGLE L MESSAGE!")) { + return; + } + } else if (MultiChatSpigot.playerChannels.get(event.getPlayer()).equals("local") || (!MultiChatSpigot.globalChatServer)) { - if (MultiChatSpigot.playerChannels.get(event.getPlayer()).equals("local")) { - - // If its a local chat message then we dont need to do anything else! + // If its a local chat message (or we can't use global chat here) then we dont need to do anything else! return; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerLowest.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerLowest.java index 8d0b38d3..2cebadfe 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerLowest.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerLowest.java @@ -29,8 +29,18 @@ public void onChat2(final AsyncPlayerChatEvent event) { channel = "global"; } + if (MultiChatSpigot.chatQueues.containsKey(event.getPlayer().getName().toLowerCase())) { + // Hack for /global /local direct messaging... + String tempChannel = MultiChatSpigot.chatQueues.get(event.getPlayer().getName().toLowerCase()).peek(); + if(tempChannel.startsWith("!SINGLE L MESSAGE!")) { + channel = "local"; + } else { + channel = "global"; + } + } + - if (channel.equals("local")) { + if (channel.equals("local") || (!MultiChatSpigot.globalChatServer)) { // Local chat @@ -80,10 +90,11 @@ public void onChat2(final AsyncPlayerChatEvent event) { format = format.replace("!!!1!!!", "%1$s"); format = format.replace("!!!2!!!", "%2$s"); - if (channel.equals("local")) { - // If we are a global chat server, then we want to set the format! - if (MultiChatSpigot.globalChatServer) event.setFormat(ChatColor.translateAlternateColorCodes('&', format)); + if (channel.equals("local") || (!MultiChatSpigot.globalChatServer)) { + // TRY TO FIX ISSUE WITH MULTICHAT NOT FORMATTING LOCAL MESSAGES IF NOT IN GLOBAL MODE if (MultiChatSpigot.globalChatServer) event.setFormat(ChatColor.translateAlternateColorCodes('&', format)); + event.setFormat(ChatColor.translateAlternateColorCodes('&', format)); } else { + // If we are a global chat server, then we want to set the format! if (MultiChatSpigot.globalChatServer) event.setFormat(ChatColor.translateAlternateColorCodes('&', format)); } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerMonitor.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerMonitor.java index 3b879264..14e3c71c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerMonitor.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/ChatListenerMonitor.java @@ -14,13 +14,40 @@ public class ChatListenerMonitor implements Listener { @EventHandler(priority=EventPriority.MONITOR) public void onChat(final AsyncPlayerChatEvent event) { + String queueValue = ""; + + if (MultiChatSpigot.chatQueues.containsKey(event.getPlayer().getName().toLowerCase())) { + // Hack for /global /local direct messaging... + String tempChannel = MultiChatSpigot.chatQueues.get(event.getPlayer().getName().toLowerCase()).poll(); + + if (MultiChatSpigot.chatQueues.get(event.getPlayer().getName().toLowerCase()).size() < 1) { + MultiChatSpigot.chatQueues.remove(event.getPlayer().getName().toLowerCase()); + } + + if(tempChannel.startsWith("!SINGLE L MESSAGE!")) { + queueValue = "local"; + } else { + queueValue = "global"; + } + } + // IF ITS ALREADY CANCELLED WE CAN IGNORE IT if (event.isCancelled()) return; // IF ITS LOCAL CHAT WE CAN IGNORE IT if (MultiChatSpigot.playerChannels.containsKey(event.getPlayer())) { - if (MultiChatSpigot.playerChannels.get(event.getPlayer()).equals("local")) { + + if (!MultiChatSpigot.globalChatServer) { + return; + } + + if (!queueValue.equals("")) { + // Hack for /global /local direct messaging... + if (queueValue.equalsIgnoreCase("local")) { + return; + } + } else if (MultiChatSpigot.playerChannels.get(event.getPlayer()).equals("local") || (!MultiChatSpigot.globalChatServer)) { return; } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/MultiChatPluginMessageListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/MultiChatPluginMessageListener.java index b097b3d2..40655327 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/MultiChatPluginMessageListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spigotbridge/listeners/MultiChatPluginMessageListener.java @@ -4,8 +4,10 @@ import java.io.DataInputStream; import java.io.IOException; import java.io.ObjectInputStream; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Queue; import java.util.Set; import java.util.UUID; @@ -114,6 +116,40 @@ public void onPluginMessageReceived(String channel, Player player, byte[] bytes) String playerRegex = in.readUTF(); String command = in.readUTF(); + /* THIS BIT NOW IS A BIT OF A HACK! */ + + /* + * To implement sending single messages to global or local chat channels, we do a nice hack... + * We send a "command" of local or global chat... + * Then we deal with it here and add to the "CHAT QUEUE" in the MultiChatSpigot class + * And then we send the chat message as if it were normal, but it will check the CHAT QUEUE to deal with it... + */ + + if (command.startsWith("!SINGLE L MESSAGE!") || command.startsWith("!SINGLE G MESSAGE!")) { + + String message = command.substring("!SINGLE X MESSAGE!".length(),command.length()); + + if (MultiChatSpigot.chatQueues.containsKey(playerRegex.toLowerCase())) { + + Queue chatQueue = MultiChatSpigot.chatQueues.get(playerRegex.toLowerCase()); + chatQueue.add(command); + + } else { + + Queue chatQueue = new LinkedList(); + chatQueue.add(command); + MultiChatSpigot.chatQueues.put(playerRegex.toLowerCase(), chatQueue); + + } + + Bukkit.getServer().getPlayer(playerRegex).chat(message); + + return; + + } + + /* END HACK */ + for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (p.getName().matches(playerRegex)) { diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/MultiChatSponge.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/MultiChatSponge.java index d67e7e26..c28c8365 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/MultiChatSponge.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/MultiChatSponge.java @@ -2,28 +2,26 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Path; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Optional; +import java.util.Queue; import java.util.Set; import java.util.UUID; -import java.util.regex.Pattern; import org.spongepowered.api.Platform; import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; -import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; @@ -32,7 +30,6 @@ import org.spongepowered.api.network.ChannelRegistrar; import org.spongepowered.api.plugin.Dependency; import org.spongepowered.api.plugin.Plugin; -import org.spongepowered.api.service.user.UserStorageService; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.channel.impl.SimpleMutableMessageChannel; @@ -45,7 +42,14 @@ import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import xyz.olivermartin.multichat.database.DatabaseManager; +import xyz.olivermartin.multichat.database.DatabaseMode; import xyz.olivermartin.multichat.spigotbridge.PseudoChannel; +import xyz.olivermartin.multichat.spongebridge.commands.MultiChatSpongeCommand; +import xyz.olivermartin.multichat.spongebridge.commands.SpongeNickCommand; +import xyz.olivermartin.multichat.spongebridge.commands.SpongeProxyExecuteCommand; +import xyz.olivermartin.multichat.spongebridge.commands.SpongeRealnameCommand; +import xyz.olivermartin.multichat.spongebridge.commands.SpongeUsernameCommand; import xyz.olivermartin.multichat.spongebridge.listeners.BungeeChatListener; import xyz.olivermartin.multichat.spongebridge.listeners.BungeeCommandListener; import xyz.olivermartin.multichat.spongebridge.listeners.BungeePlayerCommandListener; @@ -62,10 +66,12 @@ * @author Oliver Martin (Revilo410) * */ -@Plugin(id = "multichat", name = "MultiChatSponge", version = "1.7.5", dependencies = { @Dependency(id = "placeholderapi", optional = true) }) -public final class MultiChatSponge implements CommandExecutor { +@Plugin(id = "multichat", name = "MultiChatSponge", version = "1.8", dependencies = { @Dependency(id = "placeholderapi", optional = true) }) +public final class MultiChatSponge { public static SimpleMutableMessageChannel multichatChannel; + + public static MultiChatSponge instance; ChannelRegistrar channelRegistrar; @@ -83,7 +89,10 @@ public final class MultiChatSponge implements CommandExecutor { static RawDataChannel channelChannel; static RawDataChannel ignoreChannel; - public static Map nicknames; + static RawDataChannel pexecuteChannel; + static RawDataChannel ppexecuteChannel; + + //public static Map nicknames; public static Map displayNames = new HashMap(); public static boolean setDisplayNameLastVal = false; @@ -103,22 +112,34 @@ public final class MultiChatSponge implements CommandExecutor { public static boolean showNicknamePrefix = false; public static String nicknamePrefix = "~"; public static List nicknameBlacklist = new ArrayList(); + public static int nicknameMaxLength = 20; + public static int nicknameMinLength = 3; + public static boolean nicknameLengthIncludeFormatting = false; + public static boolean nicknameSQL = false; public static Map playerChannels = new HashMap(); public static Map channelObjects = new HashMap(); public static Map> ignoreMap = new HashMap>(); public static Map colourMap = new HashMap(); + + public static Map> chatQueues = new HashMap>(); @Inject @DefaultConfig(sharedRoot = true) private ConfigurationLoader configLoader; + @Inject + @ConfigDir(sharedRoot = false) + private Path privateConfigDir; + @SuppressWarnings("serial") @Listener public void onServerStart(GameStartedServerEvent event) { // DEBUG MODE - //DebugManager.setDebug(true); + //DebugManager.setDebug(true);//TODO + + instance = this; SpongeConfigManager.getInstance().registerHandler("multichatsponge.yml"); ConfigurationNode config = SpongeConfigManager.getInstance().getHandler("multichatsponge.yml").getConfig(); @@ -131,50 +152,321 @@ public void onServerStart(GameStartedServerEvent event) { showNicknamePrefix = config.getNode("show_nickname_prefix").getBoolean(); nicknamePrefix = config.getNode("nickname_prefix").getString(); nicknameBlacklist = config.getNode("nickname_blacklist").getList(value -> value.toString()); + if (!config.getNode("nickname_length_limit").isVirtual()) { + nicknameMaxLength = config.getNode("nickname_length_limit").getInt(); + nicknameLengthIncludeFormatting = config.getNode("nickname_length_limit_formatting").getBoolean(); + } + + if (!config.getNode("nickname_length_min").isVirtual()) { + + nicknameMinLength = config.getNode("nickname_length_min").getInt(); + + } + + + // SQL + + if (!config.getNode("nickname_sql").isVirtual()) { + + nicknameSQL = config.getNode("nickname_sql").getBoolean(); + + if (nicknameSQL) { + + if (config.getNode("mysql").getBoolean()) { + + DatabaseManager.getInstance().setMode(DatabaseMode.MySQL); + + DatabaseManager.getInstance().setURLMySQL(config.getNode("mysql_url").getString()); + DatabaseManager.getInstance().setUsernameMySQL(config.getNode("mysql_user").getString()); + DatabaseManager.getInstance().setPasswordMySQL(config.getNode("mysql_pass").getString()); + + try { + + if (!config.getNode("mysql_database").isVirtual()) { + DatabaseManager.getInstance().createDatabase("multichatsponge.db", config.getNode("mysql_database").getString()); + } else { + DatabaseManager.getInstance().createDatabase("multichatsponge.db", "multichatsponge"); + } + + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().connectToDatabase(); + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().update("CREATE TABLE IF NOT EXISTS name_data(id VARCHAR(128), f_name VARCHAR(255), u_name VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().update("CREATE TABLE IF NOT EXISTS nick_data(id VARCHAR(128), u_nick VARCHAR(255), f_nick VARCHAR(255), PRIMARY KEY (id));"); + ///DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().disconnectFromDatabase(); + + SpongeNameManager.useSQL(nicknameSQL); + + } catch (SQLException e) { + nicknameSQL = false; + SpongeNameManager.useSQL(false); + System.err.println("Could not enable database! Using files..."); + e.printStackTrace(); + } + + } else { + + DatabaseManager.getInstance().setMode(DatabaseMode.SQLite); + + File configDir = privateConfigDir.toFile(); + + if (!(configDir.exists() && configDir.isDirectory())) { + configDir.mkdir(); + } + + DatabaseManager.getInstance().setPathSQLite(configDir); + + try { + + DatabaseManager.getInstance().createDatabase("multichatsponge.db"); + + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().connectToDatabase(); + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().update("CREATE TABLE IF NOT EXISTS name_data(id VARCHAR(128), f_name VARCHAR(255), u_name VARCHAR(255), PRIMARY KEY (id));"); + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().update("CREATE TABLE IF NOT EXISTS nick_data(id VARCHAR(128), u_nick VARCHAR(255), f_nick VARCHAR(255), PRIMARY KEY (id));"); + //DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().disconnectFromDatabase(); + + SpongeNameManager.useSQL(nicknameSQL); + + } catch (SQLException e) { + nicknameSQL = false; + SpongeNameManager.useSQL(false); + System.err.println("Could not enable database! Using files..."); + e.printStackTrace(); + } + + } + + } + + } + + // /SQL + + } - configLoader = HoconConfigurationLoader.builder().setFile(new File("nicknames")).build(); - ConfigurationNode rootNode; + if (SpongeNameManager.getInstance() instanceof SpongeFileNameManager) { - try { + File f = new File("multichat_namedata"); + File fLegacy = new File("nicknames"); - rootNode = configLoader.load(); + if ((f.exists()) && (!f.isDirectory())) { - try { + // New file based storage + configLoader = HoconConfigurationLoader.builder().setFile(f).build(); + ConfigurationNode rootNode; + + Map mapUUIDNick; + Map mapNickUUID; + Map mapNickFormatted; + + try { + + rootNode = configLoader.load(); + + try { + + mapUUIDNick = (Map) rootNode.getNode("mapUUIDNick").getValue(new TypeToken>() { /* EMPTY */ }); + mapNickUUID = (Map) rootNode.getNode("mapNickUUID").getValue(new TypeToken>() { /* EMPTY */ }); + mapNickFormatted = (Map) rootNode.getNode("mapNickFormatted").getValue(new TypeToken>() { /* EMPTY */ }); + + if (mapUUIDNick == null) { + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + System.out.println("[MultiChatSponge] Created new nicknames maps for file storage!"); + } - nicknames = (Map) rootNode.getNode("nicknames").getValue(new TypeToken>() { /* EMPTY */ }); + System.out.println("[MultiChatSponge] Nicknames appeared to load correctly!"); - if (nicknames == null) { + } catch (ClassCastException e) { + + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } catch (ObjectMappingException e) { + + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + try { + + configLoader.save(rootNode); + + } catch (IOException e) { + + e.printStackTrace(); + + } + + } catch (IOException e) { + + e.printStackTrace(); + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + ((SpongeFileNameManager)SpongeNameManager.getInstance()).loadFromFile(mapUUIDNick, mapNickUUID, mapNickFormatted); + + } else if (fLegacy.exists()) { + + // Legacy storage + ConfigurationLoader legacyConfigLoader = HoconConfigurationLoader.builder().setFile(new File("nicknames")).build(); + ConfigurationNode rootNode; + + Map nicknames; + + try { + + rootNode = legacyConfigLoader.load(); + + try { + + nicknames = (Map) rootNode.getNode("nicknames").getValue(new TypeToken>() { /* EMPTY */ }); + + if (nicknames == null) { + nicknames = new HashMap(); + System.out.println("[MultiChatSponge] Created nicknames map"); + } + + System.out.println("[MultiChatSponge] Loaded a legacy (PRE-1.8) nicknames file!"); + System.out.println("[MultiChatSponge] Attempting conversion..."); + + } catch (ClassCastException e) { + + nicknames = new HashMap(); + + } catch (ObjectMappingException e) { + + nicknames = new HashMap(); + + } + + try { + + legacyConfigLoader.save(rootNode); + + } catch (IOException e) { + + e.printStackTrace(); + + } + + } catch (IOException e) { + + e.printStackTrace(); nicknames = new HashMap(); - System.out.println("[MultiChatSponge] Created nicknames map"); + } - System.out.println("[MultiChatSponge] Nicknames appeared to load correctly!"); + // Now loaded the legacy nicknames into "nicknames" var - } catch (ClassCastException e) { + for (Entry e : nicknames.entrySet()) { + SpongeNameManager.getInstance().setNickname(e.getKey(), e.getValue()); + } - nicknames = new HashMap(); + System.out.println("[MultiChatSponge] Conversion completed."); + System.out.println("[MultiChatSponge] Converted " + nicknames.size() + " records!"); - } catch (ObjectMappingException e) { + // Attempting to save the new file... - nicknames = new HashMap(); + configLoader = HoconConfigurationLoader.builder().setFile(f).build(); + ConfigurationNode rootNode2; - } + rootNode2 = configLoader.createEmptyNode(); - try { + try { - configLoader.save(rootNode); + rootNode2.getNode("mapUUIDNick").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapUUIDNick()); + rootNode2.getNode("mapNickUUID").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapNickUUID()); + rootNode2.getNode("mapNickFormatted").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapNickFormatted()); - } catch (IOException e) { + try { + configLoader.save(rootNode2); + System.out.println("[MultiChatSponge] SAVED NEW NICKNAME DATA!."); + } catch (IOException e) { + e.printStackTrace(); + } - e.printStackTrace(); + } catch (ObjectMappingException e) { + e.printStackTrace(); + System.err.println("[MultiChatSponge] ERROR: Could not write nicknames :("); + } - } + } else { + + // First startup + + // New file based storage + configLoader = HoconConfigurationLoader.builder().setFile(f).build(); + ConfigurationNode rootNode; + + Map mapUUIDNick; + Map mapNickUUID; + Map mapNickFormatted; + + try { - } catch (IOException e) { + rootNode = configLoader.load(); - e.printStackTrace(); - nicknames = new HashMap(); + try { + + mapUUIDNick = (Map) rootNode.getNode("mapUUIDNick").getValue(new TypeToken>() { /* EMPTY */ }); + mapNickUUID = (Map) rootNode.getNode("mapNickUUID").getValue(new TypeToken>() { /* EMPTY */ }); + mapNickFormatted = (Map) rootNode.getNode("mapNickFormatted").getValue(new TypeToken>() { /* EMPTY */ }); + + if (mapUUIDNick == null) { + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + System.out.println("[MultiChatSponge] Created new nicknames maps for file storage!"); + } + + System.out.println("[MultiChatSponge] Nicknames appeared to load correctly!"); + + } catch (ClassCastException e) { + + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } catch (ObjectMappingException e) { + + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + try { + + configLoader.save(rootNode); + + } catch (IOException e) { + + e.printStackTrace(); + + } + + } catch (IOException e) { + + e.printStackTrace(); + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + ((SpongeFileNameManager)SpongeNameManager.getInstance()).loadFromFile(mapUUIDNick, mapNickUUID, mapNickFormatted); + + } } @@ -196,6 +488,9 @@ public void onServerStart(GameStartedServerEvent event) { ChannelBinding.RawDataChannel channelChannel = Sponge.getGame().getChannelRegistrar().createRawChannel(this, "multichat:ch"); ChannelBinding.RawDataChannel ignoreChannel = Sponge.getGame().getChannelRegistrar().createRawChannel(this, "multichat:ignore"); + ChannelBinding.RawDataChannel pexecuteChannel = Sponge.getGame().getChannelRegistrar().createRawChannel(this, "multichat:pxe"); + ChannelBinding.RawDataChannel ppexecuteChannel = Sponge.getGame().getChannelRegistrar().createRawChannel(this, "multichat:ppxe"); + commChannel.addListener(Platform.Type.SERVER, new MetaListener(commChannel)); chatChannel.addListener(Platform.Type.SERVER, new BungeeChatListener(chatChannel)); channelChannel.addListener(Platform.Type.SERVER, new PlayerChannelListener()); @@ -218,6 +513,9 @@ public void onServerStart(GameStartedServerEvent event) { MultiChatSponge.channelChannel = channelChannel; MultiChatSponge.ignoreChannel = ignoreChannel; + MultiChatSponge.pexecuteChannel = pexecuteChannel; + MultiChatSponge.ppexecuteChannel = ppexecuteChannel; + // Register listeners Sponge.getEventManager().registerListeners(this, new SpongeChatListener()); @@ -231,10 +529,43 @@ public void onServerStart(GameStartedServerEvent event) { GenericArguments.onlyOne(GenericArguments.player(Text.of("player"))), GenericArguments.remainingJoinedStrings(Text.of("message"))) .permission("multichatsponge.nick.self") - .executor(this) + .executor(new SpongeNickCommand()) + .build(); + + CommandSpec multichatspongeCommandSpec = CommandSpec.builder() + .description(Text.of("MultiChatSponge command")) + .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("command")))) + .permission("multichatsponge.admin") + .executor(new MultiChatSpongeCommand()) + .build(); + + CommandSpec realnameCommandSpec = CommandSpec.builder() + .description(Text.of("Sponge Realname Command")) + .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("nickname")))) + .permission("multichatsponge.realname") + .executor(new SpongeRealnameCommand()) + .build(); + + CommandSpec usernameCommandSpec = CommandSpec.builder() + .description(Text.of("Sponge Username Command")) + .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("username")))) + .permission("multichatsponge.username") + .executor(new SpongeUsernameCommand()) + .build(); + + CommandSpec pexecuteCommandSpec = CommandSpec.builder() + .description(Text.of("Sponge Proxy Execute Command")) + .arguments( + GenericArguments.remainingJoinedStrings(Text.of("message"))) + .permission("multichatsponge.pexecute") + .executor(new SpongeProxyExecuteCommand()) .build(); Sponge.getCommandManager().register(this, nicknameCommandSpec, "nick"); + Sponge.getCommandManager().register(this, multichatspongeCommandSpec, "multichatsponge"); + Sponge.getCommandManager().register(this, realnameCommandSpec, "realname"); + Sponge.getCommandManager().register(this, usernameCommandSpec, "username"); + Sponge.getCommandManager().register(this, pexecuteCommandSpec, "pexecute", "pxe"); // Register message channel @@ -265,24 +596,41 @@ public void onServerStop(GameStoppingServerEvent event) { Sponge.getChannelRegistrar().unbindChannel(worldChannel); Sponge.getChannelRegistrar().unbindChannel(channelChannel); Sponge.getChannelRegistrar().unbindChannel(ignoreChannel); + Sponge.getChannelRegistrar().unbindChannel(pexecuteChannel); + Sponge.getChannelRegistrar().unbindChannel(ppexecuteChannel); - ConfigurationNode rootNode; + if (nicknameSQL) { + try { + DatabaseManager.getInstance().getDatabase("multichatsponge.db").get().disconnectFromDatabase(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + } else { - rootNode = configLoader.createEmptyNode(); + ConfigurationNode rootNode; - try { - - rootNode.getNode("nicknames").setValue(new TypeToken>() {}, nicknames); + rootNode = configLoader.createEmptyNode(); try { - configLoader.save(rootNode); - } catch (IOException e) { + + rootNode.getNode("mapUUIDNick").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapUUIDNick()); + rootNode.getNode("mapNickUUID").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapNickUUID()); + rootNode.getNode("mapNickFormatted").setValue(new TypeToken>() {}, + ((SpongeFileNameManager)SpongeNameManager.getInstance()).getMapNickFormatted()); + + try { + configLoader.save(rootNode); + } catch (IOException e) { + e.printStackTrace(); + } + + } catch (ObjectMappingException e) { e.printStackTrace(); + System.err.println("[MultiChatSponge] ERROR: Could not write nicknames :("); } - } catch (ObjectMappingException e) { - e.printStackTrace(); - System.err.println("[MultiChatSponge] ERROR: Could not write nicknames :("); } } @@ -293,6 +641,18 @@ public static void sendChatToBungee(Player player, String message, String format } + public static void sendProxyExecuteMessage(Player player, String message) { + + pexecuteChannel.sendTo(player,buffer -> buffer.writeUTF(message)); + + } + + public static void sendProxyExecutePlayerMessage(Player player, String message, String targetPlayer) { + + ppexecuteChannel.sendTo(player,buffer -> buffer.writeUTF(message).writeUTF(targetPlayer)); + + } + public static void updatePlayerMeta(String playername, boolean setDisplayName, String displayNameFormat) { if (!Sponge.getServer().getPlayer(playername).isPresent()) return; @@ -302,11 +662,7 @@ public static void updatePlayerMeta(String playername, boolean setDisplayName, S String prefix = ""; String suffix = ""; - if (nicknames.containsKey(player.getUniqueId())) { - nickname = nicknames.get(player.getUniqueId()); - } else { - nickname = player.getName(); - } + nickname = SpongeNameManager.getInstance().getCurrentName(player.getUniqueId()); final String fNickname = nickname; nickChannel.sendTo(player,buffer -> buffer.writeUTF(player.getUniqueId().toString()).writeUTF(fNickname)); @@ -350,103 +706,4 @@ public static void updatePlayerMeta(String playername, boolean setDisplayName, S } - @Override - public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { - - if (sender instanceof Player) { - sender = (Player) sender; - } else { - sender.sendMessage(Text.of("Only players can use this command!")); - return CommandResult.success(); - } - - Player target = args.getOne("player").get(); - String nickname = args.getOne("message").get(); - - if (target != sender) { - if (!sender.hasPermission("multichatsponge.nick.others")) { - sender.sendMessage(Text.of("You do not have permission to nickname other players!")); - return CommandResult.success(); - } - } - - UUID targetUUID = target.getUniqueId(); - - if (nickname.equalsIgnoreCase("off")) { - removeNickname(targetUUID); - updatePlayerMeta(target.getName(), setDisplayNameLastVal, displayNameFormatLastVal); - sender.sendMessage(Text.of(target.getName() + " has had their nickname removed!")); - return CommandResult.success(); - } - - String strippedNickname = stripAllFormattingCodes(nickname); - - UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); - Optional lookedUpName = uss.get(strippedNickname); - - // Check if a player name exists already (but not the name of this player) - if (lookedUpName.isPresent() && !strippedNickname.equalsIgnoreCase(target.getName()) && !sender.hasPermission("multichatsponge.nick.impersonate")) { - sender.sendMessage(Text.of("Sorry, a player already exists with this name!")); - return CommandResult.success(); - } - - String targetNickname; - if (nicknames.containsKey(targetUUID)) { - targetNickname = stripAllFormattingCodes(nicknames.get(targetUUID)); - } else { - targetNickname = target.getName(); - } - - // Check if a nickname exists already - if (nicknames.values().stream() - .map(nick -> stripAllFormattingCodes(nick)) - .anyMatch(nick -> nick.equalsIgnoreCase(strippedNickname)) - && !targetNickname.equalsIgnoreCase(strippedNickname) ) { - //&& !sender.hasPermission("multichatsponge.nick.duplicate")) { - - sender.sendMessage(Text.of("Sorry, a player already has that nickname!")); - return CommandResult.success(); - - } - - boolean blacklisted = false; - for (String bl : MultiChatSponge.nicknameBlacklist) { - if (strippedNickname.matches(bl)) blacklisted = true; - } - - if (blacklisted) { - - sender.sendMessage(Text.of("Sorry, this name is not allowed!")); - return CommandResult.success(); - - } - - addNickname(targetUUID,nickname); - updatePlayerMeta(target.getName(), setDisplayNameLastVal, displayNameFormatLastVal); - - sender.sendMessage(Text.of(target.getName() + " has been nicknamed!")); - return CommandResult.success(); - } - - private void addNickname(UUID uuid, String nickname) { - nicknames.put(uuid,nickname); - } - - private void removeNickname(UUID uuid) { - nicknames.remove(uuid); - } - - public String stripAllFormattingCodes(String input) { - - char COLOR_CHAR = '&'; - Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]"); - - if (input == null) { - return null; - } - - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - - } - } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeFileNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeFileNameManager.java new file mode 100644 index 00000000..dd834f6e --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeFileNameManager.java @@ -0,0 +1,375 @@ +package xyz.olivermartin.multichat.spongebridge; + +import java.util.Collection; +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 java.util.regex.PatternSyntaxException; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.api.service.user.UserStorageService; + +/** + * Player Name Manager + *

Manages players names, uuids and nicknames

+ * + * @author Oliver Martin (Revilo410) + * + */ +public class SpongeFileNameManager extends SpongeNameManager { + + private Map mapUUIDNick; + private Map mapNickUUID; + private Map mapNickFormatted; + + public SpongeFileNameManager() { + + super(); + + setDefaultData(); + + } + + private void setDefaultData() { + + mapUUIDNick = new HashMap(); + mapNickUUID = new HashMap(); + + mapNickFormatted = new HashMap(); + + } + + public Map getMapUUIDNick() { + return mapUUIDNick; + } + public Map getMapNickUUID() { + return mapNickUUID; + } + public Map getMapNickFormatted() { + return mapNickFormatted; + } + + public void loadFromFile(Map mapUUIDNick, Map mapNickUUID, Map mapNickFormatted) { + this.mapUUIDNick = mapUUIDNick; + this.mapNickUUID = mapNickUUID; + this.mapNickFormatted = mapNickFormatted; + } + + /** + * Returns the FORMATTED NICKNAME of a player if they have one set, otherwise returns their username + * + * @param uuid The Unique ID of the player to lookup + * @param withPrefix Should the nickname prefix also be returned if it is set? + * @return The NICKNAME of the player if it is set, otherwise their username + */ + public String getCurrentName(UUID uuid, boolean withPrefix) { + + synchronized (mapUUIDNick) { + if (mapUUIDNick.containsKey(uuid)) { + if (MultiChatSponge.showNicknamePrefix && withPrefix) { + return MultiChatSponge.nicknamePrefix + mapNickFormatted.get(mapUUIDNick.get(uuid)); + } else { + return mapNickFormatted.get(mapUUIDNick.get(uuid)); + } + } + } + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional opUser = uss.get(uuid); + + if (opUser.isPresent()) { + return opUser.get().getName(); + } + + return ""; + } + + /** + * Returns the username of a player + * + * @param uuid The Unique ID of the player to lookup + * @return The username of the player + */ + public String getName(UUID uuid) { + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional opUser = uss.get(uuid); + + if (opUser.isPresent()) { + return opUser.get().getName(); + } + + return ""; + + } + + /** + * Gets the UUID of a player from their UNFORMATTED nickname + * THIS MEANS THE NICKNAME PROVIDED MUST BE IN LOWERCASE WITH ALL FORMATTING CODES REMOVED + * + * @param nickname The UNFORMATTED nickname of the player + * @return An optional which may contain their UUID if the nickname was found in the system + */ + protected Optional getUUIDFromUnformattedNickname(String nickname) { + + nickname = nickname.toLowerCase(); + + synchronized (mapNickUUID) { + if (mapNickUUID.containsKey(nickname)) { + return Optional.of(mapNickUUID.get(nickname)); + } + } + + return Optional.empty(); + + } + + /** + * Returns a player's UUID given their username + * + * @param username The player's username + * @return An optional value which may contain their UUID if the username was found + */ + public Optional getUUIDFromName(String username) { + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional opUser = uss.get(username); + + if (opUser.isPresent()) { + return Optional.of(opUser.get().getUniqueId()); + } + + return Optional.empty(); + + } + + /** + * Register a player as online + *

Also performs any setup needed to equip nicknames etc.

+ * @param player + */ + public void registerPlayer(Player player) { + + UUID uuid = player.getUniqueId(); + + online.add(uuid); + System.out.println("[+] " + player.getName() + " has joined this server."); + + } + + /** + * Register a player into the system without them being online + *

Used mainly for legacy conversion of old nickname file

+ * @param uuid Player's UUID + */ + public void registerOfflinePlayerByUUID(UUID uuid, String username) { + + /* This is handled by Sponge */ + return; + + } + + /** + * Register a player as offline + * @param player + */ + public void unregisterPlayer(Player player) { + online.remove(player.getUniqueId()); + System.out.println("[-] " + player.getName() + " has left this server."); + } + + /** + * Set the nickname of a player + * @param uuid + * @param nickname + */ + public void setNickname(UUID uuid, String nickname) { + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional opUser = uss.get(uuid); + + if (!opUser.isPresent()) { + return; + } + + if (mapUUIDNick.containsKey(uuid)) { + removeNickname(uuid); + } + + String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + + synchronized (mapNickUUID) { + + // Check for duplicates + if (mapNickUUID.containsKey(unformattedNickname)) { + if (mapNickUUID.get(unformattedNickname) != uuid) { + return; + } + } + + mapUUIDNick.put(uuid, unformattedNickname); + mapNickUUID.put(unformattedNickname, uuid); + mapNickFormatted.put(unformattedNickname, nickname); + + } + + } + + /** + * @param username + * @return If this player has logged into the server before + */ + public boolean existsPlayer(String username) { + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional opUser = uss.get(username); + + return opUser.isPresent(); + } + + /** + * @param nickname + * @return If this nickname is currently in use + */ + public boolean existsNickname(String nickname) { + return mapNickUUID.containsKey(stripAllFormattingCodes(nickname.toLowerCase())); + } + + /** + * Return the UUIDs of players who have nicknames containing characters provided in the nickname argument + * @param nickname The characters of the nickname to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public Optional> getPartialNicknameMatches(String nickname) { + + Set nickSet = mapNickUUID.keySet(); + nickname = stripAllFormattingCodes(nickname.toLowerCase()); + Set uuidSet = new HashSet(); + + for (String nick : nickSet) { + + if (nick.startsWith(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + for (String nick : nickSet) { + + if (nick.contains(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + try { + for (String nick : nickSet) { + + if (nick.matches(nickname)) { + uuidSet.add(mapNickUUID.get(nick)); + } + + } + } catch (PatternSyntaxException e) { + /* + * Its not a valid regex, so we will just say there are no matches! + */ + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + return Optional.empty(); + + } + + /** + * Return the UUIDs of players who have names containing characters provided in the name argument + * @param name The characters of the name to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public Optional> getPartialNameMatches(String name) { + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Collection profiles = uss.getAll(); + + //Set nameSet = mapNameUUID.keySet(); + name = stripAllFormattingCodes(name.toLowerCase()); + Set uuidSet = new HashSet(); + + for (GameProfile gp : profiles) { + + Optional opName = gp.getName(); + if (!opName.isPresent()) { + continue; + } + + if (opName.get().startsWith(name)) { + uuidSet.add(gp.getUniqueId()); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + for (GameProfile gp : profiles) { + + Optional opName = gp.getName(); + if (!opName.isPresent()) { + continue; + } + + if (opName.get().contains(name)) { + uuidSet.add(gp.getUniqueId()); + } + + } + + if (!uuidSet.isEmpty()) return Optional.of(uuidSet); + + return Optional.empty(); + + } + + /** + * @param uuid + * @return If this player is currently online on the server + */ + public boolean isOnline(UUID uuid) { + return online.contains(uuid); + } + + /** + * Removes the nickname for a specified player + * @param uuid + */ + public void removeNickname(UUID uuid) { + + synchronized (mapUUIDNick) { + + if (!mapUUIDNick.containsKey(uuid)) { + return; + } + + String nickname = mapUUIDNick.get(uuid); + + mapUUIDNick.remove(uuid); + mapNickUUID.remove(nickname); + mapNickFormatted.remove(nickname); + + } + + } + + //TODO SAVE AND LOAD DATA FROM FILE + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeNameManager.java new file mode 100644 index 00000000..ec740c59 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeNameManager.java @@ -0,0 +1,286 @@ +package xyz.olivermartin.multichat.spongebridge; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +import org.spongepowered.api.entity.living.player.Player; + +/** + * Player Name Manager + *

Manages players names, uuids and nicknames

+ * + * @author Oliver Martin (Revilo410) + * + */ +public abstract class SpongeNameManager { + + private static SpongeNameManager instance; + + static { + instance = new SpongeFileNameManager(); + } + + public static SpongeNameManager getInstance() { + return instance; + } + + public static void useSQL(boolean sql) { + if (sql) instance = new SpongeSQLNameManager(); + else instance = new SpongeFileNameManager(); + } + + // END OF STATIC DEFINITIONS + + protected List online; + + protected SpongeNameManager() { + + online = new ArrayList(); + + } + + /** + * Returns the FORMATTED NICKNAME of a player if they have one set, otherwise returns their username + * + * @param uuid The Unique ID of the player to lookup + * @return The NICKNAME of the player if it is set, otherwise their username + */ + public String getCurrentName(UUID uuid) { + return getCurrentName(uuid, true); + } + + /** + * Returns the FORMATTED NICKNAME of a player if they have one set, otherwise returns their username + * + * @param uuid The Unique ID of the player to lookup + * @param withPrefix Should the nickname prefix also be returned if it is set? + * @return The NICKNAME of the player if it is set, otherwise their username + */ + public abstract String getCurrentName(UUID uuid, boolean withPrefix); + + /** + * Returns the username of a player + * + * @param uuid The Unique ID of the player to lookup + * @return The username of the player + */ + public abstract String getName(UUID uuid); + + /** + * Gets the UUID of a player from their UNFORMATTED nickname + * THIS MEANS THE NICKNAME PROVIDED MUST BE IN LOWERCASE WITH ALL FORMATTING CODES REMOVED + * + * @param nickname The UNFORMATTED nickname of the player + * @return An optional which may contain their UUID if the nickname was found in the system + */ + protected abstract Optional getUUIDFromUnformattedNickname(String nickname); + + /** + * Returns a player's UUID given their username + * + * @param username The player's username + * @return An optional value which may contain their UUID if the username was found + */ + public abstract Optional getUUIDFromName(String username); + + /** + * Gets a player's UUID from their nickname + * + * @param nickname The player's nickname (which may contain formatting codes etc.) + * @return An optional value which may contain their UUID if the nickname was found + */ + public Optional getUUIDFromNickname(String nickname) { + + nickname = nickname.toLowerCase(); + nickname = stripAllFormattingCodes(nickname); + + return getUUIDFromUnformattedNickname(nickname); + + } + + /** + * Gets a player's username from their nickname + * + * @param nickname The player's nickname (which may contain formatting codes etc.) + * @return An optional value which may contain their username if the nickname was found + */ + public Optional getNameFromNickname(String nickname) { + + Optional oUUID = getUUIDFromNickname(nickname); + + if (!oUUID.isPresent()) { + return Optional.empty(); + } + + UUID uuid = oUUID.get(); + + return Optional.of(getName(uuid)); + + } + + /** + * Gets a player's nickname from their username + * + * @param nickname The player's username + * @return An optional value which may contain their nickname, or their username if a nickname was not set, as long as their username can be found + */ + public Optional getCurrentNameFromName(String username) { + + username = username.toLowerCase(); + + Optional oUUID = getUUIDFromName(username); + + if (!oUUID.isPresent()) { + return Optional.empty(); + } + + UUID uuid = oUUID.get(); + + return Optional.of(getCurrentName(uuid)); + + } + + /** + * Gets a player's formatted name from their username + * + * @param name The player's username + * @return An optional value which may contain their name, as long as their username can be found + */ + public Optional getFormattedNameFromName(String username) { + + username = username.toLowerCase(); + + Optional oUUID = getUUIDFromName(username); + + if (!oUUID.isPresent()) { + return Optional.empty(); + } + + UUID uuid = oUUID.get(); + + return Optional.of(getName(uuid)); + + } + + /** + * Register a player as online + *

Also performs any setup needed to equip nicknames etc.

+ * @param player + */ + public abstract void registerPlayer(Player player); + + /** + * Register a player into the system without them being online + *

Used mainly for legacy conversion of old nickname file

+ * @param uuid Player's UUID + */ + public abstract void registerOfflinePlayerByUUID(UUID uuid, String username); + + /** + * Register a player as offline + * @param player + */ + public abstract void unregisterPlayer(Player player); + + /** + * Set the nickname of a player + * @param uuid + * @param nickname + */ + public abstract void setNickname(UUID uuid, String nickname); + + /** + * @param username + * @return If this player has logged into the server before + */ + public abstract boolean existsPlayer(String username); + + /** + * @param nickname + * @return If this nickname is currently in use + */ + public abstract boolean existsNickname(String nickname); + + /** + * Return the UUIDs of players who have nicknames containing characters provided in the nickname argument + * @param nickname The characters of the nickname to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public abstract Optional> getPartialNicknameMatches(String nickname); + + /** + * Return the UUIDs of players who have names containing characters provided in the name argument + * @param name The characters of the name to check + * @return An optional which might contain a players UUID if a partial match was found + */ + public abstract Optional> getPartialNameMatches(String name); + + /** + * @param uuid + * @return If this player is currently online on the server + */ + public boolean isOnline(UUID uuid) { + return online.contains(uuid); + } + + /** + * Removes the nickname for a specified player + * @param 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-OR]"); + + 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 containsColorCodes(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 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); + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongePlaceholderManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongePlaceholderManager.java index 40e4722e..d319ced5 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongePlaceholderManager.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongePlaceholderManager.java @@ -10,16 +10,8 @@ public static String buildChatFormat(Player player, String format) { String prefix = ""; String suffix = ""; - if (MultiChatSponge.nicknames.containsKey(player.getUniqueId())) { - if (MultiChatSponge.showNicknamePrefix) { - nickname = MultiChatSponge.nicknamePrefix + MultiChatSponge.nicknames.get(player.getUniqueId()); - } else { - nickname = MultiChatSponge.nicknames.get(player.getUniqueId()); - } - } else { - nickname = player.getName(); - } - + nickname = SpongeNameManager.getInstance().getCurrentName(player.getUniqueId(), MultiChatSponge.showNicknamePrefix); + DebugManager.log("PLAYERS NICKNAME / REALNAME IS: " + nickname); if (player.getOption("prefix").isPresent()) { @@ -46,7 +38,7 @@ public static String buildChatFormat(Player player, String format) { format = format.replace("%SERVER%", MultiChatSponge.serverName); DebugManager.log("PLACEHOLDER MANAGER IS RETURNING THIS FORMAT: " + format); - + return format; } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeSQLNameManager.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeSQLNameManager.java new file mode 100644 index 00000000..7d0fe2d3 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/SpongeSQLNameManager.java @@ -0,0 +1,671 @@ +package xyz.olivermartin.multichat.spongebridge; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import org.spongepowered.api.entity.living.player.Player; + +import xyz.olivermartin.multichat.database.DatabaseManager; +import xyz.olivermartin.multichat.database.GenericDatabase; + +public class SpongeSQLNameManager extends SpongeNameManager { + + private boolean connected; + private GenericDatabase spongedatabase; + + public SpongeSQLNameManager() { + + super(); + + connected = getDatabase(); + + } + + private boolean getDatabase() { + + Optional ogdb = DatabaseManager.getInstance().getDatabase("multichatsponge.db"); + if (ogdb.isPresent()) { + spongedatabase = ogdb.get(); + return true; + } else { + return false; + } + + } + + @Override + public String getCurrentName(UUID uuid, boolean withPrefix) { + + DebugManager.log("!Going to get current name..."); + + if (connected) { + + DebugManager.log("!We are connected..."); + try { + + String name; + + synchronized (spongedatabase) { + DebugManager.log("!Syncronise on database..."); + spongedatabase.connectToDatabase(); + DebugManager.log("!Connected to database..."); + ResultSet results = spongedatabase.query("SELECT f_name, f_nick FROM name_data LEFT JOIN nick_data ON name_data.id = nick_data.id WHERE name_data.id = '" + uuid.toString() + "';"); + DebugManager.log("!Query executed..."); + DebugManager.log("!Is it closed? : " + results.isClosed()); + results.next(); + DebugManager.log("!Should now have the nex result ready!"); + if (results.getString("f_nick") == null) { + name = results.getString("f_name"); + } else { + name = results.getString("f_nick"); + } + + } + + if (MultiChatSponge.showNicknamePrefix && withPrefix) { + return MultiChatSponge.nicknamePrefix + name; + } else { + return name; + } + + } catch (SQLException e) { + e.printStackTrace(); + return ""; + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return ""; + } + + } + + @Override + public String getName(UUID uuid) { + + if (connected) { + + try { + String name; + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + ResultSet results = spongedatabase.query("SELECT f_name FROM name_data WHERE id = '" + uuid.toString() + "';"); + results.next(); + name = results.getString("f_name"); + + } + + return name; + + } catch (SQLException e) { + e.printStackTrace(); + return ""; + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return ""; + } + + } + + @Override + protected Optional getUUIDFromUnformattedNickname(String nickname) { + + nickname = nickname.toLowerCase(); + + if (connected) { + + try { + + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + ResultSet results = spongedatabase.query("SELECT id FROM nick_data WHERE u_nick = '" + nickname + "';"); + if (results.next()) { + UUID id = UUID.fromString(results.getString("id")); + + return Optional.of(id); + } else { + + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + } + + @Override + public Optional getUUIDFromName(String username) { + + username = username.toLowerCase(); + + if (connected) { + + try { + + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + ResultSet results = spongedatabase.query("SELECT id FROM name_data WHERE u_name = '" + username + "';"); + if (results.next() ) { + UUID id = UUID.fromString(results.getString("id")); + + return Optional.of(id); + } else { + + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } else { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + } + + @Override + public void registerPlayer(Player player) { + + DebugManager.log("Register player: " + player.getName()); + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + UUID uuid = player.getUniqueId(); + String username = player.getName(); + String oldUsername; + + if (existsUUID(uuid)) { + + DebugManager.log("Their UUID exists..."); + + oldUsername = getName(uuid); + + if (!oldUsername.equalsIgnoreCase(username)) { + + DebugManager.log("Changed username!"); + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + spongedatabase.update("UPDATE name_data SET u_name = '" + username.toLowerCase() + "', f_name = '" + username + "' WHERE id = '" + uuid.toString() + "';"); + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } else { + + DebugManager.log("UUID does not exist yet!"); + + try { + synchronized (spongedatabase) { + + DebugManager.log("ABOUT TO CONNECT TO DATABASE..."); + spongedatabase.connectToDatabase(); + DebugManager.log("SHOULD NOW BE CONNECTED..."); + + spongedatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase()+ "');"); + DebugManager.log("SHOULD NOW HAVE ADDED THE NEW ROWS TO THE DATABASE!"); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + online.add(uuid); + System.out.println("[+] " + username + " has joined this server."); + + } + + public void testRegisterFakePlayer(UUID uuid, String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + String oldUsername; + + if (existsUUID(uuid)) { + + oldUsername = getName(uuid); + + if (!oldUsername.equalsIgnoreCase(username)) { + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + spongedatabase.update("UPDATE name_data SET u_name = '" + username.toLowerCase() + "', f_name = '" + username + "' WHERE id = '" + uuid.toString() + "';"); + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } else { + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + spongedatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase() + "');"); + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + online.add(uuid); + + } + + public boolean existsUUID(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT id FROM name_data WHERE id = '" + uuid.toString() + "';"); + if (results.next()) { + return true; + } else { + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public boolean hasNickname(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT id FROM nick_data WHERE id = '" + uuid.toString() + "';"); + if (results.next()) { + return true; + } else { + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public void registerMigratedPlayer(UUID uuid, String name, String formattedName, String nick, String formattedNick) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + // TODO remove debug + //System.out.println(name + "," + formattedName + "," + (nick == null ? "NULL!!!" : nick) + "," + (formattedNick == null ? "NULL!!!" : formattedNick) ); + + boolean setNick = (nick != null); + + // TODO remove debug + //System.out.println("SETNICK: " + setNick); + + if (existsUUID(uuid)) { + + synchronized (spongedatabase) { + + try { + spongedatabase.connectToDatabase(); + spongedatabase.update("UPDATE name_data SET f_name = '" + formattedName + "', u_name = '" + name + "' WHERE id = '" + uuid.toString() + "';"); + + if (setNick) { + + if (hasNickname(uuid)) { + spongedatabase.update("UPDATE nick_data SET u_nick = '" + nick + "', f_nick = '" + formattedNick + "' WHERE id = '" + uuid.toString() + "';"); + } else { + spongedatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + nick + "', '" + formattedNick + "');"); + } + + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + } else { + + try { + synchronized (spongedatabase) { + + spongedatabase.connectToDatabase(); + spongedatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + formattedName + "', '" + name + "');"); + + if (setNick) { + spongedatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + nick + "', '" + formattedNick + "');"); + } + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } + + @Override + public void registerOfflinePlayerByUUID(UUID uuid, String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (existsUUID(uuid)) { + + /* + * EMPTY : Player does not need registering + */ + + } else { + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + spongedatabase.update("INSERT INTO name_data VALUES ('" + uuid.toString() + "', '" + username + "', '" + username.toLowerCase() + "');"); + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + } + + @Override + public void unregisterPlayer(Player player) { + + online.remove(player.getUniqueId()); + System.out.println("[-] " + player.getName() + " has left this server."); + + } + + @Override + public void setNickname(UUID uuid, String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (!existsUUID(uuid)) { + return; + } + + String unformattedNickname = stripAllFormattingCodes(nickname.toLowerCase()); + + if (otherPlayerHasNickname(unformattedNickname, uuid)) { + return; + } + + try { + synchronized (spongedatabase) { + + if (hasNickname(uuid)) { + spongedatabase.connectToDatabase(); + spongedatabase.update("UPDATE nick_data SET u_nick = '" + unformattedNickname + "', f_nick = '" + nickname + "' WHERE id = '" + uuid.toString() + "';"); + } else { + spongedatabase.connectToDatabase(); + spongedatabase.update("INSERT INTO nick_data VALUES ('" + uuid.toString() + "', '" + unformattedNickname + "', '" + nickname + "');"); + } + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + @Override + public boolean existsPlayer(String username) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT u_name FROM name_data WHERE u_name = '" + username.toLowerCase() + "';"); + if (results.next()) { + return true; + } else { + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + @Override + public boolean existsNickname(String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT u_nick FROM nick_data WHERE u_nick = '" + stripAllFormattingCodes(nickname.toLowerCase()) + "';"); + if (results.next()) { + return true; + } else { + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + public boolean otherPlayerHasNickname(String nickname, UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return false; + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT id, u_nick FROM nick_data WHERE u_nick = '" + stripAllFormattingCodes(nickname.toLowerCase()) + "';"); + if (results.next()) { + if (results.getString("id").equals(uuid.toString())) { + return false; + } else { + return true; + } + } else { + return false; + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + } + + @Override + public Optional> getPartialNicknameMatches(String nickname) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT id FROM nick_data WHERE (u_nick LIKE '%" + stripAllFormattingCodes(nickname.toLowerCase()) + "%');"); + if (results.next()) { + Set uuids = new HashSet(); + uuids.add(UUID.fromString(results.getString("id"))); + + while (results.next()) { + uuids.add(UUID.fromString(results.getString("id"))); + } + + return Optional.of(uuids); + } else { + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } + + @Override + public Optional> getPartialNameMatches(String name) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return Optional.empty(); + } + + try { + synchronized (spongedatabase) { + spongedatabase.connectToDatabase(); + + ResultSet results = spongedatabase.query("SELECT id, f_name FROM name_data WHERE (u_name LIKE '%" + name.toLowerCase() + "%');"); + if (results.next()) { + Set uuids = new HashSet(); + uuids.add(UUID.fromString(results.getString("id"))); + + while (results.next()) { + uuids.add(UUID.fromString(results.getString("id"))); + } + + return Optional.of(uuids); + } else { + return Optional.empty(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + return Optional.empty(); + } + + } + + @Override + public void removeNickname(UUID uuid) { + + if (!connected) { + System.err.println("NOT CONNECTED TO DB?!?!?!?"); //TODO? + return; + } + + if (!existsUUID(uuid)) { + return; + } + + try { + + synchronized (spongedatabase) { + + if (!hasNickname(uuid)) { + return; + } + + spongedatabase.connectToDatabase(); + + spongedatabase.update("DELETE FROM nick_data WHERE id = '" + uuid.toString() + "';"); + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/MultiChatSpongeCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/MultiChatSpongeCommand.java new file mode 100644 index 00000000..7222564a --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/MultiChatSpongeCommand.java @@ -0,0 +1,175 @@ +package xyz.olivermartin.multichat.spongebridge.commands; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.api.service.user.UserStorageService; +import org.spongepowered.api.text.Text; + +import com.google.common.reflect.TypeToken; + +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import xyz.olivermartin.multichat.spongebridge.SpongeNameManager; +import xyz.olivermartin.multichat.spongebridge.SpongeSQLNameManager; + +public class MultiChatSpongeCommand implements CommandExecutor { + + @SuppressWarnings("serial") + @Override + public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { + + if (sender instanceof Player) { + sender.sendMessage(Text.of("This command can only be executed from the console!")); + return CommandResult.success(); + } + + String commandString = args.getOne("command").get(); + + if (commandString.equalsIgnoreCase("migratetosql")) { + + if (! (SpongeNameManager.getInstance() instanceof SpongeSQLNameManager)) { + sender.sendMessage(Text.of("This command can only be used in SQL mode!")); + return CommandResult.success(); + } + + // Load nickname data from file + + File f = new File("multichat_namedata"); + + if ((f.exists()) && (!f.isDirectory())) { + + ConfigurationLoader configLoader = HoconConfigurationLoader.builder().setFile(f).build(); + ConfigurationNode rootNode; + + Map mapUUIDNick; + Map mapNickFormatted; + + try { + + rootNode = configLoader.load(); + + try { + + mapUUIDNick = (Map) rootNode.getNode("mapUUIDNick").getValue(new TypeToken>() { /* EMPTY */ }); + mapNickFormatted = (Map) rootNode.getNode("mapNickFormatted").getValue(new TypeToken>() { /* EMPTY */ }); + + if (mapUUIDNick == null) { + mapUUIDNick = new HashMap(); + mapNickFormatted = new HashMap(); + System.out.println("[MultiChatSponge] Created new nicknames maps for file storage!"); + } + + System.out.println("[MultiChatSponge] Nicknames appeared to load correctly!"); + + } catch (ClassCastException e) { + + mapUUIDNick = new HashMap(); + mapNickFormatted = new HashMap(); + + } catch (ObjectMappingException e) { + + mapUUIDNick = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + try { + + configLoader.save(rootNode); + + } catch (IOException e) { + + e.printStackTrace(); + + } + + } catch (IOException e) { + + e.printStackTrace(); + mapUUIDNick = new HashMap(); + mapNickFormatted = new HashMap(); + + } + + // PERFORM MIGRATION + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Collection profiles = uss.getAll(); + + int count = 0; + int max = profiles.size(); + int checkcount = 25; + int checkpoint = checkcount/100*max; + + for (GameProfile gp : profiles) { + + count++; + if (count > checkpoint) { + sender.sendMessage(Text.of("Completed " + checkcount + "% of migration...")); + checkcount += 25; + checkpoint = checkcount/100*max; + } + + if (!gp.getName().isPresent()) continue; + + UUID uuid = gp.getUniqueId(); + String formattedName = gp.getName().get(); + String name = formattedName.toLowerCase(); + String nick; + String formattedNick; + + if (mapUUIDNick.containsKey(uuid)) { + nick = mapUUIDNick.get(uuid); + formattedNick = mapNickFormatted.get(nick); + if (formattedNick.equals(formattedName)) { + nick = null; + formattedNick = null; + } + } else { + nick = null; + formattedNick = null; + } + + ((SpongeSQLNameManager)SpongeNameManager.getInstance()).registerMigratedPlayer(uuid, name, formattedName, nick, formattedNick); + + } + + // /PERFORM MIGRATION + + sender.sendMessage(Text.of("Successfully migrated: " + max + " records")); + + return CommandResult.success(); + + } else { + + sender.sendMessage(Text.of("Could not find nickname file to process!")); + return CommandResult.success(); + + } + + } else { + + sender.sendMessage(Text.of("Incorrect usage... Try /multichatsponge migratetosql")); + return CommandResult.success(); + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeNickCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeNickCommand.java new file mode 100644 index 00000000..8921d71d --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeNickCommand.java @@ -0,0 +1,147 @@ +package xyz.olivermartin.multichat.spongebridge.commands; + +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.service.user.UserStorageService; +import org.spongepowered.api.text.Text; + +import xyz.olivermartin.multichat.spongebridge.MultiChatSponge; +import xyz.olivermartin.multichat.spongebridge.SpongeNameManager; + +public class SpongeNickCommand implements CommandExecutor { + + private static final Pattern simpleNickname = Pattern.compile("^[a-zA-Z0-9&_]+$"); + + @Override + public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { + + if (sender instanceof Player) { + sender = (Player) sender; + } else { + sender.sendMessage(Text.of("Only players can use this command!")); + return CommandResult.success(); + } + + Optional opTarget = args.getOne("player"); + + if (!opTarget.isPresent()) { + sender.sendMessage(Text.of("That player could not be found!")); + return CommandResult.success(); + } + + Player target = opTarget.get(); + String nickname = args.getOne("message").get(); + + if (target == null) { + sender.sendMessage(Text.of("That player could not be found!")); + return CommandResult.success(); + } + + if (target != sender) { + if (!sender.hasPermission("multichatsponge.nick.others")) { + sender.sendMessage(Text.of("You do not have permission to nickname other players!")); + return CommandResult.success(); + } + } + + UUID targetUUID = target.getUniqueId(); + + if (nickname.equalsIgnoreCase("off")) { + SpongeNameManager.getInstance().removeNickname(targetUUID); + MultiChatSponge.updatePlayerMeta(target.getName(), MultiChatSponge.setDisplayNameLastVal, MultiChatSponge.displayNameFormatLastVal); + sender.sendMessage(Text.of(target.getName() + " has had their nickname removed!")); + return CommandResult.success(); + } + + if (SpongeNameManager.getInstance().containsColorCodes(nickname) && !(sender.hasPermission("multichatsponge.nick.color") || sender.hasPermission("multichatsponge.nick.colour"))) { + sender.sendMessage(Text.of("You do not have permission to use nicknames with color codes!")); + return CommandResult.success(); + } + + if (SpongeNameManager.getInstance().containsFormatCodes(nickname) && !(sender.hasPermission("multichatsponge.nick.format"))) { + sender.sendMessage(Text.of("You do not have permission to use nicknames with format codes!")); + return CommandResult.success(); + } + + if (!simpleNickname.matcher(nickname).matches() && !(sender.hasPermission("multichatsponge.nick.special"))) { + sender.sendMessage(Text.of("You do not have permission to use nicknames with special characters!")); + return CommandResult.success(); + } + + if (MultiChatSponge.nicknameLengthIncludeFormatting) { + // Include formatting codes in the nickname length + if (nickname.length() > MultiChatSponge.nicknameMaxLength && !sender.hasPermission("multichatsponge.nick.anylength")) { + sender.sendMessage(Text.of("Sorry your nickname is too long, max " + MultiChatSponge.nicknameMaxLength + " characters! (Including format codes)")); + return CommandResult.success(); + } + if (nickname.length() < MultiChatSponge.nicknameMinLength && !sender.hasPermission("multichatsponge.nick.anylength")) { + sender.sendMessage(Text.of("Sorry your nickname is too short, min " + MultiChatSponge.nicknameMinLength + " characters! (Including format codes)")); + return CommandResult.success(); + } + } else { + // Do not include formatting codes in the nickname length + if (SpongeNameManager.getInstance().stripAllFormattingCodes(nickname).length() > MultiChatSponge.nicknameMaxLength && !sender.hasPermission("multichatsponge.nick.anylength")) { + sender.sendMessage(Text.of("Sorry your nickname is too long, max " + MultiChatSponge.nicknameMaxLength + " characters! (Excluding format codes)")); + return CommandResult.success(); + } + if (SpongeNameManager.getInstance().stripAllFormattingCodes(nickname).length() < MultiChatSponge.nicknameMinLength && !sender.hasPermission("multichatsponge.nick.anylength")) { + sender.sendMessage(Text.of("Sorry your nickname is too short, min " + MultiChatSponge.nicknameMinLength + " characters! (Excluding format codes)")); + return CommandResult.success(); + } + } + + String strippedNickname = SpongeNameManager.getInstance().stripAllFormattingCodes(nickname); + + if (strippedNickname.length() < 1 ) { + sender.sendMessage(Text.of("Sorry your nickname cannot be empty!")); + return CommandResult.success(); + } + + UserStorageService uss = Sponge.getServiceManager().provideUnchecked(UserStorageService.class); + Optional lookedUpName = uss.get(strippedNickname); + + // Check if a player name exists already (but not the name of this player) + if (lookedUpName.isPresent() && !strippedNickname.equalsIgnoreCase(target.getName()) && !sender.hasPermission("multichatsponge.nick.impersonate")) { + sender.sendMessage(Text.of("Sorry, a player already exists with this name!")); + return CommandResult.success(); + } + + String targetNickname = SpongeNameManager.getInstance().stripAllFormattingCodes(SpongeNameManager.getInstance().getCurrentName(targetUUID)); + + if (SpongeNameManager.getInstance().existsNickname(strippedNickname) && !targetNickname.equalsIgnoreCase(strippedNickname)) { + + sender.sendMessage(Text.of("Sorry, a player already has that nickname!")); + return CommandResult.success(); + + } + + boolean blacklisted = false; + for (String bl : MultiChatSponge.nicknameBlacklist) { + if (strippedNickname.matches(bl)) blacklisted = true; + } + + if (blacklisted && !sender.hasPermission("multichatsponge.nick.blacklist")) { + + sender.sendMessage(Text.of("Sorry, this name is not allowed!")); + return CommandResult.success(); + + } + + SpongeNameManager.getInstance().setNickname(targetUUID, nickname); + MultiChatSponge.updatePlayerMeta(target.getName(), MultiChatSponge.setDisplayNameLastVal, MultiChatSponge.displayNameFormatLastVal); + + sender.sendMessage(Text.of(target.getName() + " has been nicknamed!")); + return CommandResult.success(); + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeProxyExecuteCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeProxyExecuteCommand.java new file mode 100644 index 00000000..4916e3bc --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeProxyExecuteCommand.java @@ -0,0 +1,116 @@ +package xyz.olivermartin.multichat.spongebridge.commands; + +import java.util.Optional; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.Text; + +import xyz.olivermartin.multichat.spongebridge.DebugManager; +import xyz.olivermartin.multichat.spongebridge.MultiChatSponge; + +public class SpongeProxyExecuteCommand implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource sender, CommandContext rawArgs) throws CommandException { + + Optional strArgs = rawArgs.getOne("message"); + String[] args; + + if (strArgs.isPresent()) { + args = strArgs.get().split(" "); + } else { + sender.sendMessage(Text.of("Usage: /pexecute [-p ] ")); + return CommandResult.success(); + } + + DebugManager.log("[PXE] Getting ready for PXE"); + + // Show usage + if (args.length < 1) { + + sender.sendMessage(Text.of("Usage: /pexecute [-p ] ")); + return CommandResult.success(); + + } else { + + boolean playerFlag = false; + String player = ".*"; + + // Handle flags + int index = 0; + + while (index < args.length) { + + DebugManager.log("[PXE] Index = " + index); + DebugManager.log("[PXE] Current arg is = " + args[index]); + + if (args[index].equalsIgnoreCase("-p")) { + + DebugManager.log("[PXE] IT IS A -p FLAG!"); + + if (index+1 < args.length) { + DebugManager.log("[PXE] And there is another arg too!"); + playerFlag = true; + player = args[index+1]; + DebugManager.log("[PXE] That means we have a player: " + player); + } + + } else { + break; + } + + index = index+2; + + } + + if (index >= args.length) { + sender.sendMessage(Text.of("Usage: /pexecute [-p ] ")); + return CommandResult.success(); + } + + String message = ""; + for (String arg : args) { + if (index > 0) { + DebugManager.log("[PXE] Second loop, index = " + index); + index--; + } else { + message = message + arg + " "; + DebugManager.log("[PXE] Message so far is: " + message); + } + } + + if (Sponge.getServer().getOnlinePlayers().size() < 1) { + sender.sendMessage(Text.of("Sorry, this command is only possible if at least one player is online!")); + return CommandResult.success(); + } + + Player facilitatingPlayer = (Player)Sponge.getServer().getOnlinePlayers().toArray()[0]; + + if (playerFlag) { + + DebugManager.log("[PXE] Player flag true so sending ppxe message!"); + + MultiChatSponge.sendProxyExecutePlayerMessage(facilitatingPlayer, message, player); + + } else { + + DebugManager.log("[PXE] Sending regular pxe message!"); + + MultiChatSponge.sendProxyExecuteMessage(facilitatingPlayer, message); + + } + + sender.sendMessage(Text.of("SENT COMMAND TO PROXY SERVER")); + return CommandResult.success(); + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeRealnameCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeRealnameCommand.java new file mode 100644 index 00000000..8c911676 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeRealnameCommand.java @@ -0,0 +1,84 @@ +package xyz.olivermartin.multichat.spongebridge.commands; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.Text; + +import xyz.olivermartin.multichat.spongebridge.SpongeNameManager; + +public class SpongeRealnameCommand implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { + + if (sender instanceof Player) { + sender = (Player) sender; + } else { + sender.sendMessage(Text.of("Only players can use this command!")); + return CommandResult.success(); + } + + String nickname = args.getOne("nickname").get(); + + if (SpongeNameManager.getInstance().existsNickname(nickname)) { + + Optional player; + player = SpongeNameManager.getInstance().getNameFromNickname(nickname); + + if (player.isPresent()) { + sender.sendMessage(Text.of("Nickname: '" + nickname + "' Belongs to player: '" + player.get() +"'")); + } else { + sender.sendMessage(Text.of("No one could be found with nickname: " + nickname)); + } + + return CommandResult.success(); + + } else if (sender.hasPermission("multichatsponge.realname.partial")) { + + Optional> matches = SpongeNameManager.getInstance().getPartialNicknameMatches(nickname); + + if (matches.isPresent()) { + + int limit = 10; + + sender.sendMessage(Text.of("No one could be found with the exact nickname: " + nickname)); + sender.sendMessage(Text.of("The following were found as partial matches: ")); + + for (UUID uuid : matches.get()) { + + if (limit > 0 || sender.hasPermission("multichatsponge.realname.nolimit")) { + sender.sendMessage(Text.of("Nickname: '" + SpongeNameManager.getInstance().getCurrentName(uuid, false) + "' Belongs to player: '" + SpongeNameManager.getInstance().getName(uuid) + "'")); + limit--; + } else { + sender.sendMessage(Text.of("Only the first 10 results have been shown, please try a more specific query!")); + break; + } + + } + + } else { + + sender.sendMessage(Text.of("No one could be found with nickname: " + nickname)); + + } + + return CommandResult.success(); + + } else { + + sender.sendMessage(Text.of("No one could be found with nickname: " + nickname)); + return CommandResult.success(); + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeUsernameCommand.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeUsernameCommand.java new file mode 100644 index 00000000..efdc51c3 --- /dev/null +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/commands/SpongeUsernameCommand.java @@ -0,0 +1,84 @@ +package xyz.olivermartin.multichat.spongebridge.commands; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.Text; + +import xyz.olivermartin.multichat.spongebridge.SpongeNameManager; + +public class SpongeUsernameCommand implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { + + if (sender instanceof Player) { + sender = (Player) sender; + } else { + sender.sendMessage(Text.of("Only players can use this command!")); + return CommandResult.success(); + } + + String username = args.getOne("username").get(); + + if (SpongeNameManager.getInstance().existsPlayer(username)) { + + Optional player; + player = SpongeNameManager.getInstance().getFormattedNameFromName(username); + + if (player.isPresent()) { + sender.sendMessage(Text.of("User exists with name: '" + player.get() +"'")); + } else { + sender.sendMessage(Text.of("No one could be found with name: " + username)); + } + + return CommandResult.success(); + + } else if (sender.hasPermission("multichatsponge.username.partial")) { + + Optional> matches = SpongeNameManager.getInstance().getPartialNameMatches(username); + + if (matches.isPresent()) { + + int limit = 10; + + sender.sendMessage(Text.of("No one could be found with the exact username: " + username)); + sender.sendMessage(Text.of("The following were found as partial matches: ")); + + for (UUID uuid : matches.get()) { + + if (limit > 0 || sender.hasPermission("multichatsponge.username.nolimit")) { + sender.sendMessage(Text.of("- '" + SpongeNameManager.getInstance().getName(uuid) + "'")); + limit--; + } else { + sender.sendMessage(Text.of("Only the first 10 results have been shown, please try a more specific query!")); + break; + } + + } + + } else { + + sender.sendMessage(Text.of("No one could be found with username: " + username)); + + } + + return CommandResult.success(); + + } else { + + sender.sendMessage(Text.of("No one could be found with username: " + username)); + return CommandResult.success(); + + } + + } + +} diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/BungeePlayerCommandListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/BungeePlayerCommandListener.java index ca655204..9e528bf6 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/BungeePlayerCommandListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/BungeePlayerCommandListener.java @@ -1,11 +1,22 @@ package xyz.olivermartin.multichat.spongebridge.listeners; +import java.util.LinkedList; +import java.util.Optional; +import java.util.Queue; + import org.spongepowered.api.Platform; 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.spongebridge.DebugManager; +import xyz.olivermartin.multichat.spongebridge.MultiChatSponge; /** * Used to execute player specific commands sent from MultiChat on bungeecord @@ -22,13 +33,61 @@ public BungeePlayerCommandListener() { @Override public void handlePayload(ChannelBuf data, RemoteConnection connection, Platform.Type side) { - String playerRegex = data.getUTF(0); - String command = data.getUTF(0); + String playerRegex = data.readUTF(); + String command = data.readUTF(); + + DebugManager.log("[MCE-P] Got player: " + playerRegex + ", and command: " + command); + + /* THIS BIT NOW IS A BIT OF A HACK! */ + + /* + * To implement sending single messages to global or local chat channels, we do a nice hack... + * We send a "command" of local or global chat... + * Then we deal with it here and add to the "CHAT QUEUE" in the MultiChatSponge class + * And then we send the chat message as if it were normal, but it will check the CHAT QUEUE to deal with it... + */ + + if (command.startsWith("!SINGLE L MESSAGE!") || command.startsWith("!SINGLE G MESSAGE!")) { + + DebugManager.log("[MCE-P] Doing the local global direct message hack!"); + + String message = command.substring("!SINGLE X MESSAGE!".length(),command.length()); + + if (MultiChatSponge.chatQueues.containsKey(playerRegex.toLowerCase())) { + + Queue chatQueue = MultiChatSponge.chatQueues.get(playerRegex.toLowerCase()); + chatQueue.add(command); + + } else { + + Queue chatQueue = new LinkedList(); + chatQueue.add(command); + MultiChatSponge.chatQueues.put(playerRegex.toLowerCase(), chatQueue); + + } + + Optional opPlayer = Sponge.getServer().getPlayer(playerRegex); + if (opPlayer.isPresent()) { + EventContext context = EventContext.builder() + .add(EventContextKeys.PLAYER_SIMULATED, opPlayer.get().getProfile()) + .add(EventContextKeys.PLUGIN, Sponge.getPluginManager().getPlugin("multichat").get()) + .build(); + opPlayer.get().simulateChat(Text.of(message), Cause.builder().append(opPlayer.get()).append(Sponge.getPluginManager().getPlugin("multichat").get()).build(context)); + } + + return; + + } + + /* END HACK */ for (Player p : Sponge.getServer().getOnlinePlayers()) { if (p.getName().matches(playerRegex)) { + DebugManager.log("[MCE-P] Player match found: " + p.getName()); + DebugManager.log("[MCE-P] Getting them to execute command: " + command); + Sponge.getCommandManager().process(p, command); } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeChatListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeChatListener.java index 9ca0b65a..f106a7e0 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeChatListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeChatListener.java @@ -33,11 +33,30 @@ public void onChat(MessageChannelEvent.Chat event) { Set onlinePlayers = new HashSet(Sponge.getServer().getOnlinePlayers()); Iterator it = onlinePlayers.iterator(); + String queueValue = ""; + // Deal with ignores and channel members if (MultiChatSponge.playerChannels.containsKey(player)) { String channelName = MultiChatSponge.playerChannels.get(player); + if (MultiChatSponge.chatQueues.containsKey(player.getName().toLowerCase())) { + // Hack for /global /local direct messaging... + String tempChannel = MultiChatSponge.chatQueues.get(player.getName().toLowerCase()).poll(); + + if (MultiChatSponge.chatQueues.get(player.getName().toLowerCase()).size() < 1) { + MultiChatSponge.chatQueues.remove(player.getName().toLowerCase()); + } + + if(tempChannel.startsWith("!SINGLE L MESSAGE!")) { + channelName = "local"; + } else { + channelName = "global"; + } + + queueValue = channelName; + } + if (MultiChatSponge.channelObjects.containsKey(channelName)) { PseudoChannel channelObject = MultiChatSponge.channelObjects.get(channelName); @@ -74,6 +93,23 @@ public void onChat(MessageChannelEvent.Chat event) { } + if (queueValue.equals("")) { + if (MultiChatSponge.chatQueues.containsKey(player.getName().toLowerCase())) { + // Hack for /global /local direct messaging... + String tempChannel = MultiChatSponge.chatQueues.get(player.getName().toLowerCase()).poll(); + + if (MultiChatSponge.chatQueues.get(player.getName().toLowerCase()).size() < 1) { + MultiChatSponge.chatQueues.remove(player.getName().toLowerCase()); + } + + if(tempChannel.startsWith("!SINGLE L MESSAGE!")) { + queueValue = "local"; + } else { + queueValue = "global"; + } + } + } + String channel; String format; String message = event.getRawMessage().toPlain(); @@ -84,6 +120,10 @@ public void onChat(MessageChannelEvent.Chat event) { channel = "global"; } + if (!queueValue.equals("")) { + channel = queueValue; + } + if (channel.equals("local")) { // Local chat @@ -126,7 +166,7 @@ public void onChat(MessageChannelEvent.Chat event) { DebugManager.log("PlaceholderAPI is present"); - + format = TextSerializers.FORMATTING_CODE.serialize(MultiChatSponge.papi.get().replaceSourcePlaceholders(format+"#", event.getSource())); // PAPI replaces unknown placeholders with {key}, so change them back to %key%!! format = format.substring(0,format.length()-1); @@ -167,7 +207,7 @@ public void onChat(MessageChannelEvent.Chat event) { DebugManager.log("Here is exactly how the message is formatted:"); Sponge.getGame().getServer().getConsole().sendMessage(toSend); } - + DebugManager.log("The text in plaintext form is: " + toSend.toString()); } else { @@ -181,7 +221,7 @@ public void onChat(MessageChannelEvent.Chat event) { // IF WE ARE MANAGING GLOBAL CHAT THEN WE NEED TO MANAGE IT! if (MultiChatSponge.globalChatServer) { - + DebugManager.log("This server is linked to the global chat!"); event.setCancelled(true); @@ -204,7 +244,21 @@ public void onChat(MessageChannelEvent.Chat event) { MultiChatSponge.updatePlayerMeta(player.getName(), MultiChatSponge.setDisplayNameLastVal, MultiChatSponge.displayNameFormatLastVal); if (MultiChatSponge.playerChannels.containsKey(player)) { - if (!MultiChatSponge.playerChannels.get(player).equals("local")) { + + if (queueValue.equals("local")) { + return; + } else if (queueValue.equals("global")) { + + // TODO Somehow use the Sponge format so that other plugins can edit it (instead of just the global format here and the .toPlain) + // None of this is ideal, as event.getMessage() actually returns the WHOLE message that would be sent including name etc. + DebugManager.log("We need to send the message to bungeecord!"); + DebugManager.log("Data to send is: "); + DebugManager.log("PLAYER:" + player.getName()); + DebugManager.log("MESSAGE:" + message); + DebugManager.log("FORMAT: " + format.replace("%", "%%")); + MultiChatSponge.sendChatToBungee(player, message, format.replace("%", "%%")); + + } else if ((!MultiChatSponge.playerChannels.get(player).equals("local"))) { // TODO Somehow use the Sponge format so that other plugins can edit it (instead of just the global format here and the .toPlain) // None of this is ideal, as event.getMessage() actually returns the WHOLE message that would be sent including name etc. @@ -216,6 +270,7 @@ public void onChat(MessageChannelEvent.Chat event) { MultiChatSponge.sendChatToBungee(player, message, format.replace("%", "%%")); } + } } diff --git a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeLoginListener.java b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeLoginListener.java index 40a9fdd8..ca92af9c 100644 --- a/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeLoginListener.java +++ b/multichat/src/main/java/xyz/olivermartin/multichat/spongebridge/listeners/SpongeLoginListener.java @@ -5,25 +5,49 @@ import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; +import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.network.ClientConnectionEvent; +import xyz.olivermartin.multichat.spongebridge.DebugManager; import xyz.olivermartin.multichat.spongebridge.MultiChatSponge; +import xyz.olivermartin.multichat.spongebridge.SpongeNameManager; public class SpongeLoginListener { - @Listener(order=Order.POST) - public void onLogin(ClientConnectionEvent.Login event) { + /*@Listener(order=Order.POST) + public void onLogin(ClientConnectionEvent.Login event, @Root Player player) { - Optional playerOptional = event.getCause().first(Player.class); + DebugManager.log("Login event!"); - if (playerOptional.isPresent()) { + //Optional playerOptional = event.getCause().first(Player.class); - Player p = playerOptional.get(); + //if (playerOptional.isPresent()) { + + //Player p = playerOptional.get(); + + DebugManager.log("Player: " + player.getName()); + + SpongeNameManager.getInstance().registerPlayer(player); + + if (!MultiChatSponge.playerChannels.containsKey(player)) { + MultiChatSponge.playerChannels.put(player, "global"); + } + + //} + + }*/ + + @Listener(order=Order.POST) + public void onJoin(ClientConnectionEvent.Join event, @Root Player player) { + + DebugManager.log("Join event!"); + + DebugManager.log("Player: " + player.getName()); - if (!MultiChatSponge.playerChannels.containsKey(p)) { - MultiChatSponge.playerChannels.put(p, "global"); - } + SpongeNameManager.getInstance().registerPlayer(player); + if (!MultiChatSponge.playerChannels.containsKey(player)) { + MultiChatSponge.playerChannels.put(player, "global"); } } @@ -34,8 +58,11 @@ public void onLogout(ClientConnectionEvent.Disconnect event) { Optional playerOptional = event.getCause().first(Player.class); if (playerOptional.isPresent()) { + + DebugManager.log("Disconnecting player..."); Player p = playerOptional.get(); + SpongeNameManager.getInstance().unregisterPlayer(p); MultiChatSponge.playerChannels.remove(p); } diff --git a/multichat/src/main/resources/bungee.yml b/multichat/src/main/resources/bungee.yml index e2e15d27..541c4ca4 100644 --- a/multichat/src/main/resources/bungee.yml +++ b/multichat/src/main/resources/bungee.yml @@ -1,5 +1,5 @@ name: MultiChat main: xyz.olivermartin.multichat.bungee.MultiChat -version: 1.7.5 +version: 1.8 author: Revilo410 -api-version: 1.13 \ No newline at end of file +api-version: 1.15 \ No newline at end of file diff --git a/multichat/src/main/resources/chatcontrol.yml b/multichat/src/main/resources/chatcontrol.yml index 71045912..d7370b1b 100644 --- a/multichat/src/main/resources/chatcontrol.yml +++ b/multichat/src/main/resources/chatcontrol.yml @@ -8,11 +8,13 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## # 1. Chat Control Rules -# 2. Mute and Ignore Settings +# 2. Anti-Spam Settings +# 3. Mute and Ignore Settings +# 4. Link / URL Controls ############################################################ # +------------------------------------------------------+ # diff --git a/multichat/src/main/resources/chatcontrol_fr.yml b/multichat/src/main/resources/chatcontrol_fr.yml new file mode 100644 index 00000000..2ba13a38 --- /dev/null +++ b/multichat/src/main/resources/chatcontrol_fr.yml @@ -0,0 +1,202 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChat | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +################# +# NE PAS EDITER # +version: "1.8" # +################# + +# French Translation by Nogapra - Thank you ! +# Pour utiliser ce fichier, renommer en 'chatcontrol.yml'. + +# 1. Règles de Control de Chat +# 2. Paramètres d'anti-spam +# 3. Paramètres de mute et d'ignore +# 4. Contrôle de Liens / URL + +############################################################ +# +------------------------------------------------------+ # +# | Règles de Control de Chat | # +# +------------------------------------------------------+ # +############################################################ + +# Il s’agit de règles d’expression régulière personnalisées pour modifier les messages envoyés via le chat. +# L'expression à remplacée se trouve sous la valeur "look_for", et la valeur de remplacement se trouve sous le champ "replace_with". + +# Ceux-ci peuvent être utilisés pour filtrer le langage inapproprié du chat ainsi que beaucoup d’autres choses. +# Quelques exemples sont présentés ci-dessous... + +regex_rules: +# Exemple de règle pour remplacer [bold] par le code de format %l pour faire du texte en gras +- look_for: '\[bold\]' + replace_with: "&l" +# Exemple de règle pour remplacer [italic] par le code de format %o pour faire du texte en italique +- look_for: '\[italic\]' + replace_with: "&o" + +# Dans quels types de chat les règles de regex doivent t'elle être appliquées ? +# Paramétrage disponible : true ou false +apply_rules_to: + global_chat: true + private_messages: false + group_chats: false + staff_chats: false + display_command: false + announcements: false + bulletins: false + casts: false + helpme: false + +# Il s’agit d’actions déclenchées par une expression régulière personnalisée. +# L’expression régulière dans "look_for", déclenche la commande dans "commande" +# vous pouvez choisir d’annuler l’événement de chat de joueurs en définissant "annuler" à true. +# Réglage "Spigot" à true enverra la commande au serveur Spigot local +# ou le joueur est actuellement et l’exécutera là au lieu du bungeecord serveur. + +# Ceux-ci peuvent être utilisés pour filtrer le langage inapproprié du chat ainsi que beaucoup d’autres choses. +# Quelques exemples sont présentés ci-dessous... + +# Vous pouvez utiliser %PLAYER% pour faire référence au joueur qui envoie le message. + +regex_actions: +# Exemple de règle pour kick quelqu’un qui dit une phrase spécifique. +- look_for: 'kickmeplzrightnow' + command: "kick %PLAYER% Vous l'avez demandé !" + cancel: false + spigot: true + +# Dans quels types de chat les action de regex doivent t'elles être appliquées ? +# Paramétrage disponible : true ou false +apply_actions_to: + global_chat: true + private_messages: false + group_chats: false + staff_chats: false + helpme: false + +############################################################ +# +------------------------------------------------------+ # +# | Paramètres d'anti-spam | # +# +------------------------------------------------------+ # +############################################################ + +# Permet d'activer l'anti-spam de Multichat +# Paramétrage disponible : true ou false +anti_spam: true + +############################## +# Minuterie de déclenchement # +############################## + +# Définie le nombre de seconde autorisant un joueur à envoyer 4 messages avant de déclencher l’anti-spam. +anti_spam_time: 4 + +################################################ +# Nombre de message identique de déclenchement # +################################################ + +# Definie le nombre de message identique envoyé dans un laps de temps très court pour déclencher l'anti-spam. +spam_same_message: 4 + +########################## +# Actions de l'anti-spam # +########################## + +# Combien de secondes un joueur doit-il attendre avant d’envoyer un message une fois qu’il a déclenché l’anti-spam ? +anti_spam_cooldown: 60 + +# Une commande doit-elle être déclenchée si l’anti-spam est activée un certain nombre de fois pour le même joueur ? +# Paramétrage disponible : true ou false +anti_spam_action: true + +# Définie si cette commande est exécutée sur Spigot (par opposition à bungeecord). +# Paramétrage disponible : true ou false +anti_spam_spigot: true + +# Combien de fois l’anti-spam doit-il être déclenché avant d’envoyer la commande ? +anti_spam_trigger: 3 + +# Quelle commande doit être envoyée ? (%PLAYER% est le joueur qui a déclenché l’anti-spam). +anti_spam_command: "kick %PLAYER% le spam n'est pas autorisé" + +# Dans quels types de chat l'anti_spam doit t'il être appliqué ? +# Paramétrage disponible : true ou false +apply_anti_spam_to: + global_chat: true + private_messages: true + group_chats: true + helpme: true + +############################################################ +# +------------------------------------------------------+ # +# | Paramètres de mute et d'ignore | # +# +------------------------------------------------------+ # +############################################################ + +################# +# Commande Mute # +################# + +# Utiliser la commande mute de Multichat ? +# Définissez la valeur sur false si vous avez un autre plugin bungeecord qui traite ce genre de commande. +# Paramétrage disponible : true ou false +mute: false + +# Dans quels types de chat le mute doit-il être appliqué ? +# Paramétrage disponible : true ou false +apply_mute_to: + global_chat: true + private_messages: false + group_chats: false + helpme: false + +# Alias de commande MUTE (en plus de /multichatmute). +mutecommand: +- mute +- mcmute + +################### +# Commande Ignore # +################### + +# Paramètre de commande ignore de pour stopper la visibilité des message d'un joueur spécifique. + +# Une notification doit-elle être envoyée aux joueurs si un joueur qu’ils ignorent a envoyé un message ? +# Paramétrage disponible : true ou false +notify_ignore: false + +# Session ignorer (devrait ignorer les messages que pendant la dernière session de connection ?) +# AVERTISSEMENT: l’activation de la session ignore (évidemment) supprimera les données ignorées des joueurs hors-ligne. +# Paramétrage disponible : true ou false +session_ignore: false + +# Dans quels types de chat la commande /ignore doit t'elle être appliquée ? +# Paramétrage disponible : true ou false +apply_ignore_to: + global_chat: true + private_messages: true + group_chats: false + +# Alias de commande ignore (en plus de la commande /ignore) + +ignorecommand: +- blockchat + +############################################################ +# +------------------------------------------------------+ # +# | Contrôle de Liens / URL | # +# +------------------------------------------------------+ # +############################################################ + +# Le contrôle MultiChat doit-il permettre aux joueurs d’envoyer des liens vers le chat ? +# Si la valeur est true, alors seuls les joueurs avec la permission Multichat.chat.Link seront en mesure d’envoyer des liens. +# Paramétrage disponible : true ou false +link_control: false + +# Remplacer les liens / URL dans les message par : +link_removal_message: "[Lien WEB supprimé]" \ No newline at end of file diff --git a/multichat/src/main/resources/config.yml b/multichat/src/main/resources/config.yml index 60e73d82..824aaa49 100644 --- a/multichat/src/main/resources/config.yml +++ b/multichat/src/main/resources/config.yml @@ -8,15 +8,16 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## # 1. General # 2. Private Messaging -# 3. Global Chat -# 4. Group Chats -# 5. Staff Chats -# 6. Other +# 3. Chat Channels +# 4. Global Chat +# 5. Group Chats +# 6. Staff Chats +# 7. Other ############################################################ # +------------------------------------------------------+ # @@ -138,6 +139,14 @@ force_channel_on_join: false 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 | # @@ -250,3 +259,9 @@ multichatexecutecommand: - gexecute - gexe - gcommand + +# Control what aspects of chat are logged by MultiChat (useful for GDPR etc.) +privacy_settings: + log_pms: true + log_staffchat: true + log_groupchat: true diff --git a/multichat/src/main/resources/config_fr.yml b/multichat/src/main/resources/config_fr.yml new file mode 100644 index 00000000..a2c55282 --- /dev/null +++ b/multichat/src/main/resources/config_fr.yml @@ -0,0 +1,272 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChat | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +################# +# NE PAS EDITER # +version: "1.8" # +################# + +# French Translation by Nogapra - Thank you ! +# Pour utiliser ce fichier, renommer en 'config.yml' + +# 1. Général +# 2. Messages privés +# 3. Cannaux de chat +# 4. Chat global +# 5. Chats de groupe +# 6. Chat de staff +# 7. Divers + +############################################################ +# +------------------------------------------------------+ # +# | Général | # +# +------------------------------------------------------+ # +############################################################ + +# Définie si MultiChat doit chercher les noms d’affichage des joueurs respectifs à utiliser sur les serveur Spigot +# plutôt que ceux mis sur les serveur bungeecord dans le chat global ? +# Définissez cette valeur sur true si vous souhaitez utiliser des noms d’affichage définis +# par des plugins tels que Essentials, Vault, etc. +# Si vous souhaitez utiliser des noms d’affichage définis par un plugin de serveur bungeecord tel que BungeePerms, +# définissez-le sur false. +# S’IL VOUS PLAÎT NOTER QUE SI CELA EST RÉGLÉ SUR TRUE, CHAT NE FONCTIONNERA QUE SI VOUS AVEZ ÉGALEMENT MIs LE MULTICHAT.JAR +# DANS LES DOSSIERS PLUGIN DES SERVEURS SPIGOT AINSI QUE DANS LE DOSSIER PLUGINS DU SERVEUR BUNGEECORD ! +# Paramétrage disponible : true ou false +fetch_spigot_display_names: true + +# Définie si MultiChat utilise le nom d’affichage des utilisateurs dans des choses comme le TAB list et/glist ? +# Paramétrage disponible : true ou false +set_display_name: true + +# Formatage du nom d'affichage. +# Vous pouvez utiliser : %NAME%, %NICK%, %PREFIX%, %SUFFIX% +display_name_format: "%PREFIX%%NICK%%SUFFIX%" + +############################################################ +# +------------------------------------------------------+ # +# | Messages privés | # +# +------------------------------------------------------+ # +############################################################ + +########################### +# Module de message privé # +########################### + +# Utiliser la messagerie privée ? +# Paramétrage disponible : true ou false +pm: true + +# Serveurs à exclure de la messagerie privée. +# Lister les serveurs comme ceci : +# no_pm: +# - Server1 +# - Server2 +# etc. +no_pm: [] + +# Permettez aux joueurs de d'activer le canal de message privé en tapant simplement /msg +# Paramétrage disponible : true ou false +toggle_pm: true + +################################## +# Formattage des messages privés # +################################## + +# Utilisez les codes couleur de minecraft standard '&X' COLOUR/FORMAT CODES. +# %MESSAGE% = Le message envoyé +# %NAME% = Le nom de l’expéditeur +# %NAMET% = Le nom du joueur cible +# %DISPLAYNAME% = Le nom d'affichage de l’expéditeur +# %DISPLAYNAMET% = Le nom d'affichage du joueur cible +# %PREFIX% = Le préfixe de l’expéditeur +# %PREFIXT% = Le préfixe du joueur cible +# %SUFFIX% = Le suffixe de l’expéditeur +# %SUFFIXT% = Le suffixe du joueur cible +# %NICK% = Le surnom de l’expéditeur +# %NICKT% = Le surnom du joueur cible +# %SERVER% = Le serveur de l’expéditeur +# %SERVERT% = Le serveur du joueur cible +# %WORLD% = Le monde de l’expéditeur +# %WORLDT% = Le monde du joueur cible + +# formatage d'envoie de message privé. +pmout: "&6[&cYou &6-> &c%DISPLAYNAMET%&6] &f%MESSAGE%" + +# Formatage de réception d'un message privé. +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 | # +# +------------------------------------------------------+ # +############################################################ + +# Le canal de chat par défaut ou les joueurs seront affectés lors de leur connexion. +# Doit être "local" ou "global", si quelque chose d’autre est spécifié alors sera par défaut "global". +default_channel: "global" + +# Forcer les joueurs dans le canal par défaut quand ils rejoignent le serveur ? +# 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 | # +# +------------------------------------------------------+ # +############################################################ + +######################### +# Module de chat global # +######################### + +# Utiliser le chat public global ? +# Paramétrage disponible : true ou false +global: true + +# Serveurs à exclure du chat global. +# Lister les serveurs comme ceci : +# no_global: +# - Server1 +# - Server2 +# etc. +no_global: [] + +########################## +# Formata du chat global # +########################## + +# Utilisez les codes couleur de minecraft standard '&X' COLOUR/FORMAT CODES. +# %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] +globalformat: "&2[&aG&2] &f%DISPLAYNAME%&f: " + +############################################################ +# +------------------------------------------------------+ # +# | Chats de groupe | # +# +------------------------------------------------------+ # +############################################################ + +################################# +# Formatage des chats de groupe # +################################# + +# Utilisez les codes couleur de minecraft standard '&X' COLOUR/FORMAT CODES. +# %NAME% = Le nom de l’expéditeur +# %MESSAGE% = Le message envoyé +# %CC% = La couleur de chat définie par les joueurs +# %NC% = La couleur du nom définie par les joueurs +# %GROUPNAME% = Nom du chat de groupe +groupchat: + format: "%CC%(%NC%%GROUPNAME%%CC%)(%NC%%NAME%%CC%) %MESSAGE%" + ccdefault: "a" + ncdefault: "f" + +############################################################ +# +------------------------------------------------------+ # +# | Chat de staff | # +# +------------------------------------------------------+ # +############################################################ + +############################## +# Formatage du chat de staff # +############################## + +# Utilisez les codes couleur de minecraft standard '&X' COLOUR/FORMAT CODES. +# %NAME% = Le nom de l’expéditeur +# %DISPLAYNAME% = Le nom d'affichage de l’expéditeur +# %SERVER% = Le serveur de l’expéditeur +# %WORLD% = Le monde de l’expéditeur +# %MESSAGE% = Le message envoyé +# %CC% = La couleur de chat définie par les joueurs +# %NC% = La couleur du nom définie par les joueurs +modchat: + format: "%CC%{%NC%%NAME%%CC%} %MESSAGE%" + ccdefault: "b" + ncdefault: "d" + +adminchat: + format: "%CC%{%NC%%NAME%%CC%} %MESSAGE%" + ccdefault: "d" + ncdefault: "b" + +############################################################ +# +------------------------------------------------------+ # +# | Divers | # +# +------------------------------------------------------+ # +############################################################ + +# Affectez la valeur false pour désactiver la commande de liste de personnel '/staff'. +# 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 + log_staffchat: true + log_groupchat: true diff --git a/multichat/src/main/resources/joinmessages.yml b/multichat/src/main/resources/joinmessages.yml index 897e799a..eb963240 100644 --- a/multichat/src/main/resources/joinmessages.yml +++ b/multichat/src/main/resources/joinmessages.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## ############################################################ @@ -48,7 +48,7 @@ silentquit: "&b&o%NAME% &b&oleft the network silently" ############################################################## -# Should a welcome message be displayed the first time a player joins the network? +# Should a welcome message be broadcast to the network the first time a player joins? welcome: true @@ -57,3 +57,12 @@ welcome: true # %NAME% = The name of the sender welcome_message: "&dWelcome %NAME% to the network for the first time!" + +# Should a private welcome message (separate to the one above) be sent to the player the first time they join the network? + +private_welcome: false + +# Define the private welcome message here +# USES STANDARD MINECRAFT '&X' COLOUR/FORMAT CODES +# %NAME% = The name 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 abc8afb1..431fee44 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.7.5" # +version: "1.8" # ################## # French Translation by Nogapra - Thank you! @@ -53,7 +53,7 @@ silentquit: "%NAME% &b&os'est déconnecté silencieusement" ############################################################## -# Un message de bienvenue doit-il être affiché la première fois qu'un joueur rejoint le réseau ? +# Un message de bienvenue doit-il être diffusé sur l’ensemble du réseau la première fois qu'un joueur rejoint? # Paramétrage disponible : true ou false welcome: true @@ -63,3 +63,13 @@ welcome: true # %NAME% = Le nom du joueur welcome_message: "&dBienvenue %NAME% pour votre première connexion sur nos serveurs!" + +# Un autre message de bienvenue doit-il être affiché au joueur qui se connecte uniquement? + +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 + +private_welcome_message: "&dSalut %NAME%! S'il vous plaît lire les règles!" diff --git a/multichat/src/main/resources/messages.yml b/multichat/src/main/resources/messages.yml index 9e617a6e..18fc83b5 100644 --- a/multichat/src/main/resources/messages.yml +++ b/multichat/src/main/resources/messages.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## ############################################################ diff --git a/multichat/src/main/resources/messages_fr.yml b/multichat/src/main/resources/messages_fr.yml index bb5703f5..3c17b2a1 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.7.5" # +version: "1.8" # ################## # French Translation by Nogapra - Thank you! diff --git a/multichat/src/main/resources/multichatsponge.yml b/multichat/src/main/resources/multichatsponge.yml index 1281294e..2f418aa0 100644 --- a/multichat/src/main/resources/multichatsponge.yml +++ b/multichat/src/main/resources/multichatsponge.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## # Specify the name of this server here for the %SERVER% placeholder @@ -78,3 +78,23 @@ show_nickname_prefix: false # What should the prefix before nicknames be? nickname_prefix: "~" + +# The maximum length for nicknames +nickname_length_limit: 20 + +# The minimum length for nicknames +nickname_length_min: 3 + +# Should formatting codes such as "&3" be counted in the length of the nickname? +nickname_length_limit_formatting: false + +# Should MultiChat use a database to store nicknames instead of regular files? +# (PLEASE NOTE THE SERVER MUST BE RESTARTED FOR THIS TO TAKE EFFECT) +nickname_sql: false + +# If the above option is true, MultiChat will use SQLite by default. Set the below to true if you would prefer to use MySQL. +mysql: false +mysql_url: "" # For example "localhost:3306" +mysql_database: "" # Put the name of your MySQL database here +mysql_user: "" +mysql_pass: "" diff --git a/multichat/src/main/resources/multichatsponge_fr.yml b/multichat/src/main/resources/multichatsponge_fr.yml new file mode 100644 index 00000000..23187617 --- /dev/null +++ b/multichat/src/main/resources/multichatsponge_fr.yml @@ -0,0 +1,110 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChatSponge | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +################## +# NE PAS EDITER # +version: "1.8" # +################## + +# French Translation by Nogapra - Thank you ! +# Pour utiliser ce fichier, renommer en 'multichatsponge.yml'. + +# Spécifiez le nom de ce serveur ici pour le placeholder %SERVER%. +server_name: "SPONGE" + +#1. Global +#2. Local +#3. Surnom Multichat + +############################################################ +# +------------------------------------------------------+ # +# | Global | # +# +------------------------------------------------------+ # +############################################################ + +# Définie si ce serveur utilise un format différent pour le chat global que celui attribué +# dans le dossier plugins du serveur BungeeCoord ? +# (Utile si vous souhaitez utiliser des Placeholders locaux qui ne peuvent être présents que sur un seul serveur). +# Paramètre disponible : true ou false +override_global_format: false + +# Format à utiliser pour le chat global si le paramètre ci-dessus est défini sur true. +# +# Utiliser les codes couleur Minecraft standard '&X' COLOUR/FORMAT CODES. +# %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. +# +# S’affichera en tant que [FORMAT] [MESSAGE] +override_global_format_format: "&5[&dG&5] &f%DISPLAYNAME%&f: " + +############################################################ +# +------------------------------------------------------+ # +# | Local | # +# +------------------------------------------------------+ # +############################################################ + +# Format à utiliser pour le chat local pour ce serveur. +# +# Utiliser les codes couleur Minecraft standard '&X' COLOUR/FORMAT CODES. +# %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. +# +# S’affichera en tant que [FORMAT] [MESSAGE] +local_chat_format: "&3[&bL&3] &f%DISPLAYNAME%&f: &7" + +############################################################ +# +------------------------------------------------------+ # +# | MultiChat Nicknames | # +# +------------------------------------------------------+ # +############################################################ + + +# Les joueurs ne pourront se renommer avec un surnom de cette liste ! +# (?i) est le regex pour ignorer le cas +nickname_blacklist: +- "(?i)Notch" +- "(?i)Jeb" +#- "[1234567890]+.*" # <-- Exemple pour bloquer les surnoms commençant par un nombre ! + +# Un préfixe doit-il être affiché avant les surnoms pour les différencier des vrais noms ? +# Paramètre disponible : true ou false +show_nickname_prefix: false + +# Que doit être affiché avant le surnom ? +nickname_prefix: "~" + +# Nombre de caratères maximal d'un surnom +nickname_length_limit: 20 + +# Nombre de caratère minimal d'un surnom +nickname_length_min: 3 + +# Faut-il compter les codes de formatage tels que &3 dans le nombre de caractères du surnom ? +nickname_length_limit_formatting: false + +# MultiChat devrait-il utiliser un sytème de base données (MySQL ou SQLite) pour stocker les surnoms au lieu du system de fichier standard? +# (PLEASE NOTE THE SERVER MUST BE RESTARTED FOR THIS TO TAKE EFFECT) +nickname_sql: false + +# Si l’option ci-dessus est true, MultiChat utilisera SQLite par défaut. +# Définissez l'option ci-dessous à true si vous préférez utiliser MySQL. +mysql: false +mysql_url: "" # Adresse IP ou web de la base de données et le port TCP (ex : "localhost:3306") +mysql_database: "" # Nom de la base de données +mysql_user: "" #Utilistateur base de données +mysql_pass: "" #Mot de passe diff --git a/multichat/src/main/resources/plugin.yml b/multichat/src/main/resources/plugin.yml index d11abde5..d16e9bec 100644 --- a/multichat/src/main/resources/plugin.yml +++ b/multichat/src/main/resources/plugin.yml @@ -1,9 +1,8 @@ name: MultiChatSpigot -version: 1.7.5 +version: 1.8 author: Revilo410 main: xyz.olivermartin.multichat.spigotbridge.MultiChatSpigot softdepend: [Vault,PlaceholderAPI] -api-version: 1.14 commands: nick: description: Gives a player a nickname @@ -21,7 +20,18 @@ commands: permission: multichatspigot.username permission-message: You do not have permission (multichatspigot.username) multichatspigot: - description: MultiChatSpigot reload command - usage: /multichatspigot reload + description: MultiChatSpigot reload and migrate commands + usage: /multichatspigot [reload/migratetosql] permission: multichatspigot.reload permission-message: You do not have permission (multichatspigot.reload) + pxe: + description: Proxy Execute - Execute commands on Proxy server + usage: /pxe [-p ] + permission: multichatspigot.pexecute + permission-message: You do not have permission (multichatspigot.pexecute) + pexecute: + description: Proxy Execute - Execute commands on Proxy server + usage: /pexecute [-p ] + permission: multichatspigot.pexecute + permission-message: You do not have permission (multichatspigot.pexecute) + \ No newline at end of file diff --git a/multichat/src/main/resources/spigotconfig.yml b/multichat/src/main/resources/spigotconfig.yml index 319a9a79..c92bbbac 100644 --- a/multichat/src/main/resources/spigotconfig.yml +++ b/multichat/src/main/resources/spigotconfig.yml @@ -8,7 +8,7 @@ ################## # DON'T EDIT # -version: "1.7.5" # +version: "1.8" # ################## # Specify the name of this server here for the %SERVER% placeholder @@ -110,5 +110,19 @@ nickname_prefix: "~" # The maximum length for nicknames nickname_length_limit: 20 +# The minimum length for nicknames +nickname_length_min: 3 + # Should formatting codes such as "&3" be counted in the length of the nickname? nickname_length_limit_formatting: false + +# Should MultiChat use a database to store nicknames instead of regular files? +# (PLEASE NOTE THE SERVER MUST BE RESTARTED FOR THIS TO TAKE EFFECT) +nickname_sql: false + +# If the above option is true, MultiChat will use SQLite by default. Set the below to true if you would prefer to use MySQL. +mysql: false +mysql_url: "" # For example "localhost:3306" +mysql_database: "multichatspigot" # Put the name of your MySQL database here +mysql_user: "" +mysql_pass: "" diff --git a/multichat/src/main/resources/spigotconfig_fr.yml b/multichat/src/main/resources/spigotconfig_fr.yml new file mode 100644 index 00000000..a1f2bf7e --- /dev/null +++ b/multichat/src/main/resources/spigotconfig_fr.yml @@ -0,0 +1,143 @@ +############################################################ +# +------------------------------------------------------+ # +# | MultiChatSpigot | # +# +------------------------------------------------------+ # +############################################################ + +# By Revilo410 + +################## +# NE PAS EDITER # +version: "1.8" # +################## + +# French Translation by Nogapra - Thank you ! +# Pour utiliser ce fichier, renommer en 'spigotconfig.yml'. + +#1. Global +#2. Local +#3. Placeholders MultiChat +#4. Surnom MultiChat + +# Specify the name of this server here for the %SERVER% placeholder +server_name: "SERVER_NAME" + +############################################################ +# +------------------------------------------------------+ # +# | Global | # +# +------------------------------------------------------+ # +############################################################ + +# Définie si ce serveur utilise un format différent pour le chat global que celui attribué +# dans le dossier plugins du serveur BungeeCoord ? +# (Utile si vous souhaitez utiliser des Placeholders locaux qui ne peuvent être présents que sur un seul serveur). +# Paramètre disponible : true ou false +override_global_format: false + +# Format à utiliser pour le chat global si le paramètre ci-dessus est défini sur true. +# +# Utiliser les codes couleur Minecraft standard '&X' COLOUR/FORMAT CODES. +# %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. +# +# S’affichera en tant que [FORMAT] [MESSAGE] +override_global_format_format: "&5[&dG&5] &f%DISPLAYNAME%&f: " + +# Si le paramètre ci-dessous est défini sur true, alors quels que soient les paramètres ci-dessus, +# MultiChat ne touchera pas le format de chat. +# Cela signifie que si un plugin tel que Towny gère le format de chat localement, alors ce sera utilisé à la place. +# MultiChat enverra toujours le message à tous les autres serveurs. +# +# NOTE : CECI EST FAIT SUR UNE BASE DU MEILLEUR EFFORT ! +#(MultiChat est un plugin de formatage de chat est donc conçu pour formater le chat!) +# Paramètre disponible : true ou false +override_all_multichat_formatting: false + +# Définir ce paramètre sur true essaiera de prendre le contrôle malgré un plugin de formatage de chat récalcitrant. +# Paramètre disponible : true ou false +force_multichat_format: false + + +############################################################ +# +------------------------------------------------------+ # +# | Local | # +# +------------------------------------------------------+ # +############################################################ + +# MultiChat doit-il définir le format du chat local ? (Laisser cela à false permet à d’autres plugins de gérer le chat) +# Paramètre disponible : true ou false +set_local_format: true + +#Utiliser les codes couleur Minecraft standard '&X' COLOUR/FORMAT CODES. +# %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. +# +# S’affichera en tant que [FORMAT] [MESSAGE] +local_chat_format: "&3[&bL&3] &f%DISPLAYNAME%&f: &7" + +############################################################ +# +------------------------------------------------------+ # +# | Placeholders MultiChat | # +# +------------------------------------------------------+ # +############################################################ + +# Ce paramètre vous permet d’utiliser des variables discussion dans d’autres plugins! +# Par exemple, si vous utilisez le chat Essentials pour votre chat local, mais que vous vouliez utiliser un Pseudo de multichat. +# Vous pouvez spécifier le PlaceHolder {multichat_nickname} comme défini ci-dessous. MultiChat l’analysera comme d’habitude. +# Essentials ne prend pas en charge l’API de Placeholder par défaut, +# mais vous pouvez toujours utiliser les PlaceHolder PAPI en en paramétrant un ci-dessous! +# {multichat_papi_displayname} will be replaced using the example below and parsed by multichat. +multichat_placeholders: + nickname: "%NICK%" + papi_displayname: "%player_displayname%" + +############################################################ +# +------------------------------------------------------+ # +# | Surnom MultiChat | # +# +------------------------------------------------------+ # +############################################################ + +# Les joueurs ne pourront se renommer avec un surnom de cette liste ! +# (?i) est le regex pour ignorer le cas. +nickname_blacklist: +- "(?i)Notch" +- "(?i)Jeb" +#- "[1234567890]+.*" # <-- Exemple pour bloquer les surnoms commençant par un nombre ! + +# Un préfixe doit-il être affiché avant les surnoms pour les différencier des vrais noms ? +# Paramètre disponible : true ou false +show_nickname_prefix: false + +# Que doit être affiché avant le surnom ? +nickname_prefix: "~" + +# Nombre de caratères maximal d'un surnom +nickname_length_limit: 20 + +# Nombre de caratère minimal d'un surnom +nickname_length_min: 3 + +# Faut-il compter les codes de formatage tels que &3 dans le nombre de caractères du surnom ? +nickname_length_limit_formatting: false + +# MultiChat devrait-il utiliser un sytème de base données (MySQL ou SQLite) pour stocker les surnoms au lieu du system de fichier standard? +# (PLEASE NOTE THE SERVER MUST BE RESTARTED FOR THIS TO TAKE EFFECT) +nickname_sql: false + +# Si l’option ci-dessus est true, MultiChat utilisera SQLite par défaut. +# Définissez l'option ci-dessous à true si vous préférez utiliser MySQL. +mysql: false +mysql_url: "" # Adresse IP ou web de la base de données et le port TCP (ex : "localhost:3306") +mysql_database: "multichatspigot" # Nom de la base de données +mysql_user: "" #Utilistateur base de données +mysql_pass: "" #Mot de passe