From f8618a7a82c0f5344b6cfaf4442ba2c36e902abd Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 29 May 2021 17:39:06 +0200 Subject: [PATCH 01/41] Remove bau passthrough Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 1 + .../bungeecore/commands/BauCommand.java | 106 +++++++++--------- .../bungeecore/comms/PacketIdManager.java | 1 + .../comms/packets/BaumemberUpdatePacket.java | 36 ++++++ .../bungeecore/listeners/ChatListener.java | 6 - 5 files changed, 93 insertions(+), 57 deletions(-) create mode 100644 src/de/steamwar/bungeecore/comms/packets/BaumemberUpdatePacket.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 2344d565..e3a11b01 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -123,6 +123,7 @@ public class BungeeCore extends Plugin { new ResourcereloadCommand(); if(!EVENT_MODE){ + new BauCommand(); new WebregisterCommand(); new FightCommand(); new ChallengeCommand(); diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index 43944d72..d50f7a76 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -20,38 +20,38 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; +import de.steamwar.bungeecore.comms.packets.BaumemberUpdatePacket; import de.steamwar.bungeecore.inventory.SWInventory; import de.steamwar.bungeecore.inventory.SWItem; import de.steamwar.bungeecore.sql.BauweltMember; import de.steamwar.bungeecore.sql.SteamwarUser; +import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.event.ChatEvent; -public class BauCommand { +public class BauCommand extends BasicCommand { - private BauCommand(){} + public BauCommand(){ + super("bau", null, "b", "gs"); + } - public static void onBau(ChatEvent e, String[] command){ - if(BungeeCore.EVENT_MODE) + @Override + public void execute(CommandSender sender, String[] args) { + if(!(sender instanceof ProxiedPlayer)) return; - ProxiedPlayer p = (ProxiedPlayer) e.getSender(); - Subserver server = Subserver.getSubserver(p); - Bauserver bau = (server != null && server.getType() == Servertype.BAUSERVER) ? (Bauserver)server : null; - boolean ownBau = bau != null && bau.getOwner().equals(p.getUniqueId()); - e.setCancelled(true); - BungeeCore.log(p, e.getMessage()); + ProxiedPlayer p = (ProxiedPlayer) sender; - if(command.length == 1){ - if(bau15(p, command, 1)) + if(args.length == 0){ + if(bau15(p, args, 0)) SubserverSystem.sendToBau15(p, p.getUniqueId()); else SubserverSystem.sendToBauServer(p, p.getUniqueId()); return; } - switch(command[1].toLowerCase()){ + switch(args[0].toLowerCase()){ case "ws": case "warship": case "12": @@ -72,52 +72,44 @@ public class BauCommand { SubserverSystem.sendToBau15paper(p, p.getUniqueId()); break; case "addmember": - addmember(p, command); + addmember(p, args); break; case "tp": case "teleport": - teleport(p, command); + teleport(p, args); break; case "info": - if (bau != null) { - e.setCancelled(false); - } + p.chat("/bauinfo"); break; case "togglewe": - if(ownBau && command.length > 2) - e.setCancelled(false); - else - togglewe(p, command); + togglewe(p, args); break; case "toggleworld": - if(ownBau && command.length > 2) - e.setCancelled(false); - else - toggleworld(p, command); + toggleworld(p, args); break; case "delmember": - delmember(p, command); + delmember(p, args); break; case "resetall": case "delete": - delete(p, command); + delete(p, args); break; case "testarena": case "test": - testarena(p, command); + testarena(p, args); break; default: HelpCommand.sendBauHelp(p); } } - private static void addmember(ProxiedPlayer p, String[] command){ - if (command.length == 2) { + private static void addmember(ProxiedPlayer p, String[] args){ + if (args.length == 1) { Message.send("BAU_ADDMEMBER_USAGE", p); return; } - SteamwarUser target = SteamwarUser.get(command[2]); + SteamwarUser target = SteamwarUser.get(args[1]); if (target == null) { Message.send("UNKNOWN_PLAYER", p); return; @@ -137,13 +129,13 @@ public class BauCommand { Message.send("BAU_ADDMEMBER_ADDED_TARGET", z, p.getName()); } - private static void teleport(ProxiedPlayer p, String[] command){ - if (command.length == 2) { + private static void teleport(ProxiedPlayer p, String[] args){ + if (args.length == 1) { Message.send("BAU_TP_USAGE", p); return; } - SteamwarUser worldOwner = SteamwarUser.get(command[2]); + SteamwarUser worldOwner = SteamwarUser.get(args[1]); if (worldOwner == null) { Message.send("UNKNOWN_PLAYER", p); return; @@ -153,7 +145,7 @@ public class BauCommand { return; } - if(bau15(p, command, 3)) + if(bau15(p, args, 2)) SubserverSystem.sendToBau15(p, worldOwner.getUuid()); else SubserverSystem.sendToBauServer(p, worldOwner.getUuid()); @@ -183,31 +175,43 @@ public class BauCommand { } } - private static void togglewe(ProxiedPlayer p, String[] command){ - BauweltMember target = toggle(p, command, "togglewe"); + private static void togglewe(ProxiedPlayer p, String[] args){ + BauweltMember target = toggle(p, args, "togglewe"); if(target == null) return; target.setWorldEdit(!target.isWorldEdit()); + clearMembercache(p); isAllowedTo(target.isWorldEdit(), p, target, "WorldEdit verwenden"); } - private static void toggleworld(ProxiedPlayer p, String[] command){ - BauweltMember target = toggle(p, command, "toggleworld"); + private static void toggleworld(ProxiedPlayer p, String[] args){ + BauweltMember target = toggle(p, args, "toggleworld"); if(target == null) return; target.setWorld(!target.isWorld()); + clearMembercache(p); isAllowedTo(target.isWorld(), p, target, "Einstellungen vornehmen"); } - private static void delmember(ProxiedPlayer p, String[] command){ - if (command.length == 2) { + private static void clearMembercache(ProxiedPlayer p){ + for(ServerInfo info : ProxyServer.getInstance().getServers().values()){ + Subserver server = Subserver.getSubserver(info); + if(server != null && server.getType() == Servertype.BAUSERVER && ((Bauserver)server).getOwner().equals(p.getUniqueId())){ + info.getPlayers().stream().findAny().ifPresent(player -> new BaumemberUpdatePacket().send(player)); + break; + } + } + } + + private static void delmember(ProxiedPlayer p, String[] args){ + if (args.length == 1) { Message.send("BAU_DELMEMBER_USAGE", p); return; } - BauweltMember target = member(p, SteamwarUser.get(command[2])); + BauweltMember target = member(p, SteamwarUser.get(args[1])); if(target == null) return; @@ -228,13 +232,13 @@ public class BauCommand { Message.send("BAU_DELMEMBER_DELETED", p); } - private static void delete(ProxiedPlayer p, String[] command){ + private static void delete(ProxiedPlayer p, String[] args){ SWInventory inventory = new SWInventory(p, 9, Message.parse("BAU_DELETE_GUI_NAME", p)); inventory.addItem(8, new SWItem(Message.parse("BAU_DELETE_GUI_CANCEL", p), 1), click -> inventory.close() ); inventory.addItem(0, new SWItem(Message.parse("BAU_DELETE_GUI_DELETE", p), 10), click -> { - if(bau15(p, command, 2)){ + if(bau15(p, args, 1)){ SteamwarUser user = SteamwarUser.get(p.getUniqueId()); deleteWorld(p, BungeeCore.USERWORLDS15 + user.getId()); }else{ @@ -275,8 +279,8 @@ public class BauCommand { } } - private static void testarena(ProxiedPlayer p, String[] command){ - FightCommand.createArena(p, "/bau testarena ", command, 2, false, (player, mode, map) -> ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { + private static void testarena(ProxiedPlayer p, String[] args){ + FightCommand.createArena(p, "/bau testarena ", args, 1, false, (player, mode, map) -> ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { stopBauserver(p); SubserverSystem.startTestServer(p, mode, map, 0, 0); })); @@ -296,13 +300,13 @@ public class BauCommand { return target; } - private static BauweltMember toggle(ProxiedPlayer p, String[] command, String subcommand){ - if (command.length == 2) { + private static BauweltMember toggle(ProxiedPlayer p, String[] args, String subcommand){ + if (args.length == 1) { Message.send("BAU_MEMBER_TOGGLE_USAGE", p, subcommand); return null; } - SteamwarUser member = SteamwarUser.get(command[2]); + SteamwarUser member = SteamwarUser.get(args[1]); return member(p, member); } diff --git a/src/de/steamwar/bungeecore/comms/PacketIdManager.java b/src/de/steamwar/bungeecore/comms/PacketIdManager.java index 8376d591..1d48745d 100644 --- a/src/de/steamwar/bungeecore/comms/PacketIdManager.java +++ b/src/de/steamwar/bungeecore/comms/PacketIdManager.java @@ -25,6 +25,7 @@ public class PacketIdManager { public static final byte PING_PACKET = 0x01; public static final byte TABLIST_NAME = 0x02; public static final byte PREPARE_SCHEM = 0x03; + public static final byte BAUMEMBER_UPDATE = 0x04; //0x1(X) Bungee Inventory public static final byte INVENTORY_PACKET = 0x10; diff --git a/src/de/steamwar/bungeecore/comms/packets/BaumemberUpdatePacket.java b/src/de/steamwar/bungeecore/comms/packets/BaumemberUpdatePacket.java new file mode 100644 index 00000000..ddb4021e --- /dev/null +++ b/src/de/steamwar/bungeecore/comms/packets/BaumemberUpdatePacket.java @@ -0,0 +1,36 @@ +/* + This file is a part of the SteamWar software. + + Copyright (C) 2020 SteamWar.de-Serverteam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package de.steamwar.bungeecore.comms.packets; + +import com.google.common.io.ByteArrayDataOutput; +import de.steamwar.bungeecore.comms.BungeePacket; +import de.steamwar.bungeecore.comms.PacketIdManager; + +public class BaumemberUpdatePacket extends BungeePacket { + @Override + public int getId() { + return PacketIdManager.BAUMEMBER_UPDATE; + } + + @Override + public void writeVars(ByteArrayDataOutput byteArrayDataOutput) { + // empty + } +} diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index b41ea78f..774747be 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -23,7 +23,6 @@ import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Subserver; -import de.steamwar.bungeecore.commands.BauCommand; import de.steamwar.bungeecore.commands.TpCommand; import de.steamwar.bungeecore.comms.packets.PingPacket; import de.steamwar.bungeecore.sql.SteamwarUser; @@ -77,11 +76,6 @@ public class ChatListener extends BasicListener { } switch(command[0].toLowerCase()){ - case "/bau": - case "/b": - case "/gs": - BauCommand.onBau(e, command); - break; case "/bc": case "/bauchat": case "/local": From bab56f895ad1a1d70db758e97ba35562ea5a9a30 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sat, 21 Aug 2021 17:43:12 +0200 Subject: [PATCH 02/41] Add better AlertCommand --- .../bungeecore/commands/AlertCommand.java | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/AlertCommand.java b/src/de/steamwar/bungeecore/commands/AlertCommand.java index 02623cb8..db7c3b01 100644 --- a/src/de/steamwar/bungeecore/commands/AlertCommand.java +++ b/src/de/steamwar/bungeecore/commands/AlertCommand.java @@ -37,8 +37,33 @@ public class AlertCommand extends BasicCommand { return; } - String s = String.join(" ", args); + String s; + boolean discordAnnounce = false; + if (args[0].equals("-discord")) { + if (args.length == 1) { + Message.send("USAGE_ALERT", sender); + return; + } + discordAnnounce = true; + s = join(1, args); + } else { + s = join(0, args); + } + Message.broadcast("ALERT", ChatColor.translateAlternateColorCodes('&', s)); - SteamwarDiscordBot.instance().getAnnouncementListener().announce(s); + if (discordAnnounce) { + SteamwarDiscordBot.instance().getAnnouncementListener().announce(s); + } + } + + private String join(int startIndex, String... strings) { + StringBuilder st = new StringBuilder(); + for (int i = startIndex; i < strings.length; i++) { + if (i != startIndex) { + st.append(" "); + } + st.append(strings[i]); + } + return st.toString(); } } From d623f474107339b45ccd36479811e0282688491e Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sun, 22 Aug 2021 22:05:57 +0200 Subject: [PATCH 03/41] Fixup async Chat problems --- src/de/steamwar/bungeecore/bot/events/SchematicsManager.java | 2 +- .../steamwar/bungeecore/bot/listeners/IngameChatListener.java | 2 +- .../bungeecore/bot/listeners/ServerTeamChatListener.java | 2 +- src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java index 4052d84f..64809e18 100644 --- a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java +++ b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java @@ -67,7 +67,7 @@ public class SchematicsManager { if (message == null) { message = textChannel.sendMessage(messageBuilder.build()).complete(); } else { - message.editMessage(messageBuilder.build()).complete(); + message.editMessage(messageBuilder.build()).queue(); } } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java index 626a26e2..ce635f30 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java @@ -63,6 +63,6 @@ public class IngameChatListener extends BasicDiscordListener { assert textChannel != null; MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.append(message.replace("&", "").replace("@everyone", "`@everyone`").replace("@here", "`@here`").replaceAll("<[@#]!?\\d+>", "`$0`")); - textChannel.sendMessage(messageBuilder.build()).complete(); + textChannel.sendMessage(messageBuilder.build()).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java b/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java index 432c2872..0f826735 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java @@ -54,6 +54,6 @@ public class ServerTeamChatListener extends BasicDiscordListener { assert textChannel != null; MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.append(message.replace("&", "")); - textChannel.sendMessage(messageBuilder.build()).complete(); + textChannel.sendMessage(messageBuilder.build()).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java b/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java index a01121bd..b4b4261e 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java @@ -49,7 +49,7 @@ public class DiscordSchemAlert { MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.setEmbeds(builder.build()); try { - dcUser.openPrivateChannel().complete().sendMessage(messageBuilder.build()).complete(); + dcUser.openPrivateChannel().complete().sendMessage(messageBuilder.build()).queue(); } catch (Exception e) { // Ignored } @@ -70,7 +70,7 @@ public class DiscordSchemAlert { messageBuilder.setEmbeds(builder.build()); messageBuilder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")))); try { - dcUser.openPrivateChannel().complete().sendMessage(messageBuilder.build()).complete(); + dcUser.openPrivateChannel().complete().sendMessage(messageBuilder.build()).queue(); } catch (Exception e) { // Ignored } From 013330f18ddd2a6d7d7da01b6b80609258b2b2be Mon Sep 17 00:00:00 2001 From: yoyosource Date: Tue, 24 Aug 2021 14:23:51 +0200 Subject: [PATCH 04/41] Hotfix DevCommand --- src/de/steamwar/bungeecore/commands/DevCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/commands/DevCommand.java b/src/de/steamwar/bungeecore/commands/DevCommand.java index 7e5ed2d4..dcc4b7fd 100644 --- a/src/de/steamwar/bungeecore/commands/DevCommand.java +++ b/src/de/steamwar/bungeecore/commands/DevCommand.java @@ -53,7 +53,7 @@ public class DevCommand extends BasicCommand { sendToServer((ProxiedPlayer) sender, server[0], Integer.parseInt(server[1])); } else { if (args.length == 0) { - send(devServer, (ProxiedPlayer) sender, s -> s.equalsIgnoreCase(((ProxiedPlayer) sender).getDisplayName()), () -> Message.send("DEV_UNKNOWN_SERVER", sender)); + send(devServer, (ProxiedPlayer) sender, s -> s.equalsIgnoreCase(sender.getName()), () -> Message.send("DEV_UNKNOWN_SERVER", sender)); } else { send(devServer, (ProxiedPlayer) sender, args[0]::equalsIgnoreCase, () -> Message.send("DEV_NO_SERVER", sender)); } From 5186526d0a15d0d987e79ce16ffad92b4d948045 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 3 Sep 2021 12:20:24 +0200 Subject: [PATCH 05/41] Remove JDBC RAM leak Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 11 +- .../commands/PollresultCommand.java | 2 +- .../bungeecore/commands/TeamCommand.java | 2 +- .../bungeecore/sql/BannedUserIPs.java | 46 +++--- .../bungeecore/sql/BauweltMember.java | 46 +++--- .../bungeecore/sql/CheckedSchematic.java | 17 +-- src/de/steamwar/bungeecore/sql/Elo.java | 33 ++--- src/de/steamwar/bungeecore/sql/Event.java | 55 +++---- .../steamwar/bungeecore/sql/EventFight.java | 32 ++-- .../steamwar/bungeecore/sql/IgnoreSystem.java | 20 +-- src/de/steamwar/bungeecore/sql/Mod.java | 23 ++- .../steamwar/bungeecore/sql/PollAnswer.java | 43 ++---- .../steamwar/bungeecore/sql/Punishment.java | 49 +++---- src/de/steamwar/bungeecore/sql/SQL.java | 95 ------------ .../steamwar/bungeecore/sql/SWException.java | 4 +- src/de/steamwar/bungeecore/sql/Schematic.java | 80 +++++----- .../bungeecore/sql/SchematicMember.java | 85 ++--------- src/de/steamwar/bungeecore/sql/Session.java | 5 +- src/de/steamwar/bungeecore/sql/Statement.java | 137 ++++++++++++++++++ .../steamwar/bungeecore/sql/SteamwarUser.java | 132 +++++++++-------- src/de/steamwar/bungeecore/sql/Team.java | 88 +++++------ .../bungeecore/sql/TeamTeilnahme.java | 43 +++--- 22 files changed, 466 insertions(+), 582 deletions(-) delete mode 100644 src/de/steamwar/bungeecore/sql/SQL.java create mode 100644 src/de/steamwar/bungeecore/sql/Statement.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index f2bd01f1..9d5ffd94 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -24,11 +24,11 @@ import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.commands.*; import de.steamwar.bungeecore.comms.SpigotReceiver; import de.steamwar.bungeecore.listeners.*; -import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.listeners.mods.Forge; import de.steamwar.bungeecore.listeners.mods.LabyMod; +import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.listeners.mods.WorldDownloader; -import de.steamwar.bungeecore.sql.SQL; +import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; import net.dv8tion.jda.api.JDA; @@ -145,19 +145,20 @@ public class BungeeCore extends Plugin { new EventStarter(); new SessionManager(); new SpigotReceiver(); - new SteamwarDiscordBot(); new TablistManager(); getProxy().getScheduler().schedule(this, () -> { SteamwarUser.clearCache(); Team.clearCache(); }, 1, 1, TimeUnit.HOURS); + + new SteamwarDiscordBot(); } @Override public void onDisable(){ ErrorLogger.stop(); - SQL.close(); + Statement.close(); try { SteamwarDiscordBot.instance().getJda().shutdownNow(); SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); @@ -258,7 +259,7 @@ public class BungeeCore extends Plugin { Persistent.setChatPrefix(CHAT_PREFIX); Persistent.setLobbyServer(LOBBY_SERVER); - SQL.connect( + Statement.connect( config.getString("db.url"), config.getString("db.username"), config.getString("db.password") diff --git a/src/de/steamwar/bungeecore/commands/PollresultCommand.java b/src/de/steamwar/bungeecore/commands/PollresultCommand.java index 1d39e9ea..cfebd66a 100644 --- a/src/de/steamwar/bungeecore/commands/PollresultCommand.java +++ b/src/de/steamwar/bungeecore/commands/PollresultCommand.java @@ -46,7 +46,7 @@ public class PollresultCommand extends BasicCommand { ProxiedPlayer player = (ProxiedPlayer) sender; Map voted = PollAnswer.getCurrentResults(); - Message.send("POLLRESULT_HEADER", player, PollAnswer.getAllAnswered(), PollSystem.getQuestion()); + Message.send("POLLRESULT_HEADER", player, voted.values().stream().reduce(Integer::sum), PollSystem.getQuestion()); for (Map.Entry e: voted.entrySet()) { Message.send("POLLRESULT_LIST", sender, e.getKey(), e.getValue()); } diff --git a/src/de/steamwar/bungeecore/commands/TeamCommand.java b/src/de/steamwar/bungeecore/commands/TeamCommand.java index af3a84ba..3889da28 100644 --- a/src/de/steamwar/bungeecore/commands/TeamCommand.java +++ b/src/de/steamwar/bungeecore/commands/TeamCommand.java @@ -177,7 +177,7 @@ public class TeamCommand extends BasicCommand { if(checkTeamName(player, team, args[2])) return; - Team.create(args[1], args[2], user); + Team.create(args[1], args[2]); user.setTeam(Team.get(args[1]).getTeamId()); user.setLeader(true); Message.send("TEAM_CREATE_CREATED", player, args[2]); diff --git a/src/de/steamwar/bungeecore/sql/BannedUserIPs.java b/src/de/steamwar/bungeecore/sql/BannedUserIPs.java index 6b371ccc..4a754845 100644 --- a/src/de/steamwar/bungeecore/sql/BannedUserIPs.java +++ b/src/de/steamwar/bungeecore/sql/BannedUserIPs.java @@ -19,18 +19,18 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class BannedUserIPs { - private int userID; - private Timestamp timestamp; + private static final Statement getByID = new Statement("SELECT * FROM BannedUserIPs WHERE UserID = ? ORDER BY Timestamp ASC"); + private static final Statement getByIP = new Statement("SELECT * FROM BannedUserIPs WHERE IP = ? ORDER BY Timestamp DESC"); + private static final Statement banIP = new Statement("INSERT INTO BannedUserIPs (UserID, Timestamp, IP) VALUES (?, NOW(), ?) ON DUPLICATE KEY UPDATE Timestamp=NOW()"); + + private final int userID; + private final Timestamp timestamp; private BannedUserIPs(int userID, Timestamp timestamp){ this.userID = userID; @@ -38,37 +38,31 @@ public class BannedUserIPs { } public static List get(int userID){ - List userIPs = new ArrayList<>(); - ResultSet dbentry = SQL.select("SELECT * FROM BannedUserIPs WHERE UserID = ? ORDER BY Timestamp ASC", userID); - try { - while(dbentry.next()){ + return getByID.select(rs -> { + List userIPs = new ArrayList<>(); + while(rs.next()) { userIPs.add(new BannedUserIPs( userID, - dbentry.getTimestamp("Timestamp"))); + rs.getTimestamp("Timestamp"))); } - } catch (SQLException e) { - BungeeCore.log("Get BannedUserIPs failed", e); - } - return userIPs; + return userIPs; + }, userID); } public static List get(String ip){ - List userIDs = new ArrayList<>(); - ResultSet dbentry = SQL.select("SELECT * FROM BannedUserIPs WHERE IP = ? ORDER BY Timestamp DESC", ip); - try { - while(dbentry.next()){ + return getByIP.select(rs -> { + List userIDs = new ArrayList<>(); + while(rs.next()) { userIDs.add(new BannedUserIPs( - dbentry.getInt("UserID"), - dbentry.getTimestamp("Timestamp"))); + rs.getInt("UserID"), + rs.getTimestamp("Timestamp"))); } - } catch (SQLException e) { - BungeeCore.log("Get BannedUserIPs failed", e); - } - return userIDs; + return userIDs; + }, ip); } static void banIP(SteamwarUser user, String ip){ - SQL.update("INSERT INTO BannedUserIPs (UserID, Timestamp, IP) VALUES (?, NOW(), ?) ON DUPLICATE KEY UPDATE Timestamp=NOW()", user.getId(), ip); + banIP.update(user.getId(), ip); } public int getUserID() { diff --git a/src/de/steamwar/bungeecore/sql/BauweltMember.java b/src/de/steamwar/bungeecore/sql/BauweltMember.java index f05cab23..f89650e2 100644 --- a/src/de/steamwar/bungeecore/sql/BauweltMember.java +++ b/src/de/steamwar/bungeecore/sql/BauweltMember.java @@ -19,15 +19,17 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class BauweltMember{ + + private static final Statement delete = new Statement("DELETE FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + private static final Statement update = new Statement("INSERT INTO BauweltMember (BauweltID, MemberID, WorldEdit, World) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE WorldEdit = VALUES(WorldEdit), World = VALUES(World)"); + private static final Statement getMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + private static final Statement getMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); + private final int bauweltID; private final int memberID; private boolean worldEdit; @@ -52,12 +54,11 @@ public class BauweltMember{ } public void remove(){ - SQL.update("DELETE FROM BauweltMember WHERE BauweltID = " + bauweltID + " AND MemberID = " + memberID); + delete.update(bauweltID, memberID); } private void updateDB(){ - SQL.update("INSERT INTO BauweltMember (BauweltID, MemberID, WorldEdit, World) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE WorldEdit = VALUES(WorldEdit), World = VALUES(World)", - bauweltID, memberID, worldEdit, world); + update.update(bauweltID, memberID, worldEdit, world); } public static BauweltMember getBauMember(UUID ownerID, UUID memberID){ @@ -65,18 +66,12 @@ public class BauweltMember{ } public static BauweltMember getBauMember(int ownerID, int memberID){ - ResultSet member = SQL.select("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?", ownerID, memberID); - try { - if(member == null || !member.next()){ + return getMember.select(rs -> { + if(!rs.next()) return null; - } - boolean worldEdit = member.getBoolean("WorldEdit"); - boolean world = member.getBoolean("World"); - return new BauweltMember(ownerID, memberID, worldEdit, world, false); - } catch (SQLException e) { - BungeeCore.log("Could not load BauweltMember", e); - } - return null; + + return new BauweltMember(ownerID, memberID, rs.getBoolean("WorldEdit"), rs.getBoolean("World"), false); + }, ownerID, memberID); } public static List getMembers(UUID bauweltID){ @@ -84,20 +79,13 @@ public class BauweltMember{ } public static List getMembers(int bauweltID){ - try{ - ResultSet memberlist = SQL.select("SELECT * FROM BauweltMember WHERE BauweltID = ?", bauweltID); + return getMembers.select(rs -> { List members = new ArrayList<>(); - while(memberlist.next()){ - int memberID = memberlist.getInt("MemberID"); - boolean worldEdit = memberlist.getBoolean("WorldEdit"); - boolean world = memberlist.getBoolean("World"); - members.add(new BauweltMember(bauweltID, memberID, worldEdit, world, false)); + while(rs.next()){ + members.add(new BauweltMember(bauweltID, rs.getInt("MemberID"), rs.getBoolean("WorldEdit"), rs.getBoolean("World"), false)); } return members; - }catch(SQLException e){ - BungeeCore.log("Could not load BauweltMembers", e); - } - return new ArrayList<>(); + }, bauweltID); } public int getBauweltID() { diff --git a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java index 0424e4aa..436d5ab3 100644 --- a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java +++ b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java @@ -27,6 +27,9 @@ import java.util.List; public class CheckedSchematic { + private static final Statement create = new Statement("INSERT INTO CheckedSchematic (SchemName, SchemOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?)"); + private static final Statement previous = new Statement("SELECT * FROM CheckedSchematic WHERE SchemName = ? AND SchemOwner = ? ORDER BY EndTime ASC"); + private final String schemName; private final int schemOwner; @@ -45,20 +48,16 @@ public class CheckedSchematic { } public static void create(String schemName, int schemOwner, int validator, Timestamp startTime, Timestamp endTime, String reason){ - SQL.update("INSERT INTO CheckedSchematic (SchemName, SchemOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?)", - schemName, schemOwner, validator, startTime, endTime, reason); + create.update(schemName, schemOwner, validator, startTime, endTime, reason); } public static List previousChecks(String schemName, int schemOwner){ - ResultSet rs = SQL.select("SELECT * FROM CheckedSchematic WHERE SchemName = ? AND SchemOwner = ? ORDER BY EndTime ASC", schemName, schemOwner); - List schematics = new ArrayList<>(); - try { + return previous.select(rs -> { + List schematics = new ArrayList<>(); while(rs.next()) schematics.add(new CheckedSchematic(rs)); - } catch (SQLException e) { - throw new SecurityException("Could not load previous checks", e); - } - return schematics; + return schematics; + }, schemName, schemOwner); } public int getValidator() { diff --git a/src/de/steamwar/bungeecore/sql/Elo.java b/src/de/steamwar/bungeecore/sql/Elo.java index 07a95c2e..b61c8a3b 100644 --- a/src/de/steamwar/bungeecore/sql/Elo.java +++ b/src/de/steamwar/bungeecore/sql/Elo.java @@ -19,33 +19,26 @@ package de.steamwar.bungeecore.sql; -import java.sql.ResultSet; -import java.sql.SQLException; - public class Elo { + + private static final Statement elo = new Statement("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?"); + private static final Statement place = new Statement("SELECT COUNT(*) AS Place FROM Elo WHERE GameMode = ? AND Elo > ?"); + private Elo(){} public static int getElo(int userID, String gameMode){ - ResultSet rs = SQL.select("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?", userID, gameMode); - int elo = 1000; - try { + return elo.select(rs -> { if(rs.next()) - elo = rs.getInt("Elo"); - } catch (SQLException e) { - throw new SecurityException("Could not get Elo", e); - } - return elo; + return rs.getInt("Elo"); + return 1000; + }, userID, gameMode); } public static int getPlacement(int elo, String gameMode){ - ResultSet rs = SQL.select("SELECT COUNT(*) AS Place FROM Elo WHERE GameMode = ? AND Elo > ?", gameMode, elo); - try{ - if(!rs.next()) - return -1; - - return rs.getInt("Place"); - }catch(SQLException e){ - throw new SecurityException("Could not get place", e); - } + return place.select(rs -> { + if(rs.next()) + return rs.getInt("Place"); + return -1; + }, gameMode, elo); } } diff --git a/src/de/steamwar/bungeecore/sql/Event.java b/src/de/steamwar/bungeecore/sql/Event.java index 72db0659..93fd211b 100644 --- a/src/de/steamwar/bungeecore/sql/Event.java +++ b/src/de/steamwar/bungeecore/sql/Event.java @@ -19,17 +19,20 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; public class Event { + private static final Statement byCurrent = new Statement("SELECT * FROM Event WHERE Start < now() AND End > now()"); + private static final Statement byId = new Statement("SELECT * FROM Event WHERE EventID = ?"); + private static final Statement byName = new Statement("SELECT * FROM Event WHERE lower(EventName) = ?"); + private static final Statement byComing = new Statement("SELECT * FROM Event WHERE Start > now()"); + private final int eventID; private final String eventName; private final Timestamp start; @@ -56,57 +59,39 @@ public class Event { if(current != null && current.now()) return current; - ResultSet rs = SQL.select("SELECT * FROM Event WHERE Start < now() AND End > now()"); - try{ - if(!rs.next()){ + return byCurrent.select(rs -> { + if(rs.next()) + current = new Event(rs); + else current = null; - return null; - } - - current = new Event(rs); return current; - }catch (SQLException e){ - BungeeCore.log("Failed to load current Event", e); - throw new SecurityException(); - } + }); } public static Event get(int eventID){ - ResultSet rs = SQL.select("SELECT * FROM Event WHERE EventID = " + eventID); - try{ + return byId.select(rs -> { if(!rs.next()) - throw new IllegalArgumentException(); - + throw new SQLException("Couldn't find event " + eventID); return new Event(rs); - }catch (SQLException e){ - BungeeCore.log("Failed to load Event", e); - throw new SecurityException(); - } + }, eventID); } public static Event get(String eventName){ - ResultSet rs = SQL.select("SELECT * FROM Event WHERE lower(EventName) = ?", eventName.toLowerCase()); - try{ + return byName.select(rs -> { if(!rs.next()) return null; return new Event(rs); - }catch (SQLException e){ - BungeeCore.log("Failed to load Event by name", e); - throw new SecurityException(); - } + }, eventName.toLowerCase()); } public static List getComing(){ - List events = new LinkedList<>(); - ResultSet rs = SQL.select("SELECT * FROM Event WHERE Start > now()"); - try{ + return byComing.select(rs -> { + List events = new ArrayList<>(); while(rs.next()) events.add(new Event(rs)); - }catch (SQLException e){ - BungeeCore.log("Failed to load Events", e); - } - return events; + return events; + }); } private boolean now(){ diff --git a/src/de/steamwar/bungeecore/sql/EventFight.java b/src/de/steamwar/bungeecore/sql/EventFight.java index c86b145d..ffcbe6f8 100644 --- a/src/de/steamwar/bungeecore/sql/EventFight.java +++ b/src/de/steamwar/bungeecore/sql/EventFight.java @@ -20,7 +20,6 @@ package de.steamwar.bungeecore.sql; import de.steamwar.bungeecore.ArenaMode; -import de.steamwar.bungeecore.BungeeCore; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,7 +30,11 @@ import static java.time.temporal.ChronoUnit.SECONDS; public class EventFight implements Comparable { - private static Queue fights = new PriorityQueue<>(); + private static final Statement reschedule = new Statement("UPDATE EventFight SET StartTime = ? WHERE EventID = ? AND FightID = ?"); + private static final Statement allComing = new Statement("SELECT * FROM EventFight WHERE StartTime > now() ORDER BY `StartTime` ASC"); + private static final Statement event = new Statement("SELECT * FROM EventFight WHERE EventID = ? ORDER BY `StartTime` ASC"); + + private static final Queue fights = new PriorityQueue<>(); private final int eventID; private final int fightID; @@ -57,31 +60,26 @@ public class EventFight implements Comparable { public void reschedule(){ startTime = Timestamp.from(new Date().toInstant().plus(30, SECONDS)); - SQL.update("UPDATE EventFight SET StartTime = ? WHERE EventID = ? AND FightID = ?", startTime, eventID, fightID); + reschedule.update(startTime, eventID, fightID); } public static void loadAllComingFights(){ - ResultSet rs = SQL.select("SELECT * FROM EventFight WHERE StartTime > now() ORDER BY `StartTime` ASC"); - fights.clear(); - try{ + allComing.select(rs -> { + fights.clear(); while(rs.next()){ - fights.add(new EventFight(rs)); + fights.add(new EventFight(rs)); } - }catch (SQLException e){ - BungeeCore.log("Failed to load EventFights", e); - } + return null; + }); } public static List getEvent(int eventID){ - ResultSet rs = SQL.select("SELECT * FROM EventFight WHERE EventID = ? ORDER BY `StartTime` ASC", eventID); - List fights = new LinkedList<>(); - try{ + return event.select(rs -> { + List fights = new LinkedList<>(); while(rs.next()) fights.add(new EventFight(rs)); - }catch (SQLException e){ - BungeeCore.log("Failed to load EventFights", e); - } - return fights; + return fights; + }, eventID); } public static Queue getFights() { diff --git a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java index 73c15009..185fb089 100644 --- a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java +++ b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java @@ -22,9 +22,13 @@ package de.steamwar.bungeecore.sql; import net.md_5.bungee.api.connection.ProxiedPlayer; import java.sql.ResultSet; -import java.sql.SQLException; public class IgnoreSystem{ + + private static final Statement select = new Statement("SELECT COUNT(*) AS blocked FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); + private static final Statement insert = new Statement("INSERT INTO IgnoredPlayers (Ignorer, Ignored) VALUES (?, ?)"); + private static final Statement delete = new Statement("DELETE FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); + private IgnoreSystem(){} public static boolean isIgnored(ProxiedPlayer ignorer, ProxiedPlayer ignored){ @@ -34,22 +38,14 @@ public class IgnoreSystem{ } public static boolean isIgnored(SteamwarUser ignorer, SteamwarUser ignored) { - try { - ResultSet rs = SQL.select("SELECT COUNT(*) AS blocked FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?", ignorer.getId(), ignored.getId()); - if(!rs.next()) - return false; - - return rs.getInt("blocked") > 0; - } catch (SQLException e) { - throw new SecurityException("Could not check if ignored", e); - } + return select.select(ResultSet::next, ignorer.getId(), ignored.getId()); } public static void ignore(SteamwarUser ignorer, SteamwarUser ignored) { - SQL.update("INSERT INTO IgnoredPlayers (Ignorer, Ignored) VALUES (?, ?)", ignorer.getId(), ignored.getId()); + insert.update(ignorer.getId(), ignored.getId()); } public static void unIgnore(SteamwarUser ignorer, SteamwarUser ignored) { - SQL.update("DELETE FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?", ignorer.getId(), ignored.getId()); + delete.update(ignorer.getId(), ignored.getId()); } } diff --git a/src/de/steamwar/bungeecore/sql/Mod.java b/src/de/steamwar/bungeecore/sql/Mod.java index 98034bb5..9aad08b0 100644 --- a/src/de/steamwar/bungeecore/sql/Mod.java +++ b/src/de/steamwar/bungeecore/sql/Mod.java @@ -19,12 +19,11 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; - public class Mod { + + private static final Statement get = new Statement("SELECT * FROM Mods WHERE ModName = ? AND Platform = ?"); + private static final Statement insert = new Statement("INSERT INTO Mods (ModName, Platform) VALUES (?, ?)"); + private final String modName; private final Platform platform; private final ModType modType; @@ -36,15 +35,15 @@ public class Mod { } public static Mod get(String modName, Platform platform){ - ResultSet rs = SQL.select("SELECT * FROM Mods WHERE ModName = ? AND Platform = ?", modName, platform.value); - try{ + Mod mod = get.select(rs -> { if(rs.next()) return new Mod(modName, platform, ModType.valueOf(rs.getInt("ModType"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load Mod", e); - throw new SecurityException(); - } - SQL.update("INSERT INTO Mods (ModName, Platform) VALUES (?, ?)", modName, platform.value); + return null; + }, modName, platform.value); + if(mod != null) + return mod; + + insert.update(modName, platform.value); return new Mod(modName, platform, ModType.UNKLASSIFIED); } diff --git a/src/de/steamwar/bungeecore/sql/PollAnswer.java b/src/de/steamwar/bungeecore/sql/PollAnswer.java index 62fcee04..7d23c384 100644 --- a/src/de/steamwar/bungeecore/sql/PollAnswer.java +++ b/src/de/steamwar/bungeecore/sql/PollAnswer.java @@ -19,7 +19,6 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.listeners.PollSystem; import java.sql.ResultSet; @@ -29,6 +28,10 @@ import java.util.Map; public class PollAnswer { + private static final Statement get = new Statement("SELECT * FROM PollAnswer WHERE UserID = ? AND Question = ?"); + private static final Statement getResults = new Statement("SELECT Count(UserID) AS Times, Answer FROM PollAnswer WHERE Question = ? GROUP BY Answer ORDER BY `Times` ASC"); + private static final Statement insert = new Statement("INSERT INTO PollAnswer (UserID, Question, Answer) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Answer = VALUES(Answer)"); + private final int userID; private final String question; private int answer; @@ -44,38 +47,20 @@ public class PollAnswer { } public static PollAnswer get(int userID){ - ResultSet rs = SQL.select("SELECT * FROM PollAnswer WHERE UserID = ? AND Question = ?", userID, PollSystem.getQuestion()); - try { - if(!rs.next()) - return new PollAnswer(userID, PollSystem.getQuestion()); - return new PollAnswer(rs); - } catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } + return get.select(rs -> { + if(rs.next()) + return new PollAnswer(rs); + return new PollAnswer(userID, PollSystem.getQuestion()); + }, userID, PollSystem.getQuestion()); } public static Map getCurrentResults() { - ResultSet set = SQL.select("SELECT Count(UserID) AS Times, Answer FROM PollAnswer WHERE Question = ? GROUP BY Answer ORDER BY `Times` ASC", PollSystem.getQuestion()); - try { + return getResults.select(rs -> { Map retMap = new HashMap<>(); - while (set.next()) { - retMap.put(PollSystem.getAnswer(set.getInt("Answer")), set.getInt("Times")); - } + while (rs.next()) + retMap.put(PollSystem.getAnswer(rs.getInt("Answer")), rs.getInt("Times")); return retMap; - }catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } - } - - public static Integer getAllAnswered() { - ResultSet set = SQL.select("SELECT Count(UserID) AS Times FROM PollAnswer WHERE Question = ?", PollSystem.getQuestion()); - try { - if(!set.next()) - throw new SecurityException("Could not get PollAnswers"); - return set.getInt("Times"); - }catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } + }, PollSystem.getQuestion()); } public boolean hasAnswered(){ @@ -84,6 +69,6 @@ public class PollAnswer { public void setAnswer(int answer){ this.answer = answer; - SQL.update("INSERT INTO PollAnswer (UserID, Question, Answer) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Answer = VALUES(Answer)", userID, question, answer); + insert.update(userID, question, answer); } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index e4d90348..914e6b85 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -31,45 +31,40 @@ import java.util.*; public class Punishment { + private static final Statement getPunishment = new Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); + private static final Statement getPunishments = new Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); + private static final Statement getAllPunishments = new Statement("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC"); + private static final Statement insert = new Statement("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)"); + private static final Statement update = new Statement("UPDATE Punishments SET EndTime = ?, Reason = ?, Perma = ? WHERE PunishmentId = ?"); + public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1", user, type.name()); - try { - if(!set.next()) - return null; - return new Punishment(set); - } catch (SQLException e) { - throw new SecurityException("Could not Load Punishments", e); - } + return getPunishment.select(rs -> { + if(rs.next()) + return new Punishment(rs); + return null; + }, user, type.name()); } public static Map getPunishmentsOfPlayer(int user) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)", user); - try { + return getPunishments.select(rs -> { Map punishments = new HashMap<>(); - while (set.next()) - punishments.put(PunishmentType.valueOf(set.getString("Type")), new Punishment(set)); + while (rs.next()) + punishments.put(PunishmentType.valueOf(rs.getString("Type")), new Punishment(rs)); return punishments; - } catch (SQLException e) { - throw new SecurityException("Could not Load Punishments", e); - } + }, user); } public static List getAllPunishmentsOfPlayer(int user) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC", user); - try { + return getAllPunishments.select(rs -> { List punishments = new ArrayList<>(); - while (set.next()) { - punishments.add(new Punishment(set)); - } + while (rs.next()) + punishments.add(new Punishment(rs)); return punishments; - } catch (SQLException e) { - throw new SecurityException("Could not Load all Punishments", e); - } + }, user); } public static Punishment createPunishment(int user, int executor, PunishmentType type, String reason, Timestamp endTime, boolean perma) { - SQL.update("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)", - user, executor, type.name(), reason, endTime, perma); + insert.update(user, executor, type.name(), reason, endTime, perma); return getPunishmentOfPlayer(user, type); } @@ -122,7 +117,7 @@ public class Punishment { } public void updateEndTime(int from, String newreason, Timestamp newUpdate, boolean perma) { - if(newreason.equals(reason) && newUpdate.equals(endTime) && perma == perma) + if(newreason.equals(reason) && newUpdate.equals(endTime) && this.perma == perma) return; ProxiedPlayer player = BungeeCore.get().getProxy().getPlayer(SteamwarUser.get(from).getUuid()); String newReason = Message.parse("BAN_CHANGED", player, reason, @@ -131,7 +126,7 @@ public class Punishment { getBantime(newUpdate, perma), newreason); - SQL.update("UPDATE Punishments SET EndTime = ?, Reason = ?, Perma = ? WHERE PunishmentId = ?", newUpdate, newReason, perma, id); + update.update(newUpdate, newReason, perma, id); this.reason = newReason; this.perma = perma; this.endTime = newUpdate; diff --git a/src/de/steamwar/bungeecore/sql/SQL.java b/src/de/steamwar/bungeecore/sql/SQL.java deleted file mode 100644 index 947e2b60..00000000 --- a/src/de/steamwar/bungeecore/sql/SQL.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - This file is a part of the SteamWar software. - - Copyright (C) 2020 SteamWar.de-Serverteam - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package de.steamwar.bungeecore.sql; - -import de.steamwar.bungeecore.BungeeCore; -import net.md_5.bungee.api.ProxyServer; - -import java.sql.*; - - -public class SQL { - private SQL(){} - - private static Connection con; - private static String url; - private static String user; - private static String password; - - public static void connect(String url, String user, String password) { - SQL.url = url; - SQL.user = user; - SQL.password = password; - try { - con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); - }catch (SQLException e) { - ProxyServer.getInstance().stop(); - throw new SecurityException("Could not start SQL-Exception", e); - } - } - - public static void close() { - try { - if(con != null) - con.close(); - }catch (SQLException e) { - BungeeCore.log("Could not close SQL-Connection", e); - } - } - - static void update(String qry, Object... objects) { - try { - prepare(con, qry, objects).executeUpdate(); - } catch (SQLException e) { - sqlException(); - try (PreparedStatement st = con.prepareStatement(qry)) { - st.executeUpdate(); - } catch (SQLException ex) { - throw new SecurityException("Could not execute update statement", ex); - } - } - } - - static ResultSet select(String qry, Object... objects){ - try{ - return prepare(con, qry, objects).executeQuery(); - } catch (SQLException e) { - sqlException(); - try { - return prepare(con, qry, objects).executeQuery(); - } catch (SQLException ex) { - throw new SecurityException("Could not run Select-Statement", ex); - } - } - } - - private static PreparedStatement prepare(Connection connection, String qry, Object... objects) throws SQLException{ - PreparedStatement st = connection.prepareStatement(qry); - for(int i = 0; i < objects.length; i++){ - st.setObject(i+1, objects[i]); - } - return st; - } - - private static void sqlException(){ - close(); - connect(url, user, password); - } -} diff --git a/src/de/steamwar/bungeecore/sql/SWException.java b/src/de/steamwar/bungeecore/sql/SWException.java index 44a43cab..8a2c2e1f 100644 --- a/src/de/steamwar/bungeecore/sql/SWException.java +++ b/src/de/steamwar/bungeecore/sql/SWException.java @@ -22,7 +22,9 @@ package de.steamwar.bungeecore.sql; public class SWException { private SWException(){} + private static final Statement insert = new Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); + public static void log(String server, String message, String stacktrace){ - SQL.update("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)", server, message, stacktrace); + insert.update(server, message, stacktrace); } } diff --git a/src/de/steamwar/bungeecore/sql/Schematic.java b/src/de/steamwar/bungeecore/sql/Schematic.java index 9d25a384..b7155100 100644 --- a/src/de/steamwar/bungeecore/sql/Schematic.java +++ b/src/de/steamwar/bungeecore/sql/Schematic.java @@ -23,14 +23,22 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public class Schematic { + + private static final Statement schemByName = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemName = ? AND SchemOwner = ?"); + private static final Statement schemById = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemID = ?"); + private static final Statement schemsByType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?"); + private static final Statement schemsByUserType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ? AND SchemOwner = ?"); + private static final Statement schemsOfUser = new Statement("SELECT SchemID, SchemName, SchemOwner, Item, SchemType, Rank, SchemFormat, Item FROM Schematic WHERE SchemOwner = ? ORDER BY SchemName"); + private static final Statement updateType = new Statement("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?"); + private static final Statement updateRank = new Statement("UPDATE Schematic SET Rank = ? WHERE SchemID = ?"); + private final int schemID; private final String schemName; private final int schemOwner; private SchematicType schemType; - private String schemItem; + private final String schemItem; private Schematic(ResultSet rs) throws SQLException { this.schemID = rs.getInt("SchemID"); @@ -40,74 +48,52 @@ public class Schematic { this.schemItem = rs.getString("Item"); } - public static Schematic getSchemFromDB(String schemName, UUID schemOwner){ - return getSchemFromDB(schemName, SteamwarUser.get(schemOwner).getId()); - } - public static Schematic getSchemFromDB(String schemName, int schemOwner){ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemName = ? AND SchemOwner = ?", schemName, schemOwner); - try { - if(schematic == null || !schematic.next()){ - return null; - } - return new Schematic(schematic); - } catch (SQLException e) { - throw new SecurityException("Failed loading schematic", e); - } + return schemByName.select(rs -> { + if(!rs.next()) + return new Schematic(rs); + return null; + }, schemName, schemOwner); } public static Schematic getSchemFromDB(int schemID){ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemID = ?", schemID); - try { - if(!schematic.next()) + return schemById.select(rs -> { + if(!rs.next()) throw new SecurityException("Failed loading schematic " + schemID); - return new Schematic(schematic); - } catch (SQLException e) { - throw new SecurityException("Failed loading schematic", e); - } + return new Schematic(rs); + }, schemID); } public static List getAllSchemsOfType(SchematicType schemType){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?", schemType.toDB()); + return schemsByType.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } + while(rs.next()) + schematics.add(new Schematic(rs)); return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading all schems of type", e); - } + }, schemType.toDB()); } public static List getSchemsOfType(int userId, SchematicType schemType){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ? AND SchemOwner = ?", schemType.toDB(), userId); + return schemsByUserType.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } + while(rs.next()) + schematics.add(new Schematic(rs)); return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading schems of type", e); - } + }, schemType.toDB(), userId); } public static List getSchemsAccessibleByUser(int schemOwner){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, Item, SchemType, Rank, SchemFormat, Item FROM Schematic WHERE SchemOwner = ? ORDER BY SchemName", schemOwner); + return schemsOfUser.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); + while(rs.next()){ + schematics.add(new Schematic(rs)); } List addedSchems = SchematicMember.getAccessibleSchems(schemOwner); for(SchematicMember schem : addedSchems){ schematics.add(getSchemFromDB(schem.getSchemName(), schem.getSchemOwner())); } return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed listing schematics", e); - } + }, schemOwner); } public int getSchemID() { @@ -132,10 +118,10 @@ public class Schematic { public void setSchemType(SchematicType schemType) { this.schemType = schemType; - SQL.update("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?", schemType.toDB(), schemID); + updateType.update(schemType.toDB(), schemID); } public void setRank(int rank) { - SQL.update("UPDATE Schematic SET Rank = ? WHERE SchemID = ?", rank, schemID); + updateRank.update(rank, schemID); } } diff --git a/src/de/steamwar/bungeecore/sql/SchematicMember.java b/src/de/steamwar/bungeecore/sql/SchematicMember.java index 85b84855..c4ac21ac 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicMember.java +++ b/src/de/steamwar/bungeecore/sql/SchematicMember.java @@ -19,13 +19,15 @@ package de.steamwar.bungeecore.sql; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public class SchematicMember { + + private static final Statement insert = new Statement("INSERT INTO SchemMember (SchemName, SchemOwner, Member) VALUES (?, ?, ?)"); + private static final Statement selectSchems = new Statement("SELECT * FROM SchemMember WHERE Member = ?"); + private static final Statement delete = new Statement("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?"); + private final int schemOwner; private final String schemName; private final int member; @@ -38,82 +40,17 @@ public class SchematicMember { updateDB(); } - public SchematicMember(String schemName, int schemOwner, int schemMember){ - this(schemName, schemOwner, schemMember, true); - } - - public SchematicMember(String schemName, UUID schemOwner, UUID schemMember){ - this(schemName, SteamwarUser.get(schemOwner).getId(), SteamwarUser.get(schemMember).getId(), true); - } - private void updateDB(){ - SQL.update("INSERT INTO SchemMember (SchemName, SchemOwner, Member) VALUES (?, ?, ?)", schemName, schemOwner, member); - } - - public static SchematicMember getSchemMemberFromDB(String schemName, UUID schemOwner, UUID schemMember){ - return getSchemMemberFromDB(schemName, SteamwarUser.get(schemOwner).getId(), SteamwarUser.get(schemMember).getId()); - } - - public static SchematicMember getSchemMemberFromDB(String schemName, int schemOwner, int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND SchemOwner = ? AND Member = ?", schemName, schemOwner, schemMember); - try { - if(schematicMember == null || !schematicMember.next()){ - return null; - } - return new SchematicMember(schemName, schemOwner, schemMember, false); - } catch (SQLException e) { - throw new SecurityException("Could not get schemmember", e); - } - } - - public static SchematicMember getMemberBySchematic(String schemName, int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND Member = ?", schemName, schemMember); - try { - if(schematicMember == null || !schematicMember.next()){ - return null; - } - int schemOwner = schematicMember.getInt("SchemOwner"); - return new SchematicMember(schemName, schemOwner, schemMember, false); - } catch (SQLException e) { - throw new SecurityException("Could not get member", e); - } - } - - public static List getSchemMembers(String schemName, UUID schemOwner){ - return getSchemMembers(schemName, SteamwarUser.get(schemOwner).getId()); - } - - public static List getSchemMembers(String schemName, int schemOwner){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND SchemOwner = ?", schemName, schemOwner); - try { - List schematicMembers = new ArrayList<>(); - while(schematicMember.next()){ - int schemMember = schematicMember.getInt("Member"); - schematicMembers.add(new SchematicMember(schemName, schemOwner, schemMember, false)); - } - return schematicMembers; - } catch (SQLException e) { - throw new SecurityException("Could not get schemmembers", e); - } - } - - public static List getAccessibleSchems(UUID schemMember){ - return getAccessibleSchems(SteamwarUser.get(schemMember).getId()); + insert.update(schemName, schemOwner, member); } public static List getAccessibleSchems(int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE Member = ?", schemMember); - try { + return selectSchems.select(rs -> { List schematicMembers = new ArrayList<>(); - while(schematicMember.next()){ - String schemName = schematicMember.getString("SchemName"); - int schemOwner = schematicMember.getInt("SchemOwner"); - schematicMembers.add(new SchematicMember(schemName, schemOwner, schemMember, false)); - } + while(rs.next()) + schematicMembers.add(new SchematicMember(rs.getString("SchemName"), rs.getInt("SchemOwner"), schemMember, false)); return schematicMembers; - } catch (SQLException e) { - throw new SecurityException("Could not get accessible schems", e); - } + }, schemMember); } public int getSchemOwner() { @@ -129,6 +66,6 @@ public class SchematicMember { } public void remove(){ - SQL.update("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?", schemOwner, schemName, member); + delete.update(schemOwner, schemName, member); } } diff --git a/src/de/steamwar/bungeecore/sql/Session.java b/src/de/steamwar/bungeecore/sql/Session.java index 7f48659a..9793c353 100644 --- a/src/de/steamwar/bungeecore/sql/Session.java +++ b/src/de/steamwar/bungeecore/sql/Session.java @@ -22,9 +22,12 @@ package de.steamwar.bungeecore.sql; import java.sql.Timestamp; public class Session { + + private static final Statement insert = new Statement("INSERT INTO Session (UserID, StartTime, EndTime) VALUES (?, ?, NOW())"); + private Session(){} public static void insertSession(int userID, Timestamp startTime){ - SQL.update("INSERT INTO Session (UserID, StartTime, EndTime) VALUES (?, ?, NOW())", userID, startTime); + insert.update(userID, startTime); } } diff --git a/src/de/steamwar/bungeecore/sql/Statement.java b/src/de/steamwar/bungeecore/sql/Statement.java new file mode 100644 index 00000000..eac76505 --- /dev/null +++ b/src/de/steamwar/bungeecore/sql/Statement.java @@ -0,0 +1,137 @@ +/* + This file is a part of the SteamWar software. + + Copyright (C) 2020 SteamWar.de-Serverteam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + */ + +package de.steamwar.bungeecore.sql; + +import de.steamwar.bungeecore.BungeeCore; +import net.md_5.bungee.api.ProxyServer; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; + +public class Statement { + private static final List statements = new ArrayList<>(); + + private static Connection con; + private static String url; + private static String user; + private static String password; + + public static void connect(String url, String user, String password) { + Statement.url = url; + Statement.user = user; + Statement.password = password; + try { + con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); + } catch (SQLException e) { + ProxyServer.getInstance().stop(); + throw new SecurityException("Could not start SQL-Connection", e); + } + } + + private static void reset(SQLException e) { + BungeeCore.get().getLogger().log(Level.WARNING, "SQL Exception thrown", e); + close(); + connect(url, user, password); + try { + for (Statement statement : statements) { + statement.init(); + } + } catch (SQLException ex) { + throw new SecurityException("Could not reprepare SQL Statements", ex); + } + } + + public static void close() { + for (Statement statement : statements) { + try { + statement.st.close(); + } catch (SQLException e) { + BungeeCore.get().getLogger().log(Level.INFO, "Could not close statement", e); + } + } + + try { + con.close(); + } catch (SQLException e) { + BungeeCore.log("Could not close SQL-Connection", e); + } + } + + private final String sql; + private PreparedStatement st; + + Statement(String sql) { + this.sql = sql; + statements.add(this); + try { + init(); + } catch (SQLException e) { + reset(e); + } + } + + private synchronized void init() throws SQLException { + st = con.prepareStatement(sql); + } + + T select(ResultSetUser user, Object... objects) { + return prepare(() -> { + ResultSet rs = st.executeQuery(); + T result = user.use(rs); + rs.close(); + return result; + }, objects); + } + + void update(Object... objects) { + prepare(st::executeUpdate, objects); + } + + private synchronized T prepare(SQLRunnable runnable, Object... objects) { + try { + setObjects(objects); + return runnable.run(); + } catch (SQLException e) { + reset(e); + try { + setObjects(objects); + return runnable.run(); + } catch (SQLException ex) { + throw new SecurityException("Could not execute SQL statement", ex); + } + } + } + + private void setObjects(Object... objects) throws SQLException { + for (int i = 0; i < objects.length; i++) { + st.setObject(i + 1, objects[i]); + } + } + + interface ResultSetUser { + T use(ResultSet rs) throws SQLException; + } + + private interface SQLRunnable { + T run() throws SQLException; + } +} diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 00fd2218..0956d671 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -24,16 +24,14 @@ import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.commands.WebregisterCommand; import de.steamwar.bungeecore.listeners.ConnectionListener; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Scanner; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.ProxiedPlayer; +import java.io.IOException; import java.net.InetAddress; +import java.net.URL; import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; @@ -41,18 +39,26 @@ import java.sql.Timestamp; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; +import java.util.Scanner; import java.util.UUID; +import java.util.logging.Level; public class SteamwarUser { - private final int id; - private final UUID uuid; - private String userName; - private UserGroup userGroup; - private int team; - private boolean leader; - private Map punishments; - private String discordId; + + private static final Statement updateName = new Statement("UPDATE UserData SET UserName = ? WHERE id = ?"); + private static final Statement updateBedrock = new Statement("UPDATE UserData SET Bedrock = ? WHERE id = ?"); + private static final Statement insert = new Statement("INSERT INTO UserData (UUID, UserName, UserGroup) VALUES (?, ?, 'Member')"); + private static final Statement byUUID = new Statement("SELECT * FROM UserData WHERE UUID = ?"); + private static final Statement byName = new Statement("SELECT * FROM UserData WHERE lower(UserName) = ?"); + private static final Statement byID = new Statement("SELECT * FROM UserData WHERE id = ?"); + private static final Statement byDiscord = new Statement("SELECT * FROM UserData WHERE DiscordId = ?"); + private static final Statement updateTeam = new Statement("Update UserData SET Team = ? WHERE id = ?"); + private static final Statement updateDiscord = new Statement("Update UserData SET DiscordId = ? WHERE id = ?"); + private static final Statement deleteIPs = new Statement("DELETE FROM BannedUserIPs WHERE UserID = ?"); + private static final Statement updateLeader = new Statement("Update UserData SET Leader = ? WHERE id = ?"); + private static final Statement getPlaytime = new Statement("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ?"); + private static final Statement getFirstjoin = new Statement("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ?"); private static final Map usersByName = new HashMap<>(); private static final Map usersByUUID = new HashMap<>(); @@ -62,6 +68,15 @@ public class SteamwarUser { private static final String API_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static final JsonParser jsonParser = new JsonParser(); + private final int id; + private final UUID uuid; + private String userName; + private final UserGroup userGroup; + private int team; + private boolean leader; + private final Map punishments; + private String discordId; + static { try { LIXFEL_DE = InetAddress.getByAddress(new byte[]{(byte) 195, (byte) 201, (byte) 242, 43}); @@ -93,7 +108,7 @@ public class SteamwarUser { if(user != null){ String userName = connection.getName(); if(!user.userName.equals(userName)){ - SQL.update("UPDATE UserData SET UserName = ? WHERE id = ?", userName, user.id); + updateName.update(userName, user.id); WebregisterCommand.changeUsername(user.userName, userName); user.userName = userName; } @@ -105,7 +120,7 @@ public class SteamwarUser { } boolean bedrock = connection.getAddress().getAddress().equals(LIXFEL_DE); - SQL.update("UPDATE UserData SET Bedrock = ? WHERE id = ?", bedrock, user.id); + updateBedrock.update(bedrock, user.id); return user; } @@ -115,7 +130,7 @@ public class SteamwarUser { return user; } - UUID uuid = SteamwarUser.loadUUID(name); + UUID uuid = SteamwarUser.getUUIDofOfflinePlayer(name); if (uuid == null) { return null; } @@ -124,21 +139,28 @@ public class SteamwarUser { } private static SteamwarUser createUserInDatabase(UUID uuid, String name) { - SQL.update("INSERT INTO UserData (UUID, UserName, UserGroup) VALUES (?, ?, 'Member')", uuid.toString(), name); - return dbInit(SQL.select("SELECT * FROM UserData WHERE UUID = ?", uuid.toString())); + insert.update(uuid.toString(), name); + return get(uuid); } public static SteamwarUser get(String userName){ userName = userName.toLowerCase(); if(usersByName.containsKey(userName)) return usersByName.get(userName); - return dbInit(SQL.select("SELECT * FROM UserData WHERE lower(UserName) = ?", userName)); + return byName.select(rs -> { + if(rs.next()) + return new SteamwarUser(rs); + return null; + }, userName); } public static SteamwarUser get(UUID uuid){ if(usersByUUID.containsKey(uuid)) return usersByUUID.get(uuid); - return dbInit(SQL.select("SELECT * FROM UserData WHERE UUID = ?", uuid.toString())); + return byUUID.select(rs -> { + rs.next(); + return new SteamwarUser(rs); + }, uuid.toString()); } public static SteamwarUser get(ProxiedPlayer player){ @@ -148,13 +170,20 @@ public class SteamwarUser { public static SteamwarUser get(int id){ if(usersById.containsKey(id)) return usersById.get(id); - return dbInit(SQL.select("SELECT * FROM UserData WHERE id = ?", id)); + return byID.select(rs -> { + rs.next(); + return new SteamwarUser(rs); + }, id); } public static SteamwarUser get(Long discordId) { if(usersByDiscord.containsKey(discordId.toString())) return usersByDiscord.get(discordId.toString()); - return dbInit(SQL.select("SELECT * FROM UserData WHERE DiscordId = ?", discordId)); + return byDiscord.select(rs -> { + if(rs.next()) + return new SteamwarUser(rs); + return null; + }, discordId); } public static void clearCache(){ @@ -164,25 +193,20 @@ public class SteamwarUser { usersByDiscord.clear(); } - public static UUID loadUUID(String playerName) { + private static UUID getUUIDofOfflinePlayer(String playerName) { try { final URL url = new URL(API_URL + playerName); - return getUniqueIdFromString(jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString()); - } catch (MalformedURLException e) { - e.printStackTrace(); + String uuid = jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString(); + return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } catch (IOException e) { - e.printStackTrace(); + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID", e); + return null; } - return null; - } - - private static UUID getUniqueIdFromString(String uuid) { - return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } public void setTeam(int team){ this.team = team; - SQL.update("Update UserData SET Team = ? WHERE id = ?", team, id); + updateTeam.update(team, id); setLeader(false); } @@ -217,7 +241,7 @@ public class SteamwarUser { public void setDiscordId(String discordId) { usersByDiscord.remove(this.discordId); this.discordId = discordId; - SQL.update("Update UserData SET DiscordId = ? WHERE id = ?", discordId, id); + updateDiscord.update(discordId, id); if(discordId != null) { usersByDiscord.put(discordId, this); } @@ -227,7 +251,7 @@ public class SteamwarUser { if(!punishments.containsKey(Punishment.PunishmentType.Ban)) return false; if(!punishments.get(Punishment.PunishmentType.Ban).isCurrent()) { - SQL.update("DELETE FROM BannedUserIPs WHERE UserID = ?", id); + deleteIPs.update(id); punishments.remove(Punishment.PunishmentType.Ban); return false; } @@ -298,38 +322,20 @@ public class SteamwarUser { punishments.put(Punishment.PunishmentType.Mute, Punishment.createPunishment(id, from, Punishment.PunishmentType.Mute, muteReason, time, perma)); } - private static SteamwarUser dbInit(ResultSet rs){ - try { - if(!rs.next()) - return null; - return new SteamwarUser(rs); - } catch (SQLException e) { - throw new SecurityException(e); - } - } - public double getOnlinetime() { - ResultSet set = SQL.select("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ?", id); - try { - if(!set.next()) - return 0; - return set.getBigDecimal("Playtime").doubleValue(); - } catch (SQLException throwables) { - throw new SecurityException("Could not load Online Time", throwables); - } catch (NullPointerException e) { //When no Sessions are recorded - return 0; - } + return getPlaytime.select(rs -> { + if(rs.next()) + return rs.getBigDecimal("Playtime").doubleValue(); + return 0.0; + }, id); } public Timestamp getFirstjoin() { - ResultSet set = SQL.select("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ?", id); - try { - if(!set.next()) - return null; - return set.getTimestamp("FirstJoin"); - } catch (SQLException throwables) { - throw new SecurityException("Could not load First Join"); - } + return getFirstjoin.select(rs -> { + if(rs.next()) + return rs.getTimestamp("FirstJoin"); + return null; + }, id); } public boolean isLeader() { @@ -338,6 +344,6 @@ public class SteamwarUser { public void setLeader(boolean leader) { this.leader = leader; - SQL.update("Update UserData SET Leader = ? WHERE id = ?", leader, id); + updateLeader.update(leader, id); } } diff --git a/src/de/steamwar/bungeecore/sql/Team.java b/src/de/steamwar/bungeecore/sql/Team.java index b5c083bd..f721fa5d 100644 --- a/src/de/steamwar/bungeecore/sql/Team.java +++ b/src/de/steamwar/bungeecore/sql/Team.java @@ -19,25 +19,31 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import static de.steamwar.bungeecore.sql.SQL.select; - public class Team { + + private static final Statement insert = new Statement("INSERT INTO Team (TeamKuerzel, TeamName) VALUES (?, ?)"); + private static final Statement delete = new Statement("UPDATE Team SET TeamDeleted = 1 WHERE TeamID = ?"); + private static final Statement update = new Statement("INSERT INTO Team (TeamID, TeamKuerzel, TeamName, TeamColor) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName), TeamKuerzel = VALUES(TeamKuerzel), TeamColor = VALUES(TeamColor)"); + private static final Statement getSize = new Statement("SELECT COUNT(id) FROM UserData WHERE Team = ?"); + private static final Statement getMembers = new Statement("SELECT id FROM UserData WHERE Team = ?"); + private static final Statement byId = new Statement("SELECT * FROM Team WHERE TeamID = ?"); + private static final Statement byName = new Statement("SELECT * FROM Team WHERE (lower(TeamName) = ? OR lower(TeamKuerzel) = ?) AND NOT TeamDeleted"); + private static final Statement all = new Statement("SELECT * FROM Team WHERE NOT TeamDeleted"); + + private static final List teamCache = new LinkedList<>(); + private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); + private final int teamId; private String teamKuerzel; private String teamName; private String teamColor; - private static final List teamCache = new LinkedList<>(); - private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); - private Team(int id, String kuerzel, String name, String color){ teamId = id; teamKuerzel = kuerzel; @@ -52,8 +58,8 @@ public class Team { this(rs.getInt("TeamID"), rs.getString("TeamKuerzel"), rs.getString("TeamName"), rs.getString("TeamColor")); } - public static void create(String kuerzel, String name, SteamwarUser user){ - SQL.update("INSERT INTO Team (TeamKuerzel, TeamName) VALUES (?, ?)", kuerzel, name); + public static void create(String kuerzel, String name){ + insert.update(kuerzel, name); } public static Team get(int id){ @@ -64,51 +70,38 @@ public class Team { for(Team team : teamCache) if(team.teamId == id) return team; - return load(select("SELECT * FROM Team WHERE TeamID = ?", id)); + return byId.select(rs -> { + rs.next(); + return new Team(rs); + }, id); } public static Team get(String name){ for(Team team : teamCache) - if(team.teamName.equalsIgnoreCase(name)) + if(team.teamName.equalsIgnoreCase(name) || team.teamKuerzel.equalsIgnoreCase(name)) return team; - for(Team team : teamCache) - if(team.teamKuerzel.equalsIgnoreCase(name)) - return team; - return load(select("SELECT * FROM Team WHERE (lower(TeamName) = ? OR lower(TeamKuerzel) = ?) AND NOT TeamDeleted", name.toLowerCase(), name.toLowerCase())); + return byName.select(rs -> { + if(rs.next()) + return new Team(rs); + return null; + }, name.toLowerCase(), name.toLowerCase()); } public static List getAll(){ clearCache(); - try{ - ResultSet rs = select("SELECT * FROM Team WHERE NOT TeamDeleted"); - if(rs == null) - return teamCache; - + return all.select(rs -> { while(rs.next()) new Team(rs); - } catch (SQLException e) { - BungeeCore.log("Could not get all Teams", e); - } - return teamCache; + return teamCache; + }); } public static void clearCache(){ teamCache.clear(); } - private static Team load(ResultSet dbteam){ - try { - if(!dbteam.next()) - return null; - return new Team(dbteam); - } catch (SQLException e) { - BungeeCore.log("Could not load Team", e); - return null; - } - } - private void updateDB(){ - SQL.update("INSERT INTO Team (TeamID, TeamKuerzel, TeamName, TeamColor) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName), TeamKuerzel = VALUES(TeamKuerzel), TeamColor = VALUES(TeamColor)", teamId, teamKuerzel, teamName, teamColor); + update.update(teamId, teamKuerzel, teamName, teamColor); } public int getTeamId() { @@ -143,33 +136,24 @@ public class Team { } public int size(){ - ResultSet rs = select("SELECT COUNT(id) FROM UserData WHERE Team = ?", teamId); - try { + return getSize.select(rs -> { rs.next(); return rs.getInt("COUNT(id)"); - }catch (SQLException e) { - BungeeCore.log("Could not get Teamsize", e); - return 1000; - } + }, teamId); } public void disband(SteamwarUser user){ user.setLeader(false); - SQL.update("UPDATE Team SET TeamDeleted = 1 WHERE TeamID = ?", teamId); + delete.update(teamId); teamCache.remove(this); } public List getMembers(){ - try{ - ResultSet memberlist = select("SELECT id FROM UserData WHERE Team = ?", teamId); + return getMembers.select(rs -> { List members = new ArrayList<>(); - while(memberlist.next()){ - members.add(memberlist.getInt("id")); - } + while(rs.next()) + members.add(rs.getInt("id")); return members; - }catch(SQLException e){ - BungeeCore.log("Could not get Teammembers", e); - } - return new ArrayList<>(); + }, teamId); } } diff --git a/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java b/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java index 2da396b9..68b1192e 100644 --- a/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java +++ b/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java @@ -19,55 +19,46 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; -import java.sql.SQLException; import java.util.HashSet; import java.util.Set; public class TeamTeilnahme { private TeamTeilnahme(){} + private static final Statement insert = new Statement("INSERT INTO TeamTeilnahme (TeamID, EventID) VALUES (?, ?)"); + private static final Statement delete = new Statement("DELETE FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); + private static final Statement byEventTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); + private static final Statement byEvent = new Statement("SELECT * FROM TeamTeilnahme WHERE EventID = ?"); + private static final Statement byTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ?"); + public static void teilnehmen(int teamID, int eventID){ - SQL.update("INSERT INTO TeamTeilnahme (TeamID, EventID) VALUES (?, ?)", teamID, eventID); + insert.update(teamID, eventID); } public static void notTeilnehmen(int teamID, int eventID){ - SQL.update("DELETE FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?", teamID, eventID); + delete.update(teamID, eventID); } public static boolean nimmtTeil(int teamID, int eventID){ - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?", teamID, eventID); - try{ - return rs.next(); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahme", e); - throw new SecurityException(); - } + return byEventTeam.select(ResultSet::next, teamID, eventID); } public static Set getTeams(int eventID){ - Set teams = new HashSet<>(); - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE EventID = ?", eventID); - try{ + return byEvent.select(rs -> { + Set teams = new HashSet<>(); while(rs.next()) teams.add(Team.get(rs.getInt("TeamID"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahmen", e); - } - return teams; + return teams; + }, eventID); } public static Set getEvents(int teamID){ - Set events = new HashSet<>(); - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE TeamID = ?", teamID); - try{ + return byTeam.select(rs -> { + Set events = new HashSet<>(); while(rs.next()) events.add(Event.get(rs.getInt("EventID"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahmen", e); - } - return events; + return events; + }, teamID); } } From 49105c4f738825ba5f78d75c999713b37c3aa316 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 4 Sep 2021 10:51:11 +0200 Subject: [PATCH 06/41] Hotfix Ignoresystem Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/IgnoreSystem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java index 185fb089..7309f8ab 100644 --- a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java +++ b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java @@ -25,7 +25,7 @@ import java.sql.ResultSet; public class IgnoreSystem{ - private static final Statement select = new Statement("SELECT COUNT(*) AS blocked FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); + private static final Statement select = new Statement("SELECT * FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); private static final Statement insert = new Statement("INSERT INTO IgnoredPlayers (Ignorer, Ignored) VALUES (?, ?)"); private static final Statement delete = new Statement("DELETE FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); From 05c37c0df07ecda1905569c04f4809b6e9e39a80 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 4 Sep 2021 21:15:30 +0200 Subject: [PATCH 07/41] Hotfix SteamwarUser Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 0956d671..67c35960 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -158,8 +158,9 @@ public class SteamwarUser { if(usersByUUID.containsKey(uuid)) return usersByUUID.get(uuid); return byUUID.select(rs -> { - rs.next(); - return new SteamwarUser(rs); + if(rs.next()) + return new SteamwarUser(rs); + return null; }, uuid.toString()); } From f0e7f52fd65a8975ba50c9898d7ca3ecd3467d66 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 4 Sep 2021 22:18:38 +0200 Subject: [PATCH 08/41] -21s Start time. Signed-off-by: Lixfel --- .../bungeecore/bot/SteamwarDiscordBot.java | 6 +++--- .../bot/util/DiscordRolesMessage.java | 17 ++++++++++------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index 7c5f1dba..57d67f58 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -103,10 +103,10 @@ public class SteamwarDiscordBot { serverTeamChatListener = new ServerTeamChatListener(); new SlashCommandListener(); - jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).complete()); + jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); - guild.retrieveCommands().complete().forEach(command -> guild.deleteCommandById(command.getId()).complete()); + guild.retrieveCommands().complete().forEach(command -> guild.deleteCommandById(command.getId()).queue()); CommandListUpdateAction commands = jda.getGuildById(SteamwarDiscordBotConfig.GUILD).updateCommands(); addCommand(commands, new MuteCommand()); addCommand(commands, new BanCommand()); @@ -114,7 +114,7 @@ public class SteamwarDiscordBot { addCommand(commands, new TeamCommand()); addCommand(commands, new ListCommand()); addCommand(commands, new UnbanCommand()); - commands.complete(); + commands.queue(); } private void addCommand(CommandListUpdateAction commands, BasicDiscordCommand basicDiscordCommand) { diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordRolesMessage.java b/src/de/steamwar/bungeecore/bot/util/DiscordRolesMessage.java index baa88019..1486debd 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordRolesMessage.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordRolesMessage.java @@ -38,10 +38,6 @@ public class DiscordRolesMessage { public void sendMessage() { TextChannel channel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.ROLES_CHANNEL); assert channel != null; - Message message = null; - if(channel.hasLatestMessage()) { - message = channel.getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null); - } MessageBuilder builder = new MessageBuilder(); builder.setContent(SteamwarDiscordBotConfig.ROLES_BASE_MESSAGE); @@ -49,10 +45,17 @@ public class DiscordRolesMessage { SteamwarDiscordBotConfig.ROLES.forEach(discordRole -> buttons.add(discordRole.toButton())); builder.setActionRows(ActionRow.of(buttons)); - if (message != null) { - message.editMessage(builder.build()).complete(); + if(channel.hasLatestMessage()) { + channel.getIterableHistory().queue(messages -> { + Message message = messages.stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null); + if (message != null) { + message.editMessage(builder.build()).queue(); + } else { + channel.sendMessage(builder.build()).queue(); + } + }); } else { - channel.sendMessage(builder.build()).complete(); + channel.sendMessage(builder.build()).queue(); } } } From a0ac0a0be25d56d7ec6dfe96ce61c96720ca4d20 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sat, 4 Sep 2021 23:15:08 +0200 Subject: [PATCH 09/41] Async (TM) Signed-off-by: Chaoscaot --- .../steamwar/bungeecore/bot/AuthManager.java | 10 +-- .../bungeecore/bot/SteamwarDiscordBot.java | 64 ++++++++++--------- .../bungeecore/bot/commands/BanCommand.java | 6 +- .../bot/commands/BasicDiscordCommand.java | 2 +- .../bungeecore/bot/commands/ListCommand.java | 2 +- .../bungeecore/bot/commands/MuteCommand.java | 2 +- .../bungeecore/bot/commands/TeamCommand.java | 10 +-- .../bungeecore/bot/commands/UnbanCommand.java | 7 +- .../bungeecore/bot/commands/WhoisCommand.java | 2 +- .../bungeecore/bot/events/EventManager.java | 2 +- .../bot/events/SchematicsManager.java | 2 +- .../bot/listeners/AnnouncementListener.java | 2 +- .../bot/listeners/DiscordAuthListener.java | 10 +-- .../bot/listeners/DiscordTicketListener.java | 16 ++--- .../bot/listeners/IngameChatListener.java | 6 +- .../RolesInteractionButtonListener.java | 4 +- .../bot/listeners/ServerTeamChatListener.java | 1 - .../bungeecore/bot/util/DiscordRanks.java | 48 +++++++------- .../bot/util/DiscordRulesMessage.java | 4 +- .../bot/util/DiscordTicketMessage.java | 4 +- 20 files changed, 101 insertions(+), 103 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/AuthManager.java b/src/de/steamwar/bungeecore/bot/AuthManager.java index 1502b681..7d8b005b 100644 --- a/src/de/steamwar/bungeecore/bot/AuthManager.java +++ b/src/de/steamwar/bungeecore/bot/AuthManager.java @@ -48,11 +48,7 @@ public class AuthManager { TOKENS.put(code, member.getIdLong()); BungeeCore.log("Created Discord Auth-Token: " + code + " for: " + member.getUser().getAsTag()); - ScheduledTask[] task = new ScheduledTask[1]; - task[0] = BungeeCore.get().getProxy().getScheduler().schedule(BungeeCore.get(), () -> { - TOKENS.remove(code); - task[0].cancel(); - }, 10, 10, TimeUnit.MINUTES); + BungeeCore.get().getProxy().getScheduler().schedule(BungeeCore.get(), () -> TOKENS.remove(code), 10, TimeUnit.MINUTES); return code; } @@ -66,10 +62,10 @@ public class AuthManager { builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")), Button.danger("invalid", "Ich war das nicht"))); try { - member.getUser().openPrivateChannel().complete().sendMessage(builder.build()).complete(); + member.getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(builder.build()).queue()); if (member.getNickname() == null) { try { - member.getGuild().modifyNickname(member, user.getUserName()).complete(); + member.getGuild().modifyNickname(member, user.getUserName()).queue(); } catch (Exception e) { // Ignored } diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index 57d67f58..381720e9 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -78,43 +78,45 @@ public class SteamwarDiscordBot { } catch (LoginException e) { throw new SecurityException("Could not Login: " + SteamwarDiscordBotConfig.TOKEN, e); } - try { - jda.awaitReady(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - activity(); - EventManager.update(); - SchematicsManager.update(); - ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { + ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { + try { + jda.awaitReady(); + } catch (InterruptedException e) { + e.printStackTrace(); + } activity(); EventManager.update(); SchematicsManager.update(); - }, 30, 30, TimeUnit.SECONDS); - DiscordRolesMessage.sendMessage(); - DiscordRulesMessage.sendMessage(); - DiscordTicketMessage.sendMessage(); + ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { + activity(); + EventManager.update(); + SchematicsManager.update(); + }, 30, 30, TimeUnit.SECONDS); + DiscordRolesMessage.sendMessage(); + DiscordRulesMessage.sendMessage(); + DiscordTicketMessage.sendMessage(); - new RolesInteractionButtonListener(); - new DiscordTicketListener(); - new DiscordAuthListener(); - announcementListener = new AnnouncementListener(); - ingameChatListener = new IngameChatListener(); - serverTeamChatListener = new ServerTeamChatListener(); - new SlashCommandListener(); + new RolesInteractionButtonListener(); + new DiscordTicketListener(); + new DiscordAuthListener(); + announcementListener = new AnnouncementListener(); + ingameChatListener = new IngameChatListener(); + serverTeamChatListener = new ServerTeamChatListener(); + new SlashCommandListener(); - jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); + jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); - Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); - guild.retrieveCommands().complete().forEach(command -> guild.deleteCommandById(command.getId()).queue()); - CommandListUpdateAction commands = jda.getGuildById(SteamwarDiscordBotConfig.GUILD).updateCommands(); - addCommand(commands, new MuteCommand()); - addCommand(commands, new BanCommand()); - addCommand(commands, new WhoisCommand()); - addCommand(commands, new TeamCommand()); - addCommand(commands, new ListCommand()); - addCommand(commands, new UnbanCommand()); - commands.queue(); + Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); + guild.retrieveCommands().queue(commands -> commands.forEach(command -> guild.deleteCommandById(command.getId()).queue())); + CommandListUpdateAction commands = jda.getGuildById(SteamwarDiscordBotConfig.GUILD).updateCommands(); + addCommand(commands, new MuteCommand()); + addCommand(commands, new BanCommand()); + addCommand(commands, new WhoisCommand()); + addCommand(commands, new TeamCommand()); + addCommand(commands, new ListCommand()); + addCommand(commands, new UnbanCommand()); + commands.queue(); + }); } private void addCommand(CommandListUpdateAction commands, BasicDiscordCommand basicDiscordCommand) { diff --git a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java index 7d3772f5..e55b97e6 100644 --- a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java @@ -45,13 +45,13 @@ public class BanCommand extends BasicDiscordCommand { SteamwarUser sender = SteamwarUser.get(event.getMember().getIdLong()); SteamwarUser target = SteamwarUser.getOrCreateOfflinePlayer(event.getOption("user").getAsString()); if (target == null) { - event.reply("Angegebener User invalide").setEphemeral(true).complete(); + event.reply("Angegebener User invalide").setEphemeral(true).queue(); return; } Timestamp time = de.steamwar.bungeecore.commands.BanCommand.parseTime(null, event.getOption("time").getAsString()); if (time == null) { - event.reply("Angegebene Zeit invalide").setEphemeral(true).complete(); + event.reply("Angegebene Zeit invalide").setEphemeral(true).queue(); return; } @@ -60,6 +60,6 @@ public class BanCommand extends BasicDiscordCommand { target.ban(time, msg, sender.getId(), isPerma); Message.team("BAN_TEAM_BANNED", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg); - event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gebannt").setEphemeral(true).complete(); + event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gebannt").setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/commands/BasicDiscordCommand.java b/src/de/steamwar/bungeecore/bot/commands/BasicDiscordCommand.java index a767ebaa..29bbe85d 100644 --- a/src/de/steamwar/bungeecore/bot/commands/BasicDiscordCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/BasicDiscordCommand.java @@ -46,7 +46,7 @@ public abstract class BasicDiscordCommand extends CommandData { Member member = event.getMember(); SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong()); if (steamwarUser == null || (!steamwarUser.getUserGroup().isTeamGroup() && steamwarUser.getUserGroup() != UserGroup.Builder)) { - event.reply("Du hast für " + event.getName() + " keine Rechte oder es existiert keine Verknüpfung für dich.").setEphemeral(true).complete(); + event.reply("Du hast für " + event.getName() + " keine Rechte oder es existiert keine Verknüpfung für dich.").setEphemeral(true).queue(); return false; } return true; diff --git a/src/de/steamwar/bungeecore/bot/commands/ListCommand.java b/src/de/steamwar/bungeecore/bot/commands/ListCommand.java index 20501808..3b014f97 100644 --- a/src/de/steamwar/bungeecore/bot/commands/ListCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/ListCommand.java @@ -38,6 +38,6 @@ public class ListCommand extends BasicDiscordCommand { de.steamwar.bungeecore.commands.ListCommand.getPlayerMap().forEach((s, proxiedPlayers) -> { embedBuilder.addField(s, proxiedPlayers.stream().map(player -> "`" + player.getName() + "`").collect(Collectors.joining(", ")), true); }); - event.replyEmbeds(embedBuilder.build()).setEphemeral(true).complete(); + event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java index 700baacd..1c0bc96b 100644 --- a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java @@ -61,6 +61,6 @@ public class MuteCommand extends BasicDiscordCommand { target.mute(time, msg, sender.getId(), isPerma); Message.team("MUTE_TEAM_MUTED", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg); - event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gemutet").setEphemeral(true).complete(); + event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gemutet").setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/commands/TeamCommand.java b/src/de/steamwar/bungeecore/bot/commands/TeamCommand.java index 53d70397..e0b35453 100644 --- a/src/de/steamwar/bungeecore/bot/commands/TeamCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/TeamCommand.java @@ -58,11 +58,11 @@ public class TeamCommand extends BasicDiscordCommand { Team team; if (optionMapping == null) { if (steamwarUser == null) { - event.reply("Dein Discord ist nicht verknüpft").setEphemeral(true).complete(); + event.reply("Dein Discord ist nicht verknüpft").setEphemeral(true).queue(); return; } if (steamwarUser.getTeam() == 0) { - event.reply("Du bist in keinem Team").setEphemeral(true).complete(); + event.reply("Du bist in keinem Team").setEphemeral(true).queue(); return; } team = Team.get(steamwarUser.getTeam()); @@ -70,7 +70,7 @@ public class TeamCommand extends BasicDiscordCommand { team = Team.get(optionMapping.getAsString()); } if (team == null) { - event.reply("Unbekanntes Team").setEphemeral(true).complete(); + event.reply("Unbekanntes Team").setEphemeral(true).queue(); return; } EmbedBuilder embedBuilder = new EmbedBuilder(); @@ -81,10 +81,10 @@ public class TeamCommand extends BasicDiscordCommand { embedBuilder.addField("Leader", members.stream().filter(SteamwarUser::isLeader).map(user -> "`" + (isOnline(user) ? emoji.getAsMention() : "") + user.getUserName() + "`").collect(Collectors.joining(" ")), false); embedBuilder.addField("Member", members.stream().filter(user -> !user.isLeader()).map(user -> "`" + (isOnline(user) ? emoji.getAsMention() : "") + user.getUserName() + "`").collect(Collectors.joining(" ")), false); embedBuilder.addField("Events", "`" + TeamTeilnahme.getEvents(team.getTeamId()).stream().map(Event::getEventName).collect(Collectors.joining("` `")) + "`", false); - event.replyEmbeds(embedBuilder.build()).setEphemeral(true).complete(); + event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue(); return; default: - event.reply("Unbekannter Befehl").setEphemeral(true).complete(); + event.reply("Unbekannter Befehl").setEphemeral(true).queue(); return; } } diff --git a/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java b/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java index 71471081..925423f6 100644 --- a/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java @@ -19,7 +19,6 @@ package de.steamwar.bungeecore.bot.commands; -import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.SteamwarUser; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -44,16 +43,16 @@ public class UnbanCommand extends BasicDiscordCommand { SteamwarUser sender = SteamwarUser.get(event.getMember().getIdLong()); SteamwarUser target = SteamwarUser.getOrCreateOfflinePlayer(event.getOption("user").getAsString()); if (target == null) { - event.reply("Angegebener User invalide").setEphemeral(true).complete(); + event.reply("Angegebener User invalide").setEphemeral(true).queue(); return; } if (!target.isBanned()) { - event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).complete(); + event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).queue(); return; } target.ban(Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false); - event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).complete(); + event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/commands/WhoisCommand.java b/src/de/steamwar/bungeecore/bot/commands/WhoisCommand.java index b40c0492..8608047c 100644 --- a/src/de/steamwar/bungeecore/bot/commands/WhoisCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/WhoisCommand.java @@ -89,6 +89,6 @@ public class WhoisCommand extends BasicDiscordCommand { embedBuilder.addField(punishment.getType().name() + " von " + SteamwarUser.get(punishment.getPunisher()).getUserName(), "Von: " + punishment.getBantime(punishment.getStartTime(), false) + "\nBis: " + punishment.getBantime(punishment.getEndTime(), punishment.isPerma()) + "\nGrund: " + punishment.getReason(), true); } - event.replyEmbeds(embedBuilder.build()).setEphemeral(true).complete(); + event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/events/EventManager.java b/src/de/steamwar/bungeecore/bot/events/EventManager.java index 56f982cc..d40a80c1 100644 --- a/src/de/steamwar/bungeecore/bot/events/EventManager.java +++ b/src/de/steamwar/bungeecore/bot/events/EventManager.java @@ -119,7 +119,7 @@ public class EventManager { MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.setEmbeds(embedBuilder.build()); if (message == null) { - message = textChannel.sendMessage(messageBuilder.build()).complete(); + textChannel.sendMessage(messageBuilder.build()).queue(message1 -> message = message1); } else { message.editMessage(messageBuilder.build()).complete(); } diff --git a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java index 64809e18..82a83705 100644 --- a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java +++ b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java @@ -65,7 +65,7 @@ public class SchematicsManager { MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.setEmbeds(embedBuilder.build()); if (message == null) { - message = textChannel.sendMessage(messageBuilder.build()).complete(); + textChannel.sendMessage(messageBuilder.build()).queue(message1 -> message = message1); } else { message.editMessage(messageBuilder.build()).queue(); } diff --git a/src/de/steamwar/bungeecore/bot/listeners/AnnouncementListener.java b/src/de/steamwar/bungeecore/bot/listeners/AnnouncementListener.java index 2877fbd3..ab4be193 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/AnnouncementListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/AnnouncementListener.java @@ -45,6 +45,6 @@ public class AnnouncementListener extends BasicDiscordListener { assert textChannel != null; MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.append(message.replace("&", "")); - textChannel.sendMessage(messageBuilder.build()).complete(); + textChannel.sendMessage(messageBuilder.build()).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordAuthListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordAuthListener.java index 514b193f..8ad34282 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordAuthListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordAuthListener.java @@ -35,23 +35,23 @@ public class DiscordAuthListener extends BasicDiscordListener { if(event.getChannel().getId().equals(SteamwarDiscordBotConfig.RULES_CHANNEL) && event.getComponentId().equals("auth")) { String authMessage = AuthManager.createDiscordAuthToken(event.getMember()); if(authMessage != null) { - event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + authMessage + "`` auf dem Minecraft Server ein").setEphemeral(true).complete(); + event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + authMessage + "`` auf dem Minecraft Server ein").setEphemeral(true).queue(); } else { - event.reply("Du hast bereits einen Code am laufen").setEphemeral(true).complete(); + event.reply("Du hast bereits einen Code am laufen").setEphemeral(true).queue(); } } if(event.getComponentId().equals("tada") && event.getChannelType() == ChannelType.PRIVATE) { - event.reply(":tada:").setEphemeral(false).complete(); + event.reply(":tada:").setEphemeral(false).queue(); } if(event.getComponentId().equals("invalid") && event.getChannelType() == ChannelType.PRIVATE) { SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong()); if(user == null) { - event.reply(":question: Da ist keine verknüpfung?").setEphemeral(false).complete(); + event.reply(":question: Da ist keine verknüpfung?").setEphemeral(false).queue(); } else { user.setDiscordId(null); - event.reply(":x: Die Verknüpfung wurde beendet").setEphemeral(false).complete(); + event.reply(":x: Die Verknüpfung wurde beendet").setEphemeral(false).queue(); } } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java index 1ac49209..fab5aaa2 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java @@ -21,6 +21,7 @@ package de.steamwar.bungeecore.bot.listeners; import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.SpecialPermissions; import de.steamwar.bungeecore.bot.config.DiscordTicketType; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.sql.SteamwarUser; @@ -114,7 +115,7 @@ public class DiscordTicketListener extends BasicDiscordListener { logChannel.sendMessage(builder.build()).complete(); Message.team("DISCORD_TICKET_CLOSED", event.getTextChannel().getName()); - event.getTextChannel().delete().reason("Closed").complete(); + event.getTextChannel().delete().reason("Closed").queue(); } } } @@ -126,16 +127,15 @@ public class DiscordTicketListener extends BasicDiscordListener { BungeeCore.get().getProxy().getPlayers().forEach(player -> { if(event.getAuthor().isBot() || event.getAuthor().isSystem()) return; SteamwarUser user = SteamwarUser.get(player); + boolean sendMessage; if(user.getDiscordId() == null) { - if(user.getUserGroup().isTeamGroup()) { - Message.sendPrefixless("DISCORD_TICKET_MESSAGE", player, "Zur nachricht", new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw()); - } + sendMessage = user.getUserGroup().isCheckSchematics(); } else { if(event.getAuthor().getId().equals(user.getDiscordId())) return; - Member member = event.getGuild().retrieveMemberById(user.getDiscordId()).complete(); - if(member.hasPermission(event.getChannel().getManager().getChannel(), Permission.MESSAGE_WRITE)) { - Message.sendPrefixless("DISCORD_TICKET_MESSAGE", player, "Zur nachricht", new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw()); - } + sendMessage = user.getDiscordId().equals(event.getChannel().getTopic()) || user.getUserGroup().isCheckSchematics(); + } + if(sendMessage) { + Message.sendPrefixless("DISCORD_TICKET_MESSAGE", player, "Zur nachricht", new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw()); } }); } diff --git a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java index ce635f30..7163985b 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java @@ -43,15 +43,15 @@ public class IngameChatListener extends BasicDiscordListener { Member member = event.getMember(); SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong()); if (steamwarUser == null || event.getMessage().getContentRaw().length() > 250) { - event.getMessage().delete().complete(); + event.getMessage().delete().queue(); } else { String s = event.getMessage().getContentDisplay(); if (steamwarUser.getUserGroup() == UserGroup.Member && (s.contains("http") || s.contains("www"))) { - event.getMessage().delete().complete(); + event.getMessage().delete().queue(); return; } if (steamwarUser.isMuted() || steamwarUser.isBanned()) { - event.getMessage().delete().complete(); + event.getMessage().delete().queue(); return; } ChatListener.discordChat(steamwarUser, event.getMessage().getContentDisplay().replaceAll("§[a-f0-9]", "").replace('\n', ' ')); diff --git a/src/de/steamwar/bungeecore/bot/listeners/RolesInteractionButtonListener.java b/src/de/steamwar/bungeecore/bot/listeners/RolesInteractionButtonListener.java index 035cd77c..ae0e44de 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/RolesInteractionButtonListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/RolesInteractionButtonListener.java @@ -32,10 +32,10 @@ public class RolesInteractionButtonListener extends BasicDiscordListener { if(event.getType() == InteractionType.COMPONENT && event.getChannelType() == ChannelType.TEXT && event.getTextChannel().getId().equals(SteamwarDiscordBotConfig.ROLES_CHANNEL) && SteamwarDiscordBotConfig.ROLES.stream().anyMatch(discordRole -> discordRole.getRoleId().equals(event.getComponentId()))) { if (event.getMember().getRoles().stream().anyMatch(role -> role.getId().equals(event.getComponentId()))) { event.getGuild().removeRoleFromMember(event.getMember(), event.getGuild().getRoleById(event.getComponentId())).complete(); - event.reply(SteamwarDiscordBotConfig.ROLES_REMOVED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).complete(); + event.reply(SteamwarDiscordBotConfig.ROLES_REMOVED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).queue(); } else { event.getGuild().addRoleToMember(event.getMember(), event.getGuild().getRoleById(event.getComponentId())).complete(); - event.reply(SteamwarDiscordBotConfig.ROLES_ADDED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).complete(); + event.reply(SteamwarDiscordBotConfig.ROLES_ADDED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).queue(); } } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java b/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java index 0f826735..816da82b 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/ServerTeamChatListener.java @@ -22,7 +22,6 @@ package de.steamwar.bungeecore.bot.listeners; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.commands.ServerTeamchatCommand; -import de.steamwar.bungeecore.listeners.ChatListener; import de.steamwar.bungeecore.sql.SteamwarUser; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.Member; diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordRanks.java b/src/de/steamwar/bungeecore/bot/util/DiscordRanks.java index dedf0a56..7224576b 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordRanks.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordRanks.java @@ -22,13 +22,11 @@ package de.steamwar.bungeecore.bot.util; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.sql.SteamwarUser; -import de.steamwar.bungeecore.sql.UserGroup; import lombok.experimental.UtilityClass; import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -41,27 +39,31 @@ public class DiscordRanks { return; } Guild guild = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD); - Member member = guild.retrieveMemberById(steamwarUser.getDiscordId()).complete(); - if (member == null) { - return; - } - - List roleList = member.getRoles(); - Set strings = new HashSet<>(SteamwarDiscordBotConfig.RANKS.values()); - String needed = SteamwarDiscordBotConfig.RANKS.get(steamwarUser.getUserGroup()); - for (Role role : roleList) { - if (!strings.contains(role.getId())) { - continue; + guild.retrieveMemberById(steamwarUser.getDiscordId()).queue(member -> { + List roleList = member.getRoles(); + Set strings = new HashSet<>(SteamwarDiscordBotConfig.RANKS.values()); + String needed = SteamwarDiscordBotConfig.RANKS.get(steamwarUser.getUserGroup()); + for (Role role : roleList) { + if (!strings.contains(role.getId())) { + continue; + } + if (role.getId().equals(needed)) { + needed = ""; + continue; + } + guild.removeRoleFromMember(member, role).complete(); } - if (role.getId().equals(needed)) { - needed = ""; - continue; - } - guild.removeRoleFromMember(member, role).complete(); - } - if (needed != null && !needed.isEmpty()) { - guild.addRoleToMember(member, guild.getRoleById(needed)).complete(); - } + if (needed != null && !needed.isEmpty()) { + guild.addRoleToMember(member, guild.getRoleById(needed)).complete(); + } + }, throwable -> { + if(throwable instanceof ErrorResponseException) { + ErrorResponseException e = (ErrorResponseException) throwable; + if(e.getErrorCode() == 10007) { + steamwarUser.setDiscordId(null); + } + } + }); } } diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordRulesMessage.java b/src/de/steamwar/bungeecore/bot/util/DiscordRulesMessage.java index a1cb6fb6..a061d667 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordRulesMessage.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordRulesMessage.java @@ -60,9 +60,9 @@ public class DiscordRulesMessage { messageBuilder.setEmbeds(builder.build()); messageBuilder.setActionRows(ActionRow.of(buttons), ActionRow.of(authButton)); if (message != null) { - message.editMessage(messageBuilder.build()).complete(); + message.editMessage(messageBuilder.build()).queue(); } else { - channel.sendMessage(messageBuilder.build()).complete(); + channel.sendMessage(messageBuilder.build()).queue(); } } } diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordTicketMessage.java b/src/de/steamwar/bungeecore/bot/util/DiscordTicketMessage.java index ab93000b..ea6cea39 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordTicketMessage.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordTicketMessage.java @@ -56,9 +56,9 @@ public class DiscordTicketMessage { messageBuilder.setEmbeds(builder.build()); messageBuilder.setActionRows(ActionRow.of(buttons)); if (message != null) { - message.editMessage(messageBuilder.build()).complete(); + message.editMessage(messageBuilder.build()).queue(); } else { - channel.sendMessage(messageBuilder.build()).complete(); + channel.sendMessage(messageBuilder.build()).queue(); } } } From b60422245088aa26a52fc8a957592a4474078f65 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 5 Sep 2021 18:47:04 +0200 Subject: [PATCH 10/41] Deny launching multiple bauservers Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/commands/BauCommand.java | 11 ++++++----- .../steamwar/bungeecore/commands/CheckCommand.java | 13 ++++++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index d50f7a76..e8274273 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -261,12 +261,12 @@ public class BauCommand extends BasicCommand { }); } - public static void stopBauserver(ProxiedPlayer p){ + public static boolean stopBauserver(ProxiedPlayer p){ for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId())) { - if(subserver.getServer().getPlayers().isEmpty()){ + if(!subserver.hasStarted()){ Message.send("BAU_START_ALREADY", p); - return; + return false; } subserver.stop(); try { @@ -277,12 +277,13 @@ public class BauCommand extends BasicCommand { break; } } + return true; } private static void testarena(ProxiedPlayer p, String[] args){ FightCommand.createArena(p, "/bau testarena ", args, 1, false, (player, mode, map) -> ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { - stopBauserver(p); - SubserverSystem.startTestServer(p, mode, map, 0, 0); + if(stopBauserver(p)) + SubserverSystem.startTestServer(p, mode, map, 0, 0); })); } diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index c110b3c4..e61dd710 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -234,7 +234,10 @@ public class CheckCommand extends BasicCommand { this.checkList = checkQuestions.get(schematic.getSchemType()).listIterator(); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { - BauCommand.stopBauserver(checker); + if(!BauCommand.stopBauserver(checker)){ + remove(); + return; + } ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemType().fightType()); SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getSchemID(), 0); @@ -323,8 +326,7 @@ public class CheckCommand extends BasicCommand { } private void stop(){ - currentCheckers.remove(checker.getUniqueId()); - currentSchems.remove(schematic.getSchemID()); + remove(); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(checker.getUniqueId())) { @@ -334,5 +336,10 @@ public class CheckCommand extends BasicCommand { } }); } + + private void remove() { + currentCheckers.remove(checker.getUniqueId()); + currentSchems.remove(schematic.getSchemID()); + } } } From 12186e4f783477ebaeb0d1fc9a4e3fe0663e029c Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Tue, 7 Sep 2021 13:37:13 +0200 Subject: [PATCH 11/41] Fixing Signed-off-by: Chaoscaot --- .../steamwar/bungeecore/bot/listeners/DiscordTicketListener.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java index fab5aaa2..8c8c4fa7 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java @@ -21,7 +21,6 @@ package de.steamwar.bungeecore.bot.listeners; import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; -import de.steamwar.bungeecore.SpecialPermissions; import de.steamwar.bungeecore.bot.config.DiscordTicketType; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.sql.SteamwarUser; From 27293fc051a2ab0bfc03c2290233476caff33579 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Tue, 7 Sep 2021 16:49:32 +0200 Subject: [PATCH 12/41] Add Message Spliting Signed-off-by: Chaoscaot --- .../bot/listeners/DiscordTicketListener.java | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java index 8c8c4fa7..f7a2fa22 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordTicketListener.java @@ -75,29 +75,40 @@ public class DiscordTicketListener extends BasicDiscordListener { } else if(event.getComponentId().startsWith("close-")) { TextChannel logChannel = event.getGuild().getTextChannelById(SteamwarDiscordBotConfig.TICKET_LOG); - MessageBuilder builder = new MessageBuilder(); - StringBuilder stringBuilder = new StringBuilder(); + LinkedList stringBuilders = new LinkedList<>(); + stringBuilders.add(new StringBuilder()); new LinkedList<>(event.getTextChannel().getIterableHistory().complete()).descendingIterator().forEachRemaining(message -> { if(message.getAuthor().isSystem() || message.getAuthor().isBot()) return; - stringBuilder.append(" ") + StringBuilder currentBuilder = new StringBuilder(); + currentBuilder.append(" ") .append("**") .append(message.getAuthor().getName()) .append("**: ") .append(message.getContentRaw()); if(!message.getAttachments().isEmpty()) { - stringBuilder.append("\n") + currentBuilder.append("\n") .append("Files: ").append("\n"); - message.getAttachments().forEach(attachment -> stringBuilder.append(attachment.getUrl()).append("\n")); + message.getAttachments().forEach(attachment -> currentBuilder.append(attachment.getUrl()).append("\n")); } - stringBuilder.append("\n"); + currentBuilder.append("\n"); + if(currentBuilder.length() >= 4096) { + stringBuilders.getLast().append(currentBuilder.substring(0, 4090)); + stringBuilders.add(new StringBuilder(currentBuilder.substring(4090, currentBuilder.length() - 1))); + } else if (currentBuilder.length() + stringBuilders.getLast().length() >= 4096) { + stringBuilders.add(new StringBuilder(currentBuilder.toString())); + } else { + stringBuilders.getLast().append(currentBuilder); + } }); - stringBuilder.append("\n"); - stringBuilder.append(" ") - .append("**").append(event.getUser().getName()).append("**: ") - .append("Ticket geschlossen"); + String footer = " **" + event.getUser().getName() + "**: Ticket geschlossen"; + if(stringBuilders.getLast().length() + footer.length() > 4090) { + stringBuilders.add(new StringBuilder(footer)); + } else { + stringBuilders.getLast().append(footer); + } EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setColor(Color.GREEN); @@ -107,11 +118,13 @@ public class DiscordTicketListener extends BasicDiscordListener { embedBuilder.setAuthor(user.getName(), swuser==null?"https://steamwar.de/":("https://steamwar.de/users/" + swuser.getUserName().toLowerCase() + "/"), user.getAvatarUrl()); embedBuilder.setTimestamp(Instant.now()); embedBuilder.setTitle(event.getTextChannel().getName()); - embedBuilder.setDescription(stringBuilder); + stringBuilders.forEach(stringBuilder -> { + embedBuilder.setDescription(stringBuilder.toString()); + MessageBuilder builder = new MessageBuilder(); + builder.setEmbeds(embedBuilder.build()); - builder.setEmbeds(embedBuilder.build()); - - logChannel.sendMessage(builder.build()).complete(); + logChannel.sendMessage(builder.build()).queue(); + }); Message.team("DISCORD_TICKET_CLOSED", event.getTextChannel().getName()); event.getTextChannel().delete().reason("Closed").queue(); From e66990da294c0a7088f77128ad1c2ef161b0ce93 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Tue, 7 Sep 2021 23:55:07 +0200 Subject: [PATCH 13/41] Add Discord Event Teilnahme Signed-off-by: Chaoscaot --- .../bungeecore/bot/SteamwarDiscordBot.java | 1 + .../bungeecore/bot/events/EventManager.java | 22 ++++- .../bot/listeners/DiscordEventListener.java | 95 +++++++++++++++++++ 3 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index 381720e9..ba2ff108 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -99,6 +99,7 @@ public class SteamwarDiscordBot { new RolesInteractionButtonListener(); new DiscordTicketListener(); new DiscordAuthListener(); + new DiscordEventListener(); announcementListener = new AnnouncementListener(); ingameChatListener = new IngameChatListener(); serverTeamChatListener = new ServerTeamChatListener(); diff --git a/src/de/steamwar/bungeecore/bot/events/EventManager.java b/src/de/steamwar/bungeecore/bot/events/EventManager.java index d40a80c1..506e8b7f 100644 --- a/src/de/steamwar/bungeecore/bot/events/EventManager.java +++ b/src/de/steamwar/bungeecore/bot/events/EventManager.java @@ -28,13 +28,22 @@ import de.steamwar.bungeecore.sql.TeamTeilnahme; import lombok.experimental.UtilityClass; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; +import net.dv8tion.jda.api.entities.Emoji; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.interactions.components.ActionRow; +import net.dv8tion.jda.api.interactions.components.Button; +import net.dv8tion.jda.api.interactions.components.ComponentLayout; +import net.dv8tion.jda.api.interactions.components.selections.SelectOption; +import net.dv8tion.jda.api.interactions.components.selections.SelectionMenu; import java.awt.*; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import java.util.stream.Collectors; @UtilityClass @@ -66,7 +75,12 @@ public class EventManager { embedBuilder.setAuthor("SteamWar", "https://www.steamwar.de"); Timestamp now = Timestamp.from(Instant.now()); - Event.getComing().forEach(event -> { + SelectionMenu.Builder menuBuilder = SelectionMenu.create("eventName"); + menuBuilder.setPlaceholder("Wähle ein Event aus!") + .setMinValues(1) + .setMaxValues(1); + List events = Event.getComing(); + events.forEach(event -> { StringBuilder st = new StringBuilder(); if (event.getDeadline().after(now)) { st.append("Deadline: \n"); @@ -77,10 +91,16 @@ public class EventManager { st.append("\nAngemeldete Teams: ").append(teilname); } embedBuilder.addField(event.getEventName(), st.toString(), false); + if(event.getDeadline().after(Timestamp.from(Instant.now()))) { + menuBuilder.addOption(event.getEventName(), event.getEventID() + "", "An " + event.getEventName() + " teilnehmen", Emoji.fromUnicode("U+1F4DD")); + } }); MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.setEmbeds(embedBuilder.build()); + if(!events.isEmpty()) { + messageBuilder.setActionRows(ActionRow.of(menuBuilder.build())); + } if (message == null) { message = textChannel.sendMessage(messageBuilder.build()).complete(); } else { diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java new file mode 100644 index 00000000..5c262936 --- /dev/null +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java @@ -0,0 +1,95 @@ +/* + This file is a part of the SteamWar software. + + Copyright (C) 2020 SteamWar.de-Serverteam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + */ + +package de.steamwar.bungeecore.bot.listeners; + +import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; +import de.steamwar.bungeecore.sql.Event; +import de.steamwar.bungeecore.sql.SteamwarUser; +import de.steamwar.bungeecore.sql.Team; +import de.steamwar.bungeecore.sql.TeamTeilnahme; +import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; +import net.dv8tion.jda.api.interactions.components.Component; +import org.jetbrains.annotations.NotNull; + +import java.time.Instant; + +public class DiscordEventListener extends BasicDiscordListener { + + + @Override + public void onSelectionMenu(@NotNull SelectionMenuEvent event) { + if(event.getChannel().getId().equals(SteamwarDiscordBotConfig.EVENTS_CHANNEL) && event.getComponentType() == Component.Type.SELECTION_MENU) { + if(event.getSelectedOptions().isEmpty()) { + event.deferReply(true).queue(); + return; + } + if(event.getSelectedOptions().get(0).getValue().matches("([0-9]+)")) { + SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong()); + if(user == null) { + event.reply("Du hast dein Minecraft nicht verknüpft").setEphemeral(true).queue(); + return; + } + + if(user.getTeam() == 0) { + event.reply("Du bist in keinem Team").setEphemeral(true).queue(); + return; + } + + if(user.isLeader()) { + event.reply("Du bist kein Leader in deinem Team").setEphemeral(true).queue(); + return; + } + + if(Event.get() != null) { + event.reply("Du kannst dich nicht während einem Event an einem Event anmelden").setEphemeral(true).queue(); + return; + } + + Event swEvent = Event.get( + Integer.decode( + event.getSelectedOptions() + .get(0) + .getValue() + ).intValue()); + if(swEvent == null){ + event.reply("Das Event gibt es nicht").setEphemeral(true).queue(); + return; + } + + if(Instant.now().isAfter(swEvent.getDeadline().toInstant())){ + event.reply("Du kannst dich nicht mehr an diesen Event anmelden").setEphemeral(true).queue(); + return; + } + + Team team = Team.get(user.getTeam()); + + if(TeamTeilnahme.nimmtTeil(team.getTeamId(), swEvent.getEventID())){ + TeamTeilnahme.notTeilnehmen(team.getTeamId(), swEvent.getEventID()); + event.reply("Dein Team **" + team.getTeamName() + "** nimmt nun nicht mehr an **" + swEvent.getEventName() + "** teil!").setEphemeral(true).queue(); + }else{ + TeamTeilnahme.teilnehmen(team.getTeamId(), swEvent.getEventID()); + event.reply("Dein Team **" + team.getTeamName() + "** nimmt nun an **" + swEvent.getEventName() + "** teil!").setEphemeral(true).queue(); + } + } else { + event.reply("Lefuq?").setEphemeral(true).queue(); + } + } + } +} From 21dd3e3e0cb8475961a3cf1976d92bcc22919e17 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Wed, 8 Sep 2021 00:57:53 +0200 Subject: [PATCH 14/41] House Keeping Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/bot/events/EventManager.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/events/EventManager.java b/src/de/steamwar/bungeecore/bot/events/EventManager.java index 506e8b7f..398f05d6 100644 --- a/src/de/steamwar/bungeecore/bot/events/EventManager.java +++ b/src/de/steamwar/bungeecore/bot/events/EventManager.java @@ -32,17 +32,12 @@ import net.dv8tion.jda.api.entities.Emoji; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.interactions.components.ActionRow; -import net.dv8tion.jda.api.interactions.components.Button; -import net.dv8tion.jda.api.interactions.components.ComponentLayout; -import net.dv8tion.jda.api.interactions.components.selections.SelectOption; import net.dv8tion.jda.api.interactions.components.selections.SelectionMenu; import java.awt.*; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; From 6490ce28488015f777c6aa431b7b844a0fe0e9ac Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Wed, 8 Sep 2021 13:51:42 +0200 Subject: [PATCH 15/41] Long DiscordId Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/bot/AuthManager.java | 2 +- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/AuthManager.java b/src/de/steamwar/bungeecore/bot/AuthManager.java index 7d8b005b..a2facf00 100644 --- a/src/de/steamwar/bungeecore/bot/AuthManager.java +++ b/src/de/steamwar/bungeecore/bot/AuthManager.java @@ -56,7 +56,7 @@ public class AuthManager { if (TOKENS.containsKey(code)) { Member member = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).retrieveMemberById(TOKENS.get(code).longValue()).complete(); if(member == null) return null; - user.setDiscordId(member.getId()); + user.setDiscordId(member.getIdLong()); MessageBuilder builder = new MessageBuilder(); builder.setContent(":white_check_mark: Dein Discord Konto wurde mit **" + user.getUserName() + "** verknüpft"); builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")), Button.danger("invalid", "Ich war das nicht"))); diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 67c35960..e09bbc8d 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -63,7 +63,7 @@ public class SteamwarUser { private static final Map usersByName = new HashMap<>(); private static final Map usersByUUID = new HashMap<>(); private static final Map usersById = new HashMap<>(); - private static final Map usersByDiscord = new HashMap<>(); + private static final Map usersByDiscord = new HashMap<>(); private static final InetAddress LIXFEL_DE; private static final String API_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static final JsonParser jsonParser = new JsonParser(); @@ -75,7 +75,7 @@ public class SteamwarUser { private int team; private boolean leader; private final Map punishments; - private String discordId; + private Long discordId; static { try { @@ -93,7 +93,7 @@ public class SteamwarUser { userGroup = UserGroup.getUsergroup(rs.getString("UserGroup")); team = rs.getInt("Team"); leader = rs.getBoolean("Leader"); - discordId = rs.getString("DiscordId"); + discordId = rs.getLong("DiscordId"); usersById.put(id, this); usersByName.put(userName.toLowerCase(), this); usersByUUID.put(uuid, this); @@ -178,8 +178,8 @@ public class SteamwarUser { } public static SteamwarUser get(Long discordId) { - if(usersByDiscord.containsKey(discordId.toString())) - return usersByDiscord.get(discordId.toString()); + if(usersByDiscord.containsKey(discordId)) + return usersByDiscord.get(discordId); return byDiscord.select(rs -> { if(rs.next()) return new SteamwarUser(rs); @@ -235,11 +235,11 @@ public class SteamwarUser { return punishments.getOrDefault(type, null); } - public String getDiscordId() { + public Long getDiscordId() { return discordId; } - public void setDiscordId(String discordId) { + public void setDiscordId(Long discordId) { usersByDiscord.remove(this.discordId); this.discordId = discordId; updateDiscord.update(discordId, id); From 96f54cf6df537cd99a912ca317a1c8597cc5351b Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Wed, 8 Sep 2021 19:40:59 +0200 Subject: [PATCH 16/41] Simplyfy Int Signed-off-by: Chaoscaot --- .../bungeecore/bot/listeners/DiscordEventListener.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java index 5c262936..a8a7cbe3 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java @@ -62,12 +62,7 @@ public class DiscordEventListener extends BasicDiscordListener { return; } - Event swEvent = Event.get( - Integer.decode( - event.getSelectedOptions() - .get(0) - .getValue() - ).intValue()); + Event swEvent = Event.get(Integer.decode(event.getSelectedOptions().get(0).getValue())); if(swEvent == null){ event.reply("Das Event gibt es nicht").setEphemeral(true).queue(); return; From 613b78688aa6baf82d948d7acd1b1d2fe710380f Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Wed, 8 Sep 2021 19:44:40 +0200 Subject: [PATCH 17/41] Add EventManager Update Signed-off-by: Chaoscaot --- .../bungeecore/bot/listeners/DiscordEventListener.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java index a8a7cbe3..da5ac0ca 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java @@ -20,6 +20,7 @@ package de.steamwar.bungeecore.bot.listeners; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; +import de.steamwar.bungeecore.bot.events.EventManager; import de.steamwar.bungeecore.sql.Event; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; @@ -82,6 +83,8 @@ public class DiscordEventListener extends BasicDiscordListener { TeamTeilnahme.teilnehmen(team.getTeamId(), swEvent.getEventID()); event.reply("Dein Team **" + team.getTeamName() + "** nimmt nun an **" + swEvent.getEventName() + "** teil!").setEphemeral(true).queue(); } + + EventManager.update(); } else { event.reply("Lefuq?").setEphemeral(true).queue(); } From ac2a952017885810c05a29403b828694db86b2c3 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Thu, 9 Sep 2021 21:04:56 +0200 Subject: [PATCH 18/41] Update Heap size of ListCommand --- .../bungeecore/bot/commands/ListCommand.java | 4 ++-- src/de/steamwar/bungeecore/commands/ListCommand.java | 12 ++++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/commands/ListCommand.java b/src/de/steamwar/bungeecore/bot/commands/ListCommand.java index 3b014f97..746bb026 100644 --- a/src/de/steamwar/bungeecore/bot/commands/ListCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/ListCommand.java @@ -32,10 +32,10 @@ public class ListCommand extends BasicDiscordCommand { @Override public void run(SlashCommandEvent event) { - de.steamwar.bungeecore.commands.ListCommand.updateCustomTablist(); + de.steamwar.bungeecore.commands.ListCommand.getCustomTablist(); EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle("List"); - de.steamwar.bungeecore.commands.ListCommand.getPlayerMap().forEach((s, proxiedPlayers) -> { + de.steamwar.bungeecore.commands.ListCommand.getCustomTablist().forEach((s, proxiedPlayers) -> { embedBuilder.addField(s, proxiedPlayers.stream().map(player -> "`" + player.getName() + "`").collect(Collectors.joining(", ")), true); }); event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue(); diff --git a/src/de/steamwar/bungeecore/commands/ListCommand.java b/src/de/steamwar/bungeecore/commands/ListCommand.java index b7a4a63d..cb2de64d 100644 --- a/src/de/steamwar/bungeecore/commands/ListCommand.java +++ b/src/de/steamwar/bungeecore/commands/ListCommand.java @@ -22,7 +22,6 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Subserver; -import lombok.Getter; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; @@ -40,12 +39,8 @@ public class ListCommand extends BasicCommand { super("list", ""); } - @Getter - private static final TreeMap> playerMap = new TreeMap<>(); - - public static synchronized void updateCustomTablist(){ - //Calculate server-player-map - playerMap.clear(); + public static synchronized TreeMap> getCustomTablist(){ + TreeMap> playerMap = new TreeMap<>(); for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { Server pserver = player.getServer(); if (pserver == null) //Happens temporarily @@ -62,11 +57,12 @@ public class ListCommand extends BasicCommand { } } playerMap.forEach((server, players) -> players.sort((proxiedPlayer, t1) -> proxiedPlayer.getName().compareToIgnoreCase(t1.getName()))); + return playerMap; } @Override public void execute(CommandSender commandSender, String[] strings) { - updateCustomTablist(); + TreeMap> playerMap = getCustomTablist(); for (String server : playerMap.navigableKeySet()) { if (server.equals("Bau")) { server = Message.parse("TABLIST_BAU", commandSender); From 689538f6c5153b6967f707811d0ead4a316f4d98 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Thu, 9 Sep 2021 21:30:48 +0200 Subject: [PATCH 19/41] Hotfix DiscordBot command integration --- src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index ba2ff108..8ff2dfc9 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -108,7 +108,7 @@ public class SteamwarDiscordBot { jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); - guild.retrieveCommands().queue(commands -> commands.forEach(command -> guild.deleteCommandById(command.getId()).queue())); + guild.retrieveCommands().complete().forEach(command -> guild.deleteCommandById(command.getId()).complete()); CommandListUpdateAction commands = jda.getGuildById(SteamwarDiscordBotConfig.GUILD).updateCommands(); addCommand(commands, new MuteCommand()); addCommand(commands, new BanCommand()); @@ -116,7 +116,7 @@ public class SteamwarDiscordBot { addCommand(commands, new TeamCommand()); addCommand(commands, new ListCommand()); addCommand(commands, new UnbanCommand()); - commands.queue(); + commands.complete(); }); } From 2d89d642886c5c47f92fac0bb51ac5ffd781dd36 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Fri, 10 Sep 2021 20:57:19 +0200 Subject: [PATCH 20/41] Hotfix DiscordEventListener --- .../steamwar/bungeecore/bot/listeners/DiscordEventListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java index da5ac0ca..a08f74d2 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/DiscordEventListener.java @@ -53,7 +53,7 @@ public class DiscordEventListener extends BasicDiscordListener { return; } - if(user.isLeader()) { + if(!user.isLeader()) { event.reply("Du bist kein Leader in deinem Team").setEphemeral(true).queue(); return; } From eb4aaaf4348132709354b59d0c2e684201f6953a Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 16 Sep 2021 13:10:00 +0200 Subject: [PATCH 21/41] New ErrorLogger implementation matching new SpigotCore implementation Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 1 - src/de/steamwar/bungeecore/ErrorLogger.java | 93 ++++++++------------- 2 files changed, 35 insertions(+), 59 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 7dee2cac..66093247 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -158,7 +158,6 @@ public class BungeeCore extends Plugin { @Override public void onDisable(){ - ErrorLogger.stop(); Statement.close(); try { SteamwarDiscordBot.instance().getJda().shutdownNow(); diff --git a/src/de/steamwar/bungeecore/ErrorLogger.java b/src/de/steamwar/bungeecore/ErrorLogger.java index 5f4ab534..23c00cfb 100644 --- a/src/de/steamwar/bungeecore/ErrorLogger.java +++ b/src/de/steamwar/bungeecore/ErrorLogger.java @@ -20,83 +20,47 @@ package de.steamwar.bungeecore; import de.steamwar.bungeecore.sql.SWException; -import net.md_5.bungee.api.ProxyServer; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import java.text.MessageFormat; -import java.util.logging.Filter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.logging.Logger; -public class ErrorLogger extends Handler implements Filter { - private static ErrorLogger instance; +public class ErrorLogger extends Handler { private int ddosRate = 0; ErrorLogger(){ - ProxyServer.getInstance().getLogger().addHandler(this); - ProxyServer.getInstance().getLogger().setFilter(this); - instance = this; - } - - static void stop(){ - ProxyServer.getInstance().getLogger().removeHandler(instance); + Logger.getLogger("").addHandler(this); } @Override - public boolean isLoggable(LogRecord record) { - if(record.getLevel() != Level.SEVERE) - return true; + public void publish(LogRecord logRecord) { + if(logRecord.getLevel().intValue() < Level.WARNING.intValue()) + return; - StringBuilder stacktrace = new StringBuilder(record.getSourceClassName() + "\n" + record.getSourceMethodName()); - Throwable thrown = record.getThrown(); - while(thrown != null){ - stacktrace.append("\nCaused by ").append(thrown.getMessage()); + String message = MessageFormat.format(logRecord.getMessage(), logRecord.getParameters()); + for(String reason : ignoreContains) + if(message.contains(reason)) + return; - for(StackTraceElement ste : thrown.getStackTrace()) - stacktrace.append("\n").append(ste.toString()); - - thrown = thrown.getCause(); - } - - String stacktraceString = stacktrace.toString(); - if(stacktraceString.contains("Cannot request protocol")){ - ddosRate++; - if(ddosRate % 1000 == 0){ + ByteArrayOutputStream stacktraceOutput = new ByteArrayOutputStream(); + if(logRecord.getThrown() != null) + logRecord.getThrown().printStackTrace(new PrintStream(stacktraceOutput)); + String stacktrace = stacktraceOutput.toString(); + if(stacktrace.contains("Cannot request protocol")) { + if(++ddosRate % 1000 == 0) { SWException.log("Bungee", "DDOS", ddosRate + ""); } - return false; - } - return true; - } - - @Override - public void publish(LogRecord record) { - if(record.getLevel() != Level.SEVERE && record.getLevel() != Level.WARNING) return; - - StringBuilder stacktrace = new StringBuilder(record.getSourceClassName() + "\n" + record.getSourceMethodName()); - Throwable thrown = record.getThrown(); - while(thrown != null){ - stacktrace.append("\nCaused by ").append(thrown.getMessage()); - - for(StackTraceElement ste : thrown.getStackTrace()) - stacktrace.append("\n").append(ste.toString()); - - thrown = thrown.getCause(); } - String stacktraceString = stacktrace.toString(); - String message = MessageFormat.format(record.getMessage(), record.getParameters()); - - if(message.contains("ServerConnector") - || message.contains("InitialHandler") - || message.contains("UpstreamBridge") - || message.contains("DownstreamBridge") - || message.contains(" took ") - || message.contains("No client connected for pending server!")) - return; - - SWException.log("Bungee", message, stacktraceString); + SWException.log("Bungee", message, stacktrace); } @Override @@ -108,4 +72,17 @@ public class ErrorLogger extends Handler implements Filter { public void close() { //ignored } + + private static final List ignoreContains; + + static { + List contains = new ArrayList<>(); + contains.add("ServerConnector"); + contains.add("InitialHandler"); + contains.add("UpstreamBridge"); + contains.add("DownstreamBridge"); + contains.add(" took "); + contains.add("No client connected for pending server!"); + ignoreContains = Collections.unmodifiableList(contains); + } } From 85fe4ba2640090b48727dc71dd417923fdbaea84 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 16 Sep 2021 16:45:47 +0200 Subject: [PATCH 22/41] Object oriented subserver node system Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 15 +- .../steamwar/bungeecore/LoadEvaluation.java | 96 ------- src/de/steamwar/bungeecore/Node.java | 235 ++++++++++++++++++ .../steamwar/bungeecore/SubserverSystem.java | 155 ++---------- .../bungeecore/commands/BauCommand.java | 2 +- .../bungeecore/commands/StatCommand.java | 32 +-- .../steamwar/messages/BungeeCore.properties | 3 +- 7 files changed, 280 insertions(+), 258 deletions(-) delete mode 100644 src/de/steamwar/bungeecore/LoadEvaluation.java create mode 100644 src/de/steamwar/bungeecore/Node.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 7dee2cac..c3bf9943 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -89,9 +89,10 @@ public class BungeeCore extends Plugin { new WorldDownloader(); new BrandListener(); - commands.put("/b", null); - commands.put("/gs", null); - commands.put("/bau", null); + new Node.LocalNode(); + new Node.RemoteNode("lx", 8); + new Node.RemoteNode("az", 10); + commands.put("/tp", null); commands.put("/bc", null); commands.put("/bauchat", null); @@ -158,14 +159,14 @@ public class BungeeCore extends Plugin { @Override public void onDisable(){ - ErrorLogger.stop(); - Statement.close(); try { SteamwarDiscordBot.instance().getJda().shutdownNow(); SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); - } catch (Exception e) { - // Ignored + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } + ErrorLogger.stop(); + Statement.close(); } public static BungeeCore get() { diff --git a/src/de/steamwar/bungeecore/LoadEvaluation.java b/src/de/steamwar/bungeecore/LoadEvaluation.java deleted file mode 100644 index 59fda6c2..00000000 --- a/src/de/steamwar/bungeecore/LoadEvaluation.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * This file is a part of the SteamWar software. - * - * Copyright (C) 2021 SteamWar.de-Serverteam - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -package de.steamwar.bungeecore; - -import java.io.*; - -public class LoadEvaluation { - private LoadEvaluation(){} - - private static final File meminfo = new File("/proc/meminfo"); - - public static double getRamPercentage() { - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(meminfo)))) { - String memTotal = bufferedReader.readLine().replaceAll(" +", " "); - bufferedReader.readLine(); - String memAvailable = bufferedReader.readLine().replaceAll(" +", " "); - - long memTotalLong = getNumber(memTotal); - long memAvailableLong = getNumber(memAvailable); - return (memTotalLong - memAvailableLong) / (double) memTotalLong; - } catch (IOException e) { - return 1D; - } - } - - public static double getRemoteRamPercentage(String remote) { - try { - // Attention: - // memInfo.sh needs to contain: cat /proc/meminfo - Process process = new ProcessBuilder("ssh", remote, "\"./memInfo.sh\"").start(); - process.waitFor(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); - String memTotal = bufferedReader.readLine().replaceAll(" +", " "); - bufferedReader.readLine(); - String memAvailable = bufferedReader.readLine().replaceAll(" +", " "); - - long memTotalLong = getNumber(memTotal); - long memAvailableLong = getNumber(memAvailable); - return (memTotalLong - memAvailableLong) / (double) memTotalLong; - } catch (IOException e) { - return 1D; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return 1D; - } - } - - public static double getCPULoad() { - try { - Process process = new ProcessBuilder("bash", "-c", "cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS=\"\" '{printf \"%.2f\\n\", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'").start(); - process.waitFor(); - return Double.parseDouble(new BufferedReader(new InputStreamReader(process.getInputStream())).readLine()) / 100.0; - } catch (IOException e) { - return 1D; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return 1D; - } - } - - public static double getRemoteCPULoad(String remote) { - try { - // Attention: - // cpuLoad.sh needs to contain: cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%.2f\n", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}' - Process process = new ProcessBuilder("ssh", remote, "\"./cpuLoad.sh\"").start(); - process.waitFor(); - return Double.parseDouble(new BufferedReader(new InputStreamReader(process.getInputStream())).readLine()) / 100.0; - } catch (IOException e) { - return 1D; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return 1D; - } - } - - private static long getNumber(String s) { - return Long.parseLong(s.split(" ")[1]); - } -} diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java new file mode 100644 index 00000000..5edcd067 --- /dev/null +++ b/src/de/steamwar/bungeecore/Node.java @@ -0,0 +1,235 @@ +/* + This file is a part of the SteamWar software. + + Copyright (C) 2020 SteamWar.de-Serverteam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package de.steamwar.bungeecore; + +import net.md_5.bungee.api.ProxyServer; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.logging.Level; + +public abstract class Node { + + private static final List JVM_ARGS = Arrays.asList("-Dlog4j.configurationFile=log4j2.xml", "-server", "-Xms128M", "-XX:+UseCompressedOops", "-XX:+TieredCompilation", "-XX:TargetSurvivorRatio=90", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=15", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseBiasedLocking", "-XX:UseSSE=3", "-XX:+UseCodeCacheFlushing", "-XX:+UseThreadPriorities", "-XX:+AggressiveOpts", "-XX:+ReduceSignalUsage", "-XX:+UseInterpreter", "-XX:+UseSharedSpaces", "-XX:AllocatePrefetchStyle=1", "-XX:+AlwaysCompileLoopMethods", "-XX:+UseConcMarkSweepGC", "-XX:+RewriteFrequentPairs", "-XX:+OptimizeStringConcat", "-XX:+CMSCleanOnEnter", "-XX:+UseInlineCaches"); + private static final List JVM8_ARGS = Arrays.asList("-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); + + private static final List nodes = new ArrayList<>(); + public static Node local = null; + + public static Node getNode() { + Node node = null; + double minLoad = Double.POSITIVE_INFINITY; + synchronized (nodes) { + Iterator it = nodes.iterator(); + while(it.hasNext()) { + Node n = it.next(); + double load = n.getLoad(); + if (load < minLoad) { + minLoad = load; + node = n; + } else if (load == Double.POSITIVE_INFINITY) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Removing " + n.getName() + " due to infinite load!"); + it.remove(); + } + } + } + return node; + } + + public static void forEach(Consumer consumer) { + synchronized (nodes) { + nodes.forEach(consumer); + } + } + + protected Node() { + synchronized (nodes) { + nodes.add(this); + } + } + + public abstract ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams); + public abstract void execute(String... command); + public abstract String getName(); + public abstract double getLoad(); + + protected void constructServerstart(List cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) { + boolean jdk11 = serverJar.contains("1.15.2"); + + if(jdk11) + cmd.add("/usr/lib/jvm/java-11-openjdk-amd64/bin/java"); + else + cmd.add("java"); + + for(String param : dParams){ + cmd.add("-D" + param); + } + cmd.add("-Xmx" + xmx); + cmd.addAll(JVM_ARGS); + if(!jdk11) + cmd.addAll(JVM8_ARGS); + cmd.add("-jar"); + cmd.add("/binarys/" + serverJar); + cmd.add("--log-strip-color"); + cmd.add("--world-dir"); + cmd.add(worldDir); + cmd.add("--level-name"); + cmd.add(levelName); + cmd.add("--port"); + cmd.add(String.valueOf(port)); + cmd.add("nogui"); + } + + protected void execute(ProcessBuilder builder) { + try { + builder.start().waitFor(); + } catch (IOException e) { + throw new SecurityException("Could not execute command", e); + } catch (InterruptedException e) { + ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted during execution", e); + Thread.currentThread().interrupt(); + } + } + + public static class LocalNode extends Node { + private static final File meminfo = new File("/proc/meminfo"); + private static final File loadavg = new File("/proc/loadavg"); + + private final int cores; + + public LocalNode() { + super(); + this.cores = Runtime.getRuntime().availableProcessors(); + local = this; + } + + @Override + public ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams) { + List cmd = new ArrayList<>(); + constructServerstart(cmd, serverJar, worldDir, levelName, port, xmx, dParams); + ProcessBuilder builder = new ProcessBuilder(cmd); + builder.directory(directory); + return builder; + } + + @Override + public void execute(String... command) { + execute(new ProcessBuilder(command)); + } + + @Override + public String getName() { + return "local"; + } + + @Override + public double getLoad() { + double totalMem; + double freeMem; + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(meminfo)))) { + totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); + bufferedReader.readLine(); + freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); + } catch (IOException e) { + throw new SecurityException("Could not read local memory", e); + } + + double cpuLoad; + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(loadavg)))) { + cpuLoad = Double.parseDouble(bufferedReader.readLine().split(" ")[0]); + } catch (IOException e) { + throw new SecurityException("Could not read local cpu", e); + } + + return cpuLoad / cores + (totalMem - freeMem) / totalMem; + } + } + + public static class RemoteNode extends Node { + private final int cores; + private final String remote; + + public RemoteNode(String remote, int cores) { + super(); + this.cores = cores; + this.remote = remote; + } + + @Override + public ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams) { + List cmd = new ArrayList<>(); + cmd.add("ssh"); + cmd.add("-L"); + cmd.add(port + ":localhost:" + port); + cmd.add(remote); + cmd.add("cd"); + cmd.add(directory.getPath()); + cmd.add(";"); + constructServerstart(cmd, serverJar, worldDir, levelName, port, xmx, dParams); + return new ProcessBuilder(cmd); + } + + @Override + public void execute(String... command) { + List cmd = new ArrayList<>(); + cmd.add("ssh"); + cmd.add(remote); + cmd.addAll(Arrays.asList(command)); + execute(new ProcessBuilder(cmd)); + } + + @Override + public String getName() { + return remote; + } + + @Override + public double getLoad() { + Process process; + try { + process = new ProcessBuilder("ssh", remote, "cat /proc/loadavg;cat /proc/meminfo").start(); + if(!process.waitFor(1, TimeUnit.SECONDS)) + return Double.POSITIVE_INFINITY; + } catch (IOException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could starting process to read load", e); + return Double.POSITIVE_INFINITY; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return Double.POSITIVE_INFINITY; + } + + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + double cpuLoad = Double.parseDouble(bufferedReader.readLine().split(" ")[0]); + double totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); + bufferedReader.readLine(); + double freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); + return cpuLoad / cores + (totalMem - freeMem) / totalMem; + } catch (IOException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could read load", e); + return Double.POSITIVE_INFINITY; + } + } + } +} diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index d5e85b03..018c8a33 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -27,18 +27,14 @@ import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.connection.ProxiedPlayer; import java.io.File; -import java.io.IOException; import java.net.InetSocketAddress; import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.logging.Level; +import java.util.UUID; public class SubserverSystem { private SubserverSystem(){} - private static final String BACKBONE = "/home/minecraft/backbone/"; - private static final List JVM_ARGS = Arrays.asList("-Dlog4j.configurationFile=log4j2.xml", "-server", "-Xms128M", "-XX:+UseCompressedOops", "-XX:+TieredCompilation", "-XX:TargetSurvivorRatio=90", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=15", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseBiasedLocking", "-XX:UseSSE=3", "-XX:+UseCodeCacheFlushing", "-XX:+UseThreadPriorities", "-XX:+AggressiveOpts", "-XX:+ReduceSignalUsage", "-XX:+UseInterpreter", "-XX:+UseSharedSpaces", "-XX:AllocatePrefetchStyle=1", "-XX:+AlwaysCompileLoopMethods", "-XX:+UseConcMarkSweepGC", "-XX:+RewriteFrequentPairs", "-XX:+OptimizeStringConcat", "-XX:+CMSCleanOnEnter", "-XX:+UseInlineCaches"); - private static final List JVM8_ARGS = Arrays.asList("-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); + private static final String BACKBONE = "/home/minecraft/"; private static final String ARENA_PATH = BACKBONE + "arenaserver/"; private static final String SERVER_PATH = BACKBONE + "server/"; private static final String EVENT_PATH = BACKBONE + "event/"; @@ -91,6 +87,7 @@ public class SubserverSystem { */ public static synchronized Subserver startArena(ArenaMode modus, String map, int eventFightID, int checkSchemID, int prepareSchemID, String serverName, String mapName, UUID player1, UUID player2, boolean ranked){ //Generate missing parameters + Node node = eventFightID > 0 ? Node.local : Node.getNode(); int port = freePort(FIRST_ARENA_PORT); if(serverName == null){ @@ -109,56 +106,31 @@ public class SubserverSystem { worldDir = ARENA_PATH; //Copy world - try { - new ProcessBuilder("cp", "-r", SERVER_PATH + modus.getFolder() + "/arenas/" + map, worldDir + mapName).start().waitFor(); - } catch (IOException e) { - throw new SecurityException("Could not copy folder", e); - } catch (InterruptedException e) { - ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted while copying folder", e); - Thread.currentThread().interrupt(); - } + node.execute("cp", "-r", SERVER_PATH + modus.getFolder() + "/arenas/" + map, worldDir + mapName); File directory = new File(SERVER_PATH, modus.getFolder()); - List cmd = serverStartCommand( - modus.serverJar(), - directory, - worldDir, - mapName, - port, - "2G", - "logPath=" + mapName, - "config="+modus.getConfig(), - "fightID=" + eventFightID, - "ranked=" + ranked, - "checkSchemID=" + checkSchemID, - "prepareSchemID=" + prepareSchemID, + ProcessBuilder builder = node.startServer( + modus.serverJar(), directory, worldDir, mapName, port, "2G", + "logPath=" + mapName, "config=" + modus.getConfig(), + "fightID=" + eventFightID, "ranked=" + ranked, + "checkSchemID=" + checkSchemID, "prepareSchemID=" + prepareSchemID, player1 != null && eventFightID != -1 ? "blueLeader=" + player1 : null, - player2 != null ? "redLeader=" + player2 : null); - - //Start server - ProcessBuilder process = new ProcessBuilder(cmd); - process.directory(directory); + player2 != null ? "redLeader=" + player2 : null + ); String finalMapName = mapName; if(eventFightID == -1) - return new Bauserver(serverName, player1, port, process, () -> deleteFolder(ARENA_PATH + finalMapName)); + return new Bauserver(serverName, player1, port, builder, () -> deleteFolder(node, ARENA_PATH + finalMapName)); else - return new Subserver(Servertype.ARENA, serverName, port, process, () -> { + return new Subserver(Servertype.ARENA, serverName, port, builder, () -> { if(eventFightID > 0) return; - deleteFolder(ARENA_PATH + finalMapName); + deleteFolder(node, ARENA_PATH + finalMapName); }); } - public static void deleteFolder(String worldName){ - try { - new ProcessBuilder("rm", "-r", worldName).start().waitFor(); - } catch (IOException e) { - throw new SecurityException("Could not clean up folder", e); - } catch (InterruptedException e) { - ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted while deleting folder", e); - Thread.currentThread().interrupt(); - } + public static void deleteFolder(Node node, String worldName){ + node.execute("rm", "-r", worldName); } public static Subserver startEventArena(EventFight eventFight, String serverName){ @@ -183,25 +155,15 @@ public class SubserverSystem { if(bauRunning(p, owner)) return; + copyBauweltIfRequired(prototype, worldFolder + worldName); SteamwarUser user = SteamwarUser.get(owner); - copyBauweltIfRequired(p, prototype, worldFolder + worldName); + File directory = new File(SERVER_PATH, serverName); + Node node = Node.getNode(); int port = freePort(4000); - File directory = new File(SERVER_PATH, serverName); - List cmd = serverStartCommand( - serverJar, - directory, - worldDir, - worldName, - port, - xmx, - "logPath=" + worldName); - - //Start server - ProcessBuilder process = new ProcessBuilder(cmd); - process.directory(directory); - - new Bauserver(user.getUserName() + "s Bau", owner, port, process, () -> {}).sendPlayer(p); + new Bauserver(user.getUserName() + "s Bau", owner, port, node.startServer( + serverJar, directory, worldDir, worldName, port, xmx, "logPath=" + worldName + ), () -> {}).sendPlayer(p); } public static void sendToBauServer(ProxiedPlayer p, UUID owner){ @@ -235,63 +197,6 @@ public class SubserverSystem { new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.getName())); } - private static List serverStartCommand(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams){ - List cmd = new ArrayList<>(); - boolean jdk11 = serverJar.contains("1.15.2"); - - boolean fallback = false; - if (!steamwarStartAvailable()) { - cmd.add("ssh"); - cmd.add("-L"); - cmd.add(port + ":localhost:" + port); - if (remoteStartAvailable("lx")) { - cmd.add("lx"); - } else if (remoteStartAvailable("az")) { - cmd.add("az"); - } else { - fallback = true; - } - cmd.add("cd"); - cmd.add(directory.getPath()); - cmd.add(";"); - } - if (fallback) { - cmd.clear(); - } - - if(jdk11) - cmd.add("/usr/lib/jvm/java-11-openjdk-amd64/bin/java"); - else - cmd.add("java"); - - for(String param : dParams){ - cmd.add("-D" + param); - } - cmd.add("-Xmx" + xmx); - cmd.addAll(JVM_ARGS); - if(!jdk11) - cmd.addAll(JVM8_ARGS); - cmd.add("-jar"); - cmd.add("/binarys/" + serverJar); - cmd.add("--log-strip-color"); - cmd.add("--world-dir"); - cmd.add(worldDir); - cmd.add("--level-name"); - cmd.add(levelName); - cmd.add("--port"); - cmd.add(String.valueOf(port)); - - return cmd; - } - - private static boolean steamwarStartAvailable(){ - return LoadEvaluation.getCPULoad() < 0.7 && LoadEvaluation.getRamPercentage() < 0.8; - } - - private static boolean remoteStartAvailable(String remote) { - return LoadEvaluation.getRemoteCPULoad(remote) < 0.7 && LoadEvaluation.getRemoteRamPercentage(remote) < 0.8; - } - private static boolean bauRunning(ProxiedPlayer p, UUID owner){ for(Subserver subserver : Subserver.getServerList()){ if(subserver.getType() == Servertype.BAUSERVER && ((Bauserver)subserver).getOwner().equals(owner)){ @@ -302,20 +207,10 @@ public class SubserverSystem { return false; } - private static void copyBauweltIfRequired(ProxiedPlayer p, String sourcePath, String targetPath){ + private static void copyBauweltIfRequired(String sourcePath, String targetPath){ File w = new File(targetPath); - if (!w.exists() || !w.isDirectory()){ - try { - new ProcessBuilder("cp", "-r", sourcePath, targetPath).start().waitFor(); - } catch (IOException e) { - Message.send("SERVER_WORLD_ERROR", p); - throw new SecurityException("Could not create Bauwelt", e); - } catch (InterruptedException e){ - BungeeCore.log("Could not create Bauwelt", e); - Message.send("SERVER_WORLD_ERROR", p); - Thread.currentThread().interrupt(); - } - } + if (!w.exists() || !w.isDirectory()) + Node.local.execute("cp", "-r", sourcePath, targetPath); } private static int freePort(int start){ diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index e8274273..2965f08a 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -257,7 +257,7 @@ public class BauCommand extends BasicCommand { break; } } - SubserverSystem.deleteFolder(world); + SubserverSystem.deleteFolder(Node.local, world); }); } diff --git a/src/de/steamwar/bungeecore/commands/StatCommand.java b/src/de/steamwar/bungeecore/commands/StatCommand.java index 1488dbfa..ade3705f 100644 --- a/src/de/steamwar/bungeecore/commands/StatCommand.java +++ b/src/de/steamwar/bungeecore/commands/StatCommand.java @@ -19,8 +19,8 @@ package de.steamwar.bungeecore.commands; -import de.steamwar.bungeecore.LoadEvaluation; import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.Node; import net.md_5.bungee.api.CommandSender; import java.io.BufferedReader; @@ -36,34 +36,22 @@ public class StatCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { + Map serverCount = new HashMap<>(); try { Process process = new ProcessBuilder("ps", "x").start(); - process.waitFor(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); - Map serverCounts = new HashMap<>(); - bufferedReader.lines().forEach(s -> { - if (!s.contains("--port")) { + new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(s -> { + if (s.contains("--port")) return; - } - String server = "SW"; - if (s.contains("ssh -L")) { - server = s.substring(s.indexOf("ssh -L") + 6).split(" ")[2]; - } - serverCounts.put(server, serverCounts.computeIfAbsent(server, s1 -> 0) + 1); + serverCount.compute( + s.contains("ssh -L") ? s.substring(s.indexOf("ssh -L") + 6).split(" ")[2] : "local", + (server, count) -> (count != null ? count : 0) + 1 + ); }); - serverCounts.forEach((s, integer) -> { - if (s.equals("SW")) { - Message.send("STAT_SERVER", sender, s, LoadEvaluation.getRamPercentage(), LoadEvaluation.getCPULoad(), integer); - } else { - Message.send("STAT_SERVER", sender, s.toUpperCase(), LoadEvaluation.getRemoteRamPercentage(s), LoadEvaluation.getRemoteCPULoad(s), integer); - } - }); - if (serverCounts.isEmpty()) { - Message.send("NO_STATS", sender); - } } catch (Exception e) { throw new SecurityException(e.getMessage(), e); } + + Node.forEach(node -> Message.send("STAT_SERVER", sender, node.getName(), node.getLoad(), serverCount.getOrDefault(node.getName(), 0))); } } diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 31cb6cca..5d32af1e 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -107,8 +107,7 @@ MOD_YELLOW_PLUR=§7Deaktiviere die Mods\n§e{0}\n§7um weiter auf §eSteam§8War #Various commands ALERT=§f{0} -STAT_SERVER=§7Server §f{0} - §7Ram §f{1} §7CPU §f{2} §7Server Count §f{3} -NO_STATS=§7Kein Bau oder Fight Server gestartet +STAT_SERVER=§7Server §e{0}§8: §7Load §e{1} §7Serveranzahl §e{2} #Ban&Mute-Command BAN_TEAM_BANNED={0} §c{1} wurde von {2} {3} gebannt. §f§lGrund: §f{4} From d73c0ea7eae763392f86a63db4393bc471724c1d Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 16 Sep 2021 17:12:22 +0200 Subject: [PATCH 23/41] Auto core count detection Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 4 ++-- src/de/steamwar/bungeecore/Node.java | 28 ++++++++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index c3bf9943..e4380001 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -90,8 +90,8 @@ public class BungeeCore extends Plugin { new BrandListener(); new Node.LocalNode(); - new Node.RemoteNode("lx", 8); - new Node.RemoteNode("az", 10); + new Node.RemoteNode("lx"); + new Node.RemoteNode("az"); commands.put("/tp", null); commands.put("/bc", null); diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index 5edcd067..cb349863 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -171,10 +171,34 @@ public abstract class Node { private final int cores; private final String remote; - public RemoteNode(String remote, int cores) { + public RemoteNode(String remote) { super(); - this.cores = cores; this.remote = remote; + + //Determin core count + Process process; + try { + process = new ProcessBuilder("ssh", remote, "nproc").start(); + if(!process.waitFor(5, TimeUnit.SECONDS)) + throw new IOException("Timeout of " + remote + " on init"); + } catch (IOException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not initialize " + remote); + cores = 1; + return; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + cores = 1; + return; + } + + int c; + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + c = Integer.parseInt(bufferedReader.readLine()); + } catch (IOException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); + c = 1; + } + cores = c; } @Override From d41bb58fac07425676ea44118505b2db85dd4703 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Thu, 16 Sep 2021 22:21:36 +0200 Subject: [PATCH 24/41] Fix null Issues Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/bot/AuthManager.java | 1 - src/de/steamwar/bungeecore/sql/SteamwarUser.java | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/AuthManager.java b/src/de/steamwar/bungeecore/bot/AuthManager.java index a2facf00..ac4f5539 100644 --- a/src/de/steamwar/bungeecore/bot/AuthManager.java +++ b/src/de/steamwar/bungeecore/bot/AuthManager.java @@ -27,7 +27,6 @@ import net.dv8tion.jda.api.entities.Emoji; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.Button; -import net.md_5.bungee.api.scheduler.ScheduledTask; import java.util.*; import java.util.concurrent.TimeUnit; diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index e09bbc8d..2643d62b 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -94,11 +94,15 @@ public class SteamwarUser { team = rs.getInt("Team"); leader = rs.getBoolean("Leader"); discordId = rs.getLong("DiscordId"); + if(rs.wasNull()) { + discordId = null; + } usersById.put(id, this); usersByName.put(userName.toLowerCase(), this); usersByUUID.put(uuid, this); - if(discordId != null) + if(discordId != null) { usersByDiscord.put(discordId, this); + } punishments = Punishment.getPunishmentsOfPlayer(id); } From 265fa45371c9c209fc27d2ff658a25aa20f35b22 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 17 Sep 2021 07:56:26 +0200 Subject: [PATCH 25/41] Prefer local node Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index cb349863..f0afc097 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -39,8 +39,11 @@ public abstract class Node { public static Node local = null; public static Node getNode() { - Node node = null; - double minLoad = Double.POSITIVE_INFINITY; + Node node = local; + double minLoad = local.getLoad(); + if(minLoad < 0.5) + return local; + synchronized (nodes) { Iterator it = nodes.iterator(); while(it.hasNext()) { @@ -59,17 +62,12 @@ public abstract class Node { } public static void forEach(Consumer consumer) { + consumer.accept(local); synchronized (nodes) { nodes.forEach(consumer); } } - protected Node() { - synchronized (nodes) { - nodes.add(this); - } - } - public abstract ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams); public abstract void execute(String... command); public abstract String getName(); @@ -120,7 +118,6 @@ public abstract class Node { private final int cores; public LocalNode() { - super(); this.cores = Runtime.getRuntime().availableProcessors(); local = this; } @@ -172,7 +169,6 @@ public abstract class Node { private final String remote; public RemoteNode(String remote) { - super(); this.remote = remote; //Determin core count @@ -199,6 +195,10 @@ public abstract class Node { c = 1; } cores = c; + + synchronized (nodes) { + nodes.add(this); + } } @Override From a8d62d6115c5249261962c14ca1de0d54b345081 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 17 Sep 2021 07:58:10 +0200 Subject: [PATCH 26/41] Fix inversion + debugoutput Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 1 + src/de/steamwar/bungeecore/commands/StatCommand.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index f0afc097..d63093d0 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -195,6 +195,7 @@ public abstract class Node { c = 1; } cores = c; + BungeeCore.get().getLogger().log(Level.INFO, "Adding node " + remote + " with " + cores + " cores."); synchronized (nodes) { nodes.add(this); diff --git a/src/de/steamwar/bungeecore/commands/StatCommand.java b/src/de/steamwar/bungeecore/commands/StatCommand.java index ade3705f..b633fb51 100644 --- a/src/de/steamwar/bungeecore/commands/StatCommand.java +++ b/src/de/steamwar/bungeecore/commands/StatCommand.java @@ -40,7 +40,7 @@ public class StatCommand extends BasicCommand { try { Process process = new ProcessBuilder("ps", "x").start(); new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(s -> { - if (s.contains("--port")) + if (!s.contains("--port")) return; serverCount.compute( s.contains("ssh -L") ? s.substring(s.indexOf("ssh -L") + 6).split(" ")[2] : "local", From 74df8a82a341f3bbdd1b5421a56c0c26209c1280 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 17 Sep 2021 08:45:47 +0200 Subject: [PATCH 27/41] Memory threshold Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index d63093d0..5336491f 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -34,6 +34,7 @@ public abstract class Node { private static final List JVM_ARGS = Arrays.asList("-Dlog4j.configurationFile=log4j2.xml", "-server", "-Xms128M", "-XX:+UseCompressedOops", "-XX:+TieredCompilation", "-XX:TargetSurvivorRatio=90", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=15", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseBiasedLocking", "-XX:UseSSE=3", "-XX:+UseCodeCacheFlushing", "-XX:+UseThreadPriorities", "-XX:+AggressiveOpts", "-XX:+ReduceSignalUsage", "-XX:+UseInterpreter", "-XX:+UseSharedSpaces", "-XX:AllocatePrefetchStyle=1", "-XX:+AlwaysCompileLoopMethods", "-XX:+UseConcMarkSweepGC", "-XX:+RewriteFrequentPairs", "-XX:+OptimizeStringConcat", "-XX:+CMSCleanOnEnter", "-XX:+UseInlineCaches"); private static final List JVM8_ARGS = Arrays.asList("-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); + private static final long minFreeMem = 4L * 1024 * 1024; // 4 GB private static final List nodes = new ArrayList<>(); public static Node local = null; @@ -160,7 +161,7 @@ public abstract class Node { throw new SecurityException("Could not read local cpu", e); } - return cpuLoad / cores + (totalMem - freeMem) / totalMem; + return cpuLoad / cores + freeMem > minFreeMem ? 0 : ((totalMem - freeMem) / totalMem); } } @@ -250,7 +251,7 @@ public abstract class Node { double totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); bufferedReader.readLine(); double freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); - return cpuLoad / cores + (totalMem - freeMem) / totalMem; + return cpuLoad / cores + freeMem > minFreeMem ? 0 : ((totalMem - freeMem) / totalMem); } catch (IOException e) { BungeeCore.get().getLogger().log(Level.SEVERE, "Could read load", e); return Double.POSITIVE_INFINITY; From 45cc55c4a19d0ca161b8a0123ae1a56961306b81 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 17 Sep 2021 08:48:57 +0200 Subject: [PATCH 28/41] Memory threshold Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index 5336491f..ea0a2eda 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -34,7 +34,7 @@ public abstract class Node { private static final List JVM_ARGS = Arrays.asList("-Dlog4j.configurationFile=log4j2.xml", "-server", "-Xms128M", "-XX:+UseCompressedOops", "-XX:+TieredCompilation", "-XX:TargetSurvivorRatio=90", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=15", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseBiasedLocking", "-XX:UseSSE=3", "-XX:+UseCodeCacheFlushing", "-XX:+UseThreadPriorities", "-XX:+AggressiveOpts", "-XX:+ReduceSignalUsage", "-XX:+UseInterpreter", "-XX:+UseSharedSpaces", "-XX:AllocatePrefetchStyle=1", "-XX:+AlwaysCompileLoopMethods", "-XX:+UseConcMarkSweepGC", "-XX:+RewriteFrequentPairs", "-XX:+OptimizeStringConcat", "-XX:+CMSCleanOnEnter", "-XX:+UseInlineCaches"); private static final List JVM8_ARGS = Arrays.asList("-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); - private static final long minFreeMem = 4L * 1024 * 1024; // 4 GB + private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB private static final List nodes = new ArrayList<>(); public static Node local = null; @@ -161,7 +161,7 @@ public abstract class Node { throw new SecurityException("Could not read local cpu", e); } - return cpuLoad / cores + freeMem > minFreeMem ? 0 : ((totalMem - freeMem) / totalMem); + return cpuLoad / cores + (freeMem > MIN_FREE_MEM ? 0 : ((totalMem - freeMem) / totalMem)); } } @@ -251,7 +251,7 @@ public abstract class Node { double totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); bufferedReader.readLine(); double freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]); - return cpuLoad / cores + freeMem > minFreeMem ? 0 : ((totalMem - freeMem) / totalMem); + return cpuLoad / cores + (freeMem > MIN_FREE_MEM ? 0 : ((totalMem - freeMem) / totalMem)); } catch (IOException e) { BungeeCore.get().getLogger().log(Level.SEVERE, "Could read load", e); return Double.POSITIVE_INFINITY; From 2b2fc2b00ea05f0428e5e86badfd67d411e4a7c2 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 19 Sep 2021 16:41:42 +0200 Subject: [PATCH 29/41] Fix deadlock Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ErrorLogger.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/ErrorLogger.java b/src/de/steamwar/bungeecore/ErrorLogger.java index 23c00cfb..8e357eb6 100644 --- a/src/de/steamwar/bungeecore/ErrorLogger.java +++ b/src/de/steamwar/bungeecore/ErrorLogger.java @@ -60,7 +60,11 @@ public class ErrorLogger extends Handler { return; } - SWException.log("Bungee", message, stacktrace); + try { + SWException.log("Bungee", message, stacktrace); + } catch (SecurityException e) { + // HELL NO! This results in a deadlock! + } } @Override From 49f7dc991152a4cc8da22801434a0ecde9624f15 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 21 Sep 2021 19:05:28 +0200 Subject: [PATCH 30/41] Fix deadlock #2 :/ Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ErrorLogger.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/ErrorLogger.java b/src/de/steamwar/bungeecore/ErrorLogger.java index 8e357eb6..e20a7047 100644 --- a/src/de/steamwar/bungeecore/ErrorLogger.java +++ b/src/de/steamwar/bungeecore/ErrorLogger.java @@ -58,13 +58,12 @@ public class ErrorLogger extends Handler { SWException.log("Bungee", "DDOS", ddosRate + ""); } return; + } else if (stacktrace.contains("ErrorLogger")) { + return; } - try { - SWException.log("Bungee", message, stacktrace); - } catch (SecurityException e) { - // HELL NO! This results in a deadlock! - } + + SWException.log("Bungee", message, stacktrace); } @Override From f8d6b73c0f28ea9daeaeeeb4e3ff4fd6864a4655 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 26 Sep 2021 21:46:35 +0200 Subject: [PATCH 31/41] Fix deadlock #3 :/ Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ErrorLogger.java | 3 +- src/de/steamwar/bungeecore/sql/Statement.java | 62 +++++++++++-------- 2 files changed, 37 insertions(+), 28 deletions(-) diff --git a/src/de/steamwar/bungeecore/ErrorLogger.java b/src/de/steamwar/bungeecore/ErrorLogger.java index e20a7047..4bfe84c8 100644 --- a/src/de/steamwar/bungeecore/ErrorLogger.java +++ b/src/de/steamwar/bungeecore/ErrorLogger.java @@ -20,6 +20,7 @@ package de.steamwar.bungeecore; import de.steamwar.bungeecore.sql.SWException; +import de.steamwar.bungeecore.sql.Statement; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -58,7 +59,7 @@ public class ErrorLogger extends Handler { SWException.log("Bungee", "DDOS", ddosRate + ""); } return; - } else if (stacktrace.contains("ErrorLogger")) { + } else if (!Statement.connectionStable()) { return; } diff --git a/src/de/steamwar/bungeecore/sql/Statement.java b/src/de/steamwar/bungeecore/sql/Statement.java index eac76505..c37538b2 100644 --- a/src/de/steamwar/bungeecore/sql/Statement.java +++ b/src/de/steamwar/bungeecore/sql/Statement.java @@ -40,39 +40,48 @@ public class Statement { Statement.user = user; Statement.password = password; try { - con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); + con = DriverManager.getConnection(url + "?autoreconnect=true&useServerPrepStmts=true", user, password); } catch (SQLException e) { ProxyServer.getInstance().stop(); throw new SecurityException("Could not start SQL-Connection", e); } } - private static void reset(SQLException e) { - BungeeCore.get().getLogger().log(Level.WARNING, "SQL Exception thrown", e); + private static void reset() { close(); connect(url, user, password); try { for (Statement statement : statements) { statement.init(); } - } catch (SQLException ex) { - throw new SecurityException("Could not reprepare SQL Statements", ex); + } catch (SQLException e) { + throw new SecurityException("Could not reprepare SQL statements", e); } } public static void close() { - for (Statement statement : statements) { + synchronized (statements) { + for (Statement statement : statements) { + try { + statement.st.close(); + } catch (SQLException e) { + BungeeCore.get().getLogger().log(Level.INFO, "Could not close statement", e); + } + } + try { - statement.st.close(); + con.close(); } catch (SQLException e) { - BungeeCore.get().getLogger().log(Level.INFO, "Could not close statement", e); + BungeeCore.get().getLogger().log(Level.INFO, "Could not close SQL connection", e); } } + } + public static boolean connectionStable() { try { - con.close(); + return !con.isClosed(); } catch (SQLException e) { - BungeeCore.log("Could not close SQL-Connection", e); + return false; } } @@ -85,39 +94,38 @@ public class Statement { try { init(); } catch (SQLException e) { - reset(e); + throw new SecurityException("Could not init SQL statement", e); } } - private synchronized void init() throws SQLException { + private void init() throws SQLException { st = con.prepareStatement(sql); } T select(ResultSetUser user, Object... objects) { - return prepare(() -> { - ResultSet rs = st.executeQuery(); - T result = user.use(rs); - rs.close(); - return result; - }, objects); + synchronized (statements) { + return prepare(() -> { + ResultSet rs = st.executeQuery(); + T result = user.use(rs); + rs.close(); + return result; + }, objects); + } } void update(Object... objects) { - prepare(st::executeUpdate, objects); + synchronized (statements) { + prepare(st::executeUpdate, objects); + } } - private synchronized T prepare(SQLRunnable runnable, Object... objects) { + private T prepare(SQLRunnable runnable, Object... objects) { try { setObjects(objects); return runnable.run(); } catch (SQLException e) { - reset(e); - try { - setObjects(objects); - return runnable.run(); - } catch (SQLException ex) { - throw new SecurityException("Could not execute SQL statement", ex); - } + reset(); + throw new SecurityException("Could not execute SQL statement", e); } } From 5b5a1796efca7b88d3da971fd5dfefae64102e8e Mon Sep 17 00:00:00 2001 From: Lixfel Date: Mon, 27 Sep 2021 15:23:20 +0200 Subject: [PATCH 32/41] Add steamwarci script Signed-off-by: Lixfel --- steamwarci.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 steamwarci.yml diff --git a/steamwarci.yml b/steamwarci.yml new file mode 100644 index 00000000..432a095c --- /dev/null +++ b/steamwarci.yml @@ -0,0 +1,6 @@ +build: + - "ln -s /home/gitea/lib" + - "mvn package -B" + +artifacts: + "/binarys/bungeecore.jar": "target/bungeecore.jar" From 0cdcfc12a82e916f8d56e7145861f7551acfd377 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 16:42:07 +0200 Subject: [PATCH 33/41] Update DiscordBot integration --- src/de/steamwar/bungeecore/BungeeCore.java | 8 ++++++-- .../bungeecore/bot/config/SteamwarDiscordBotConfig.java | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 0b71cb53..6b46fbbc 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -154,7 +154,9 @@ public class BungeeCore extends Plugin { Team.clearCache(); }, 1, 1, TimeUnit.HOURS); - new SteamwarDiscordBot(); + if (SteamwarDiscordBotConfig.loaded) { + new SteamwarDiscordBot(); + } } @Override @@ -267,7 +269,9 @@ public class BungeeCore extends Plugin { ); ArenaMode.init(config.getSection("games")); - SteamwarDiscordBotConfig.loadConfig(config.getSection("discord")); + if (config.getSection("discord") != null) { + SteamwarDiscordBotConfig.loadConfig(config.getSection("discord")); + } final Configuration servers = config.getSection("servers"); for(final String serverName : servers.getKeys()){ diff --git a/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java b/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java index f69a3ac1..34c65e88 100644 --- a/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java +++ b/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java @@ -29,6 +29,7 @@ import java.util.Map; public class SteamwarDiscordBotConfig { + public static boolean loaded = false; public static String TOKEN; public static String GUILD; public static String ANNOUNCEMENTS_CHANNEL; @@ -110,5 +111,6 @@ public class SteamwarDiscordBotConfig { for (String type : ranksSections.getKeys()) { RANKS.put(UserGroup.getUsergroup(type), ranksSections.getString(type)); } + loaded = true; } } From c51415443f0931b0f0f6fdfe52dfa57eb76f37db Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 16:46:26 +0200 Subject: [PATCH 34/41] Fix Node NumberFormatException --- src/de/steamwar/bungeecore/Node.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index ea0a2eda..465778c2 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -191,7 +191,7 @@ public abstract class Node { int c; try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { c = Integer.parseInt(bufferedReader.readLine()); - } catch (IOException e) { + } catch (IOException | NumberFormatException e) { BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); c = 1; } From 5bcc87aa1e89fb69009649b756b0c3cdcd461639 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 30 Sep 2021 12:26:47 +0200 Subject: [PATCH 35/41] Fix autoreconnect Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/Statement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/sql/Statement.java b/src/de/steamwar/bungeecore/sql/Statement.java index c37538b2..9b1628c0 100644 --- a/src/de/steamwar/bungeecore/sql/Statement.java +++ b/src/de/steamwar/bungeecore/sql/Statement.java @@ -40,7 +40,7 @@ public class Statement { Statement.user = user; Statement.password = password; try { - con = DriverManager.getConnection(url + "?autoreconnect=true&useServerPrepStmts=true", user, password); + con = DriverManager.getConnection(url + "?autoReconnect=true&useServerPrepStmts=true", user, password); } catch (SQLException e) { ProxyServer.getInstance().stop(); throw new SecurityException("Could not start SQL-Connection", e); From 33924752c80ef163f0eb46a834684596846f179a Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 30 Sep 2021 12:30:11 +0200 Subject: [PATCH 36/41] Fix unregistering Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 6 +++++- src/de/steamwar/bungeecore/ErrorLogger.java | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 6b46fbbc..9a5dfc16 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -71,6 +71,8 @@ public class BungeeCore extends Plugin { public static final Map serverPermissions = new HashMap<>(); public static final Map commands = new HashMap<>(); + private ErrorLogger errorLogger; + @Override public void onEnable(){ getProxy().registerChannel("sw:bridge"); @@ -78,7 +80,7 @@ public class BungeeCore extends Plugin { setInstance(this); loadConfig(); - new ErrorLogger(); + errorLogger = new ErrorLogger(); new ConnectionListener(); new Forge(); new LabyMod(); @@ -167,6 +169,8 @@ public class BungeeCore extends Plugin { } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + + errorLogger.unregister(); Statement.close(); } diff --git a/src/de/steamwar/bungeecore/ErrorLogger.java b/src/de/steamwar/bungeecore/ErrorLogger.java index 4bfe84c8..80b417f1 100644 --- a/src/de/steamwar/bungeecore/ErrorLogger.java +++ b/src/de/steamwar/bungeecore/ErrorLogger.java @@ -40,6 +40,10 @@ public class ErrorLogger extends Handler { Logger.getLogger("").addHandler(this); } + void unregister(){ + Logger.getLogger("").removeHandler(this); + } + @Override public void publish(LogRecord logRecord) { if(logRecord.getLevel().intValue() < Level.WARNING.intValue()) From f9b42ad0c1a184bd9b71d35d82cf998137129b39 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 30 Sep 2021 16:21:24 +0200 Subject: [PATCH 37/41] Prevent username triggering Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/ChatListener.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index e0e4472b..0e85917a 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -21,7 +21,6 @@ package de.steamwar.bungeecore.listeners; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; -import de.steamwar.bungeecore.bot.listeners.IngameChatListener; import de.steamwar.bungeecore.commands.TpCommand; import de.steamwar.bungeecore.comms.packets.PingPacket; import de.steamwar.bungeecore.sql.SteamwarUser; @@ -151,7 +150,7 @@ public class ChatListener extends BasicListener { return; } - if(!sender.hasPermission(ConnectionListener.TEAM_GROUP) && (e.getMessage().contains("http") || e.getMessage().contains("www"))){ + if(!sender.hasPermission(ConnectionListener.TEAM_GROUP) && (e.getMessage().contains("http:") || e.getMessage().contains("https:") || e.getMessage().contains("www."))){ Message.send("CHAT_NO_LINKS", sender); e.setCancelled(true); return; From c3c666c30595ac01e80654e8a8e5328038f61a93 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 1 Oct 2021 10:38:48 +0200 Subject: [PATCH 38/41] Encapsulate DiscordBot errors Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 8 +++++++- src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java | 7 ++++++- .../bungeecore/commands/ServerTeamchatCommand.java | 9 ++++++++- src/de/steamwar/bungeecore/listeners/ChatListener.java | 7 ++++++- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 9a5dfc16..16e8e9dd 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -157,7 +157,11 @@ public class BungeeCore extends Plugin { }, 1, 1, TimeUnit.HOURS); if (SteamwarDiscordBotConfig.loaded) { - new SteamwarDiscordBot(); + try { + new SteamwarDiscordBot(); + } catch (Exception e) { + getLogger().log(Level.SEVERE, "Could not initialize discord bot", e); + } } } @@ -168,6 +172,8 @@ public class BungeeCore extends Plugin { SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); } catch (InterruptedException e) { Thread.currentThread().interrupt(); + } catch (Exception e) { + getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e); } errorLogger.unregister(); diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index 8ff2dfc9..3a4c2b39 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -44,6 +44,7 @@ import javax.security.auth.login.LoginException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.logging.Level; public class SteamwarDiscordBot { @@ -84,7 +85,11 @@ public class SteamwarDiscordBot { } catch (InterruptedException e) { e.printStackTrace(); } - activity(); + try { + activity(); + } catch (Exception e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not set initial activity to discord", e); + } EventManager.update(); SchematicsManager.update(); ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { diff --git a/src/de/steamwar/bungeecore/commands/ServerTeamchatCommand.java b/src/de/steamwar/bungeecore/commands/ServerTeamchatCommand.java index b9b0ab1a..f9c589b2 100644 --- a/src/de/steamwar/bungeecore/commands/ServerTeamchatCommand.java +++ b/src/de/steamwar/bungeecore/commands/ServerTeamchatCommand.java @@ -19,6 +19,7 @@ package de.steamwar.bungeecore.commands; +import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.listeners.ChatListener; @@ -28,6 +29,8 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; +import java.util.logging.Level; + public class ServerTeamchatCommand extends BasicCommand { public ServerTeamchatCommand() { @@ -51,7 +54,11 @@ public class ServerTeamchatCommand extends BasicCommand { String msg = msgBuilder.toString(); msg = ChatColor.translateAlternateColorCodes('&', msg); - SteamwarDiscordBot.instance().getServerTeamChatListener().send(" " + (player.getName() + "» " + msg).replaceAll("§[a-f0-9r]", "")); + try { + SteamwarDiscordBot.instance().getServerTeamChatListener().send(" " + (player.getName() + "» " + msg).replaceAll("§[a-f0-9r]", "")); + } catch (Exception e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send stc message to discord", e); + } sendToTeam(msg, player); } } diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index 0e85917a..b4ff5e98 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -37,6 +37,7 @@ import net.md_5.bungee.event.EventHandler; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.logging.Level; public class ChatListener extends BasicListener { @@ -203,7 +204,11 @@ public class ChatListener extends BasicListener { msg = "§" + team.getTeamColor() + team.getTeamKuerzel() + " §r" + msg; } - SteamwarDiscordBot.instance().getIngameChatListener().send(" " + msg.replaceAll("§[a-f0-9r]", "")); + try { + SteamwarDiscordBot.instance().getIngameChatListener().send(" " + msg.replaceAll("§[a-f0-9r]", "")); + } catch (Exception e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send chat message to discord", e); + } for(ProxiedPlayer target : ProxyServer.getInstance().getPlayers()){ Subserver targetServer = Subserver.getSubserver(target); if(!(targetServer == null || targetServer.getType() != Servertype.ARENA || targetServer.getServer() != target.getServer().getInfo())) continue; From ef8928d3bda6f4517fc8e2be8661eea375eba730 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 1 Oct 2021 10:41:58 +0200 Subject: [PATCH 39/41] Better encapsulation Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 16e8e9dd..be2007a3 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -159,7 +159,7 @@ public class BungeeCore extends Plugin { if (SteamwarDiscordBotConfig.loaded) { try { new SteamwarDiscordBot(); - } catch (Exception e) { + } catch (Throwable e) { getLogger().log(Level.SEVERE, "Could not initialize discord bot", e); } } @@ -172,7 +172,7 @@ public class BungeeCore extends Plugin { SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } catch (Exception e) { + } catch (Throwable e) { getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e); } From a3d768b1f101af92b334fd016ed8f82a1184d558 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Fri, 1 Oct 2021 10:55:29 +0200 Subject: [PATCH 40/41] Making listener stuff volatile to fix NPE's with multiple threads accessing them --- src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java index 3a4c2b39..e614c5ee 100644 --- a/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java +++ b/src/de/steamwar/bungeecore/bot/SteamwarDiscordBot.java @@ -55,13 +55,13 @@ public class SteamwarDiscordBot { } @Getter - private AnnouncementListener announcementListener; + private volatile AnnouncementListener announcementListener; @Getter - private IngameChatListener ingameChatListener; + private volatile IngameChatListener ingameChatListener; @Getter - private ServerTeamChatListener serverTeamChatListener; + private volatile ServerTeamChatListener serverTeamChatListener; @Getter private final JDA jda; @@ -100,7 +100,6 @@ public class SteamwarDiscordBot { DiscordRolesMessage.sendMessage(); DiscordRulesMessage.sendMessage(); DiscordTicketMessage.sendMessage(); - new RolesInteractionButtonListener(); new DiscordTicketListener(); new DiscordAuthListener(); @@ -109,7 +108,6 @@ public class SteamwarDiscordBot { ingameChatListener = new IngameChatListener(); serverTeamChatListener = new ServerTeamChatListener(); new SlashCommandListener(); - jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); From aebb37e10eab78301c00380096ee6b3ce218515e Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 2 Oct 2021 07:48:21 +0200 Subject: [PATCH 41/41] Fix discord bot shutdown Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index be2007a3..13a27a0b 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -31,7 +31,6 @@ import de.steamwar.bungeecore.listeners.mods.WorldDownloader; import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; -import net.dv8tion.jda.api.JDA; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; @@ -168,10 +167,7 @@ public class BungeeCore extends Plugin { @Override public void onDisable(){ try { - SteamwarDiscordBot.instance().getJda().shutdownNow(); - SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + SteamwarDiscordBot.instance().getJda().shutdown(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e); }