From 4496cd8b0a4a4aba70b1363156a2317f63248aa9 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Thu, 4 Mar 2021 03:06:34 +0100 Subject: [PATCH 01/83] Changing to Schemnodes --- .../bungeecore/commands/CheckCommand.java | 74 ++-- .../bungeecore/inventory/SWListInv.java | 23 -- .../bungeecore/listeners/CheckListener.java | 6 +- .../bungeecore/sql/CheckedSchematic.java | 20 +- .../steamwar/bungeecore/sql/NodeMember.java | 87 +++++ src/de/steamwar/bungeecore/sql/Schematic.java | 141 ------- .../bungeecore/sql/SchematicMember.java | 134 ------- .../bungeecore/sql/SchematicNode.java | 359 ++++++++++++++++++ 8 files changed, 497 insertions(+), 347 deletions(-) create mode 100644 src/de/steamwar/bungeecore/sql/NodeMember.java delete mode 100644 src/de/steamwar/bungeecore/sql/Schematic.java delete mode 100644 src/de/steamwar/bungeecore/sql/SchematicMember.java create mode 100644 src/de/steamwar/bungeecore/sql/SchematicNode.java diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index 9aaed51..bd268ec 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -22,7 +22,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.sql.CheckedSchematic; -import de.steamwar.bungeecore.sql.Schematic; +import de.steamwar.bungeecore.sql.SchematicNode; import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ChatColor; @@ -66,7 +66,7 @@ public class CheckCommand extends BasicCommand { super("check", ConnectionListener.CHECK_PERMISSION); ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { - List schematics = getSchemsToCheck(); + List schematics = getSchemsToCheck(); if(schematics.size() != currentCheckers.size()) Message.team("CHECK_REMINDER", schematics.size() - currentCheckers.size()); }, 10, 10, TimeUnit.MINUTES); @@ -105,33 +105,33 @@ public class CheckCommand extends BasicCommand { } } - private static List getSchemsToCheck(){ - List schematicList = new LinkedList<>(); + private static List getSchemsToCheck(){ + List schematicList = new LinkedList<>(); for (SchematicType type : SchematicType.values()) { if (type.check()) - schematicList.addAll(Schematic.getAllSchemsOfType(type)); + schematicList.addAll(SchematicNode.getAllSchematicsOfType(type.toDB())); } return schematicList; } private void list(ProxiedPlayer player) { - List schematicList = getSchemsToCheck(); + List schematicList = getSchemsToCheck(); Message.sendPrefixless("CHECK_LIST_HEADER", player, schematicList.size()); - for (Schematic schematic : schematicList) { - CheckSession current = currentSchems.get(schematic.getSchemID()); + for (SchematicNode schematic : schematicList) { + CheckSession current = currentSchems.get(schematic.getId()); if (current == null) { Message.sendPrefixless("CHECK_LIST_TO_CHECK", player, Message.parse("CHECK_LIST_TO_CHECK_HOVER", player), - new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check schematic " + schematic.getSchemID()), - schematic.getSchemType().getKuerzel(), SteamwarUser.get(schematic.getSchemOwner()).getUserName(), schematic.getSchemName()); + new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check schematic " + schematic.getId()), + schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName()); } else { Message.sendPrefixless("CHECK_LIST_CHECKING", player, Message.parse("CHECK_LIST_CHECKING_HOVER", player), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + current.checker.getName()), - schematic.getSchemType().getKuerzel(), SteamwarUser.get(schematic.getSchemOwner()).getUserName(), schematic.getSchemName(), current.checker.getName()); + schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName(), current.checker.getName()); } } } @@ -142,11 +142,11 @@ public class CheckCommand extends BasicCommand { return; } - Schematic schem = Schematic.getSchemFromDB(Integer.parseInt(schemID)); - if(!schem.getSchemType().check()){ + SchematicNode schem = SchematicNode.getSchematicNode(Integer.parseInt(schemID)); + if(!schem.getSchemtype().check()){ ProxyServer.getInstance().getLogger().log(Level.SEVERE, player.getName() + " tried to check an uncheckable schematic!"); return; - }else if(schem.getSchemOwner() == SteamwarUser.get(player.getUniqueId()).getId()) { + }else if(schem.getOwner() == SteamwarUser.get(player.getUniqueId()).getId()) { Message.send("CHECK_SCHEMATIC_OWN", player); return; } @@ -212,15 +212,15 @@ public class CheckCommand extends BasicCommand { private static class CheckSession{ private final ProxiedPlayer checker; - private final Schematic schematic; + private final SchematicNode schematic; private final Timestamp startTime; private final ListIterator checkList; - private CheckSession(ProxiedPlayer checker, Schematic schematic){ + private CheckSession(ProxiedPlayer checker, SchematicNode schematic){ this.checker = checker; this.schematic = schematic; this.startTime = Timestamp.from(Instant.now()); - this.checkList = checkQuestions.get(schematic.getSchemType()).listIterator(); + this.checkList = checkQuestions.get(schematic.getSchemtype()).listIterator(); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { for (Subserver subserver : Subserver.getServerList()) { @@ -230,11 +230,11 @@ public class CheckCommand extends BasicCommand { } } - ArenaMode mode = ArenaMode.getByCheckSchemType(schematic.getSchemType().toDB()); - SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getSchemID()); + //ArenaMode mode = ArenaMode.getByCheckSchemType(schematic.getSchemtype().toDB()); + //SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getId()); currentCheckers.put(checker.getUniqueId(), this); - currentSchems.put(schematic.getSchemID(), this); - for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic.getSchemName(), schematic.getSchemOwner())) + currentSchems.put(schematic.getId(), this); + for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic.getId())) Message.sendPrefixless("CHECK_SCHEMATIC_PREVIOUS", checker, previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getReason()); next(0); }); @@ -253,8 +253,8 @@ public class CheckCommand extends BasicCommand { if(checkList.hasNext()){ next.setText(Message.parse("CHECK_NEXT", checker)); next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check next")); - }else if(ranks.containsKey(schematic.getSchemType())){ - List r = ranks.get(schematic.getSchemType()); + }else if(ranks.containsKey(schematic.getSchemtype())){ + List r = ranks.get(schematic.getSchemtype()); for(int i = 0; i < r.size(); i++){ Message.sendPrefixless("CHECK_RANK", checker, Message.parse("CHECK_RANK_HOVER", checker), @@ -276,43 +276,43 @@ public class CheckCommand extends BasicCommand { } private void accept(int rank){ - if(ranks.containsKey(schematic.getSchemType())){ - if(rank <= 0 || ranks.get(schematic.getSchemType()).size() < rank){ + if(ranks.containsKey(schematic.getSchemtype())){ + if(rank <= 0 || ranks.get(schematic.getSchemtype()).size() < rank){ Message.send("CHECK_INVALID_RANK", checker); return; } schematic.setRank(rank); } - schematic.setSchemType(schematic.getSchemType().fightType()); - CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben"); - SteamwarUser user = SteamwarUser.get(schematic.getSchemOwner()); + schematic.setType(schematic.getSchemtype().fightType().toDB()); + CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben"); + SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) - Message.send("CHECK_ACCEPTED", player, schematic.getSchemType().name(), schematic.getSchemName()); - Message.team("CHECK_ACCEPTED_TEAM", schematic.getSchemName(), user.getUserName()); + Message.send("CHECK_ACCEPTED", player, schematic.getSchemtype().name(), schematic.getName()); + Message.team("CHECK_ACCEPTED_TEAM", schematic.getName(), user.getUserName()); stop(); } private void decline(String reason){ - schematic.setSchemType(SchematicType.Normal); - CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason); - SteamwarUser user = SteamwarUser.get(schematic.getSchemOwner()); + schematic.setType(SchematicType.Normal.toDB()); + CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason); + SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) - Message.send("CHECK_DECLINED", player, schematic.getSchemType().name(), schematic.getSchemName(), reason); - Message.team("CHECK_DECLINED_TEAM", schematic.getSchemName(), user.getUserName(), reason); + Message.send("CHECK_DECLINED", player, schematic.getSchemtype().name(), schematic.getName(), reason); + Message.team("CHECK_DECLINED_TEAM", schematic.getName(), user.getUserName(), reason); stop(); } private void abort(){ - CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen"); + CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen"); stop(); } private void stop(){ currentCheckers.remove(checker.getUniqueId()); - currentSchems.remove(schematic.getSchemID()); + currentSchems.remove(schematic.getId()); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(checker.getUniqueId())) { diff --git a/src/de/steamwar/bungeecore/inventory/SWListInv.java b/src/de/steamwar/bungeecore/inventory/SWListInv.java index 1161260..8636054 100644 --- a/src/de/steamwar/bungeecore/inventory/SWListInv.java +++ b/src/de/steamwar/bungeecore/inventory/SWListInv.java @@ -19,8 +19,6 @@ package de.steamwar.bungeecore.inventory; -import de.steamwar.bungeecore.sql.Schematic; -import de.steamwar.bungeecore.sql.SchematicType; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -103,27 +101,6 @@ public class SWListInv extends SWInventory { return onlinePlayers; } - public static List> getSchemList(SchematicType type, int steamwarUserId){ - List> schemList = new ArrayList<>(); - - List schems; - if(type == null) - schems = Schematic.getSchemsAccessibleByUser(steamwarUserId); - else - schems = Schematic.getSchemsOfType(steamwarUserId, type); - - for(Schematic s : schems){ - String m; - if(s.getSchemItem().isEmpty()) - m = "CAULDRON_ITEM"; - else - m = s.getSchemItem(); - SWItem item = new SWItem(m, "§e" + s.getSchemName()); - schemList.add(new SWListEntry<>(item, s)); - } - return schemList; - } - public static class SWListEntry{ final SWItem item; final T object; diff --git a/src/de/steamwar/bungeecore/listeners/CheckListener.java b/src/de/steamwar/bungeecore/listeners/CheckListener.java index f4aec74..1370a0d 100644 --- a/src/de/steamwar/bungeecore/listeners/CheckListener.java +++ b/src/de/steamwar/bungeecore/listeners/CheckListener.java @@ -21,7 +21,7 @@ package de.steamwar.bungeecore.listeners; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.commands.CheckCommand; -import de.steamwar.bungeecore.sql.Schematic; +import de.steamwar.bungeecore.sql.SchematicNode; import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -40,10 +40,10 @@ public class CheckListener extends BasicListener { ProxiedPlayer player = e.getPlayer(); SteamwarUser user = SteamwarUser.get(player.getUniqueId()); - List uncheckedSchematics = new LinkedList<>(); + List uncheckedSchematics = new LinkedList<>(); for(SchematicType type : SchematicType.values()){ if(type.check()) - uncheckedSchematics.addAll(Schematic.getSchemsOfType(user.getId(), type)); + uncheckedSchematics.addAll(SchematicNode.getAllSchematicsOfType(user.getId(), type.toDB())); } if(!uncheckedSchematics.isEmpty()) diff --git a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java index 0424e4a..ed2160c 100644 --- a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java +++ b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java @@ -27,8 +27,7 @@ import java.util.List; public class CheckedSchematic { - private final String schemName; - private final int schemOwner; + private final int nodeId; private final int validator; private final Timestamp startTime; @@ -36,21 +35,20 @@ public class CheckedSchematic { private final String reason; private CheckedSchematic(ResultSet rs) throws SQLException { - schemName = rs.getString("SchemName"); - schemOwner = rs.getInt("SchemOwner"); + nodeId = rs.getInt("NodeId"); validator = rs.getInt("Validator"); startTime = rs.getTimestamp("StartTime"); endTime = rs.getTimestamp("EndTime"); reason = rs.getString("DeclineReason"); } - 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); + public static void create(int nodeId, int validator, Timestamp startTime, Timestamp endTime, String reason){ + SQL.update("INSERT INTO CheckedSchematic (NodeId, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?)", + nodeId, 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); + public static List previousChecks(int nodeId){ + ResultSet rs = SQL.select("SELECT * FROM CheckedSchematic WHERE NodeId = ? ORDER BY EndTime ASC", nodeId); List schematics = new ArrayList<>(); try { while(rs.next()) @@ -72,4 +70,8 @@ public class CheckedSchematic { public String getReason() { return reason; } + + public int getNodeId() { + return nodeId; + } } diff --git a/src/de/steamwar/bungeecore/sql/NodeMember.java b/src/de/steamwar/bungeecore/sql/NodeMember.java new file mode 100644 index 0000000..76c91e4 --- /dev/null +++ b/src/de/steamwar/bungeecore/sql/NodeMember.java @@ -0,0 +1,87 @@ +/* + 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 java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.Set; + +public class NodeMember { + public static NodeMember getNodeMember(int node, int member) { + ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?", node, member); + try { + if(!set.next()) + return null; + return new NodeMember(set); + } catch (SQLException e) { + throw new SecurityException("Could not load NodeMember", e); + } + } + + public static Set getNodeMembers(int node) { + ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE NodeId = ?", node); + try { + Set members = new HashSet<>(); + while (set.next()) + members.add(new NodeMember(set)); + return members; + } catch (SQLException e) { + throw new SecurityException("Could not load NodeMember", e); + } + } + + public static Set getSchematics(int member) { + ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE UserId = ?", member); + try { + Set members = new HashSet<>(); + while (set.next()) + members.add(new NodeMember(set)); + return members; + } catch (SQLException e) { + throw new SecurityException("Could not load NodeMember", e); + } + } + + public static NodeMember createNodeMember(int node, int member) { + SQL.update("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)", node, member); + return getNodeMember(node, member); + } + + final int node; + final int member; + + private NodeMember(ResultSet set) throws SQLException { + node = set.getInt("NodeId"); + member = set.getInt("UserId"); + } + + public int getNode() { + return node; + } + + public int getMember() { + return member; + } + + public void delete() { + SQL.update("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?", node, member); + } +} diff --git a/src/de/steamwar/bungeecore/sql/Schematic.java b/src/de/steamwar/bungeecore/sql/Schematic.java deleted file mode 100644 index 9d25a38..0000000 --- a/src/de/steamwar/bungeecore/sql/Schematic.java +++ /dev/null @@ -1,141 +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 java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class Schematic { - private final int schemID; - private final String schemName; - private final int schemOwner; - private SchematicType schemType; - private String schemItem; - - private Schematic(ResultSet rs) throws SQLException { - this.schemID = rs.getInt("SchemID"); - this.schemName = rs.getString("SchemName"); - this.schemOwner = rs.getInt("SchemOwner"); - this.schemType = SchematicType.fromDB(rs.getString("SchemType")); - 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); - } - } - - 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()) - throw new SecurityException("Failed loading schematic " + schemID); - return new Schematic(schematic); - } catch (SQLException e) { - throw new SecurityException("Failed loading schematic", e); - } - } - - public static List getAllSchemsOfType(SchematicType schemType){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?", schemType.toDB()); - List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } - return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading all schems of type", e); - } - } - - 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); - List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } - return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading schems of type", e); - } - } - - 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); - List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } - 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); - } - } - - public int getSchemID() { - return schemID; - } - - public String getSchemName() { - return schemName; - } - - public int getSchemOwner() { - return schemOwner; - } - - public String getSchemItem() { - return schemItem; - } - - public SchematicType getSchemType() { - return schemType; - } - - public void setSchemType(SchematicType schemType) { - this.schemType = schemType; - SQL.update("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?", schemType.toDB(), schemID); - } - - public void setRank(int rank) { - SQL.update("UPDATE Schematic SET Rank = ? WHERE SchemID = ?", rank, schemID); - } -} diff --git a/src/de/steamwar/bungeecore/sql/SchematicMember.java b/src/de/steamwar/bungeecore/sql/SchematicMember.java deleted file mode 100644 index 85b8485..0000000 --- a/src/de/steamwar/bungeecore/sql/SchematicMember.java +++ /dev/null @@ -1,134 +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 java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class SchematicMember { - private final int schemOwner; - private final String schemName; - private final int member; - - private SchematicMember(String schemName, int schemOwner, int schemMember, boolean updateDB){ - this.schemOwner = schemOwner; - member = schemMember; - this.schemName = schemName; - if(updateDB) - 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()); - } - - public static List getAccessibleSchems(int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE Member = ?", schemMember); - try { - 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)); - } - return schematicMembers; - } catch (SQLException e) { - throw new SecurityException("Could not get accessible schems", e); - } - } - - public int getSchemOwner() { - return schemOwner; - } - - public String getSchemName() { - return schemName; - } - - public int getMember() { - return member; - } - - public void remove(){ - SQL.update("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?", schemOwner, schemName, member); - } -} diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java new file mode 100644 index 0000000..85c0bf6 --- /dev/null +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -0,0 +1,359 @@ +/* + 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 java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +public class SchematicNode { + + public static SchematicNode createSchematic(int owner, String name, Integer parent) { + return createSchematicNode(owner, name, parent, SchematicType.Normal.toDB(), ""); + } + + public static SchematicNode createSchematicDirectory(int owner, String name, Integer parent) { + return createSchematicNode(owner, name, parent, null, ""); + } + + public static SchematicNode createSchematicNode(int owner, String name, Integer parent, String type, String item) { + if(parent == 0) + parent = null; + SQL.update("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)", + name, owner, parent, type, item); + return getSchematicNode(owner, name, parent); + } + + public static SchematicNode getSchematicNode(int owner, String name, Integer parent) { + if(parent != null && parent == 0) + parent = null; + ResultSet set; + if(parent == null) { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL", owner, name); + }else { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?", owner, name, parent); + } + try { + while (set.next()) { + SchematicNode node = new SchematicNode(set); + if(!node.isDir()) + return node; + } + List nodes = getSchematicNodeInNode(parent); + for (SchematicNode node:nodes) { + if(!node.isDir() && node.name.equals(name) && NodeMember.getNodeMember(node.getId(), owner) != null) + return node; + } + return null; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static SchematicNode getSchematicNode(int owner, String name, SchematicNode parent) { + return getSchematicNode(owner, name, parent.getId()); + } + + public static List getSchematicNodeInNode(Integer parent) { + if(parent != null && parent == 0) + parent = null; + ResultSet set; + if(parent == null) { + set = SQL.select("SELECT * FROM SchematicNode WHERE ParentNode is NULL"); + }else { + set = SQL.select("SELECT * FROM SchematicNode WHERE ParentNode = ?", parent); + } + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getSchematicNodeInNode(SchematicNode parent) { + return getSchematicNodeInNode(parent.getId()); + } + + public static SchematicNode getSchematicDirectory(String name, SchematicNode parent) { + return getSchematicDirectory(name, parent.getId()); + } + + public static SchematicNode getSchematicDirectory(String name, Integer parent) { + if(parent != null && parent == 0) + parent = null; + ResultSet set; + if(parent == null) { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); + }else { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); + } + try { + while (set.next()) { + SchematicNode node = new SchematicNode(set); + if(node.isDir()) + return node; + } + return null; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static SchematicNode getSchematicInParent(String name, Integer parent) { + if(parent != null && parent == 0) + parent = null; + ResultSet set; + if(parent == null) { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); + }else { + set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); + } + try { + while (set.next()) { + SchematicNode node = new SchematicNode(set); + if(!node.isDir()) + return node; + } + return null; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static SchematicNode getSchematicNode(int id) { + ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeId = ?", id); + try { + if(!set.next()) + return null; + return new SchematicNode(set); + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getAllSchematicsOfType(int owner, String schemType) { + ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?", owner, schemType); + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getAllSchematicsOfType(String schemType) { + ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeType = ?", schemType); + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getSchematicsOfType(int owner, String schemType, Integer parent) { + if(parent != null && parent == 0) + parent = null; + List schems = getAllSchematicsOfType(owner, schemType); + Map nodesInParent = new LinkedHashMap<>(); + for (SchematicNode schematicNode : schems) { + SchematicNode currentNode = schematicNode; + while (currentNode.getParent() != parent) { + currentNode = currentNode.getParentNode(); + } + nodesInParent.putIfAbsent(currentNode.getId(), currentNode); + } + return new ArrayList<>(nodesInParent.values()); + } + + public static List getSchematicsAccessibleByUser(int user, Integer parent) { + if(parent != null && parent != 0) { + SchematicNode node = SchematicNode.getSchematicNode(parent); + boolean isAdded = false; + while (node.getId() != 0) { + for (NodeMember member:node.getMembers()) { + if (member.getMember() == user) { + isAdded = true; + break; + } + } + node = SchematicNode.getSchematicNode(node.getParent()); + } + if(isAdded) + return getSchematicNodeInNode(parent); + } else { + ResultSet set = SQL.select("SELECT * FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName", user, user); + try{ + List nodes = new ArrayList<>(); + while(set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch(SQLException e){ + throw new SecurityException("Failed listing schematics", e); + } + } + return null; + } + + public static List getAllSchematicsAccessibleByUser(int user) { + ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode FROM SchematicNode s LEFT JOIN NodeMember nm ON nm.NodeId = s.NodeId WHERE s.NodeOwner = ? OR nm.UserId = ? GROUP BY s.NodeId ORDER BY s.NodeName", user, user); + try{ + List nodes = new ArrayList<>(); + while(set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch(SQLException e){ + throw new SecurityException("Failed listing schematics", e); + } + } + + private final int id; + private final int owner; + private String name; + private int parent; + private String item; + private String type; + private boolean schemFormat; + private int rank; + private boolean isDir; + + private SchematicNode(ResultSet set) throws SQLException { + id = set.getInt("NodeId"); + owner = set.getInt("NodeOwner"); + name = set.getString("NodeName"); + parent = set.getInt("ParentNode"); + item = set.getString("NodeItem"); + type = set.getString("NodeType"); + if(type != null) { + isDir = false; + rank = set.getInt("NodeRank"); + schemFormat = set.getBoolean("NodeFormat"); + }else { + isDir = true; + } + } + + public int getId() { + return id; + } + + public int getOwner() { + return owner; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + updateDB(); + } + + public int getParent() { + return parent; + } + + public void setParent(int parent) { + this.parent = parent; + updateDB(); + } + + public String getItem() { + return item; + } + + public void setItem(String item) { + this.item = item; + updateDB(); + } + + public String getType() { + if(isDir) + throw new SecurityException("Node is Directory"); + return type; + } + + public void setType(String type) { + if(isDir) + throw new SecurityException("Node is Directory"); + this.type = type; + updateDB(); + } + + public boolean isDir() { + return isDir; + } + + public boolean getSchemFormat() { + if(isDir) + throw new SecurityException("Node is Directory"); + return schemFormat; + } + + public int getRank() { + if(isDir) + throw new SecurityException("Node is Directory"); + return rank; + } + + public void setRank(int rank) { + if(isDir) + throw new SecurityException("Node is Directory"); + this.rank = rank; + } + + public SchematicType getSchemtype() { + if(isDir()) + throw new RuntimeException("Is Directory"); + return SchematicType.fromDB(type); + } + + public SchematicNode getParentNode() { + return SchematicNode.getSchematicNode(parent); + } + + public boolean accessibleByUser(int user) { + return NodeMember.getNodeMember(id, user) != null; + } + + public Set getMembers() { + return NodeMember.getNodeMembers(id); + } + + private void updateDB() { + SQL.update("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?", + name, owner, parent, item, type, rank, id); + } + + public void delete() { + if(isDir()) { + getSchematicNodeInNode(getId()).forEach(SchematicNode::delete); + } + SQL.update("DELETE FROM SchematicNode WHERE NodeId = ?", id); + } +} From 5576d1e3ca295f0a402943f5acdbc05fc5e5821e Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sun, 18 Jul 2021 19:40:53 +0200 Subject: [PATCH 02/83] Update! --- .../bungeecore/commands/CheckCommand.java | 6 +- .../bungeecore/sql/SchematicNode.java | 301 +++++++++++------- 2 files changed, 190 insertions(+), 117 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index fe8b40e..63671c0 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -72,7 +72,7 @@ public class CheckCommand extends BasicCommand { }, 10, 10, TimeUnit.MINUTES); } public static void sendReminder(ProxiedPlayer player) { - List schematics = getSchemsToCheck(); + List schematics = getSchemsToCheck(); if(schematics.size() != currentCheckers.size()) Message.send("CHECK_REMINDER", player, "CHECK_REMINDER_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size()); } @@ -230,8 +230,8 @@ public class CheckCommand extends BasicCommand { ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { BauCommand.stopBauserver(checker); - ArenaMode mode = ArenaMode.getByCheckSchemType(schematic.getSchemType().toDB()); - SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getSchemID()); + ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemtype()); + SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getId(), 0); currentCheckers.put(checker.getUniqueId(), this); currentSchems.put(schematic.getId(), this); for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic.getId())) diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java index 85c0bf6..c419c09 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicNode.java +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -1,27 +1,31 @@ /* - 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 . + * 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 java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Instant; import java.util.*; +import java.util.function.Predicate; public class SchematicNode { @@ -34,59 +38,33 @@ public class SchematicNode { } public static SchematicNode createSchematicNode(int owner, String name, Integer parent, String type, String item) { - if(parent == 0) + if (parent == 0) parent = null; SQL.update("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)", name, owner, parent, type, item); return getSchematicNode(owner, name, parent); } - public static SchematicNode getSchematicNode(int owner, String name, Integer parent) { - if(parent != null && parent == 0) - parent = null; - ResultSet set; - if(parent == null) { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL", owner, name); - }else { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?", owner, name, parent); - } - try { - while (set.next()) { - SchematicNode node = new SchematicNode(set); - if(!node.isDir()) - return node; - } - List nodes = getSchematicNodeInNode(parent); - for (SchematicNode node:nodes) { - if(!node.isDir() && node.name.equals(name) && NodeMember.getNodeMember(node.getId(), owner) != null) - return node; - } - return null; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } - } + private Timestamp lastUpdate; public static SchematicNode getSchematicNode(int owner, String name, SchematicNode parent) { return getSchematicNode(owner, name, parent.getId()); } - public static List getSchematicNodeInNode(Integer parent) { - if(parent != null && parent == 0) - parent = null; - ResultSet set; - if(parent == null) { - set = SQL.select("SELECT * FROM SchematicNode WHERE ParentNode is NULL"); - }else { - set = SQL.select("SELECT * FROM SchematicNode WHERE ParentNode = ?", parent); - } - try { - List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); - return nodes; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); + private SchematicNode(ResultSet set) throws SQLException { + id = set.getInt("NodeId"); + owner = set.getInt("NodeOwner"); + name = set.getString("NodeName"); + parent = set.getInt("ParentNode"); + item = set.getString("NodeItem"); + type = set.getString("NodeType"); + lastUpdate = set.getTimestamp("LastUpdate"); + if (type != null) { + isDir = false; + rank = set.getInt("NodeRank"); + schemFormat = set.getBoolean("NodeFormat"); + } else { + isDir = true; } } @@ -98,14 +76,58 @@ public class SchematicNode { return getSchematicDirectory(name, parent.getId()); } + public static SchematicNode getSchematicNode(int owner, String name, Integer parent) { + if (parent != null && parent == 0) + parent = null; + ResultSet set; + if (parent == null) { + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL", owner, name); + } else { + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?", owner, name, parent); + } + try { + while (set.next()) { + SchematicNode node = new SchematicNode(set); + return node; + } + List nodes = getSchematicNodeInNode(parent); + for (SchematicNode node:nodes) { + if (node.name.equals(name) && NodeMember.getNodeMember(node.getId(), owner) != null) + return node; + } + return null; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getSchematicNodeInNode(Integer parent) { + if(parent != null && parent == 0) + parent = null; + ResultSet set; + if(parent == null) { + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL"); + }else { + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ?", parent); + } + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + }catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + public static SchematicNode getSchematicDirectory(String name, Integer parent) { if(parent != null && parent == 0) parent = null; ResultSet set; if(parent == null) { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); }else { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); } try { while (set.next()) { @@ -124,9 +146,9 @@ public class SchematicNode { parent = null; ResultSet set; if(parent == null) { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name); }else { - set = SQL.select("SELECT * FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); + set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); } try { while (set.next()) { @@ -141,44 +163,19 @@ public class SchematicNode { } public static SchematicNode getSchematicNode(int id) { - ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeId = ?", id); + ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?", id); try { - if(!set.next()) + if (!set.next()) return null; return new SchematicNode(set); - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } - } - - public static List getAllSchematicsOfType(int owner, String schemType) { - ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?", owner, schemType); - try { - List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); - return nodes; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } - } - - public static List getAllSchematicsOfType(String schemType) { - ResultSet set = SQL.select("SELECT * FROM SchematicNode WHERE NodeType = ?", schemType); - try { - List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); - return nodes; - }catch (SQLException e) { + } catch (SQLException e) { throw new SecurityException("Failed to load Schemnodes", e); } } public static List getSchematicsOfType(int owner, String schemType, Integer parent) { - if(parent != null && parent == 0) - parent = null; - List schems = getAllSchematicsOfType(owner, schemType); + List schems = getAllSchematicsAccessibleByUser(owner); + schems.removeIf(node -> !node.getType().equals(schemType)); Map nodesInParent = new LinkedHashMap<>(); for (SchematicNode schematicNode : schems) { SchematicNode currentNode = schematicNode; @@ -190,8 +187,46 @@ public class SchematicNode { return new ArrayList<>(nodesInParent.values()); } + public static List getAllSchematicsOfType(int owner, String schemType) { + ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?", owner, schemType); + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + } catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List getAllSchematicsOfType(String schemType) { + ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?", schemType); + try { + List nodes = new ArrayList<>(); + while (set.next()) + nodes.add(new SchematicNode(set)); + return nodes; + } catch (SQLException e) { + throw new SecurityException("Failed to load Schemnodes", e); + } + } + + public static List deepGet(Integer parent, Predicate filter) { + List finalList = new ArrayList<>(); + List nodes = SchematicNode.getSchematicNodeInNode(parent); + nodes.forEach(node -> { + if (node.isDir()) { + finalList.addAll(deepGet(node.getId(), filter)); + } else { + if (filter.test(node)) + finalList.add(node); + } + }); + return finalList; + } + public static List getSchematicsAccessibleByUser(int user, Integer parent) { - if(parent != null && parent != 0) { + if (parent != null && parent != 0) { SchematicNode node = SchematicNode.getSchematicNode(parent); boolean isAdded = false; while (node.getId() != 0) { @@ -206,7 +241,7 @@ public class SchematicNode { if(isAdded) return getSchematicNodeInNode(parent); } else { - ResultSet set = SQL.select("SELECT * FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName", user, user); + ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName", user, user); try{ List nodes = new ArrayList<>(); while(set.next()) @@ -216,11 +251,11 @@ public class SchematicNode { throw new SecurityException("Failed listing schematics", e); } } - return null; + return Collections.emptyList(); } public static List getAllSchematicsAccessibleByUser(int user) { - ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode FROM SchematicNode s LEFT JOIN NodeMember nm ON nm.NodeId = s.NodeId WHERE s.NodeOwner = ? OR nm.UserId = ? GROUP BY s.NodeId ORDER BY s.NodeName", user, user); + ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember nm ON nm.NodeId = s.NodeId WHERE s.NodeOwner = ? OR nm.UserId = ? GROUP BY s.NodeId ORDER BY s.NodeName", user, user); try{ List nodes = new ArrayList<>(); while(set.next()) @@ -234,26 +269,35 @@ public class SchematicNode { private final int id; private final int owner; private String name; - private int parent; + private Integer parent; private String item; private String type; private boolean schemFormat; private int rank; - private boolean isDir; + private final boolean isDir; - private SchematicNode(ResultSet set) throws SQLException { - id = set.getInt("NodeId"); - owner = set.getInt("NodeOwner"); - name = set.getString("NodeName"); - parent = set.getInt("ParentNode"); - item = set.getString("NodeItem"); - type = set.getString("NodeType"); - if(type != null) { - isDir = false; - rank = set.getInt("NodeRank"); - schemFormat = set.getBoolean("NodeFormat"); - }else { - isDir = true; + public static List filterSchems(int user, Predicate filter) { + List finalList = new ArrayList<>(); + List nodes = SchematicNode.getSchematicsAccessibleByUser(user, null); + nodes.forEach(node -> { + if (node.isDir()) { + finalList.addAll(deepGet(node.getId(), filter)); + } else { + if (filter.test(node)) + finalList.add(node); + } + }); + return finalList; + } + + public static Integer countNodes() { + ResultSet set = SQL.select("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); + try { + if (set.next()) + return set.getInt("count"); + return 0; + } catch (SQLException e) { + throw new SecurityException("Failed listing schematics", e); } } @@ -274,7 +318,7 @@ public class SchematicNode { updateDB(); } - public int getParent() { + public Integer getParent() { return parent; } @@ -345,15 +389,44 @@ public class SchematicNode { return NodeMember.getNodeMembers(id); } + public Timestamp getLastUpdate() { + return lastUpdate; + } + + public String generateBreadcrumbs(SteamwarUser user) { + return generateBreadcrumbs("/", user); + } + + public String generateBreadcrumbs(String split, SteamwarUser user) { + StringBuilder builder = new StringBuilder(getName()); + SchematicNode currentNode = this; + if (currentNode.isDir()) builder.append("/"); + while (currentNode.getParentNode() != null) { + currentNode = currentNode.getParentNode(); + builder.insert(0, split) + .insert(0, currentNode.getName()); + if (currentNode.getMembers().stream().anyMatch(member -> member.getMember() == user.getId())) { + break; + } + } + return builder.toString(); + } + private void updateDB() { SQL.update("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?", - name, owner, parent, item, type, rank, id); + name, owner, parent == 0 ? null : parent, item, type, rank, id); + this.lastUpdate = Timestamp.from(Instant.now()); } public void delete() { - if(isDir()) { + if (isDir()) { getSchematicNodeInNode(getId()).forEach(SchematicNode::delete); } SQL.update("DELETE FROM SchematicNode WHERE NodeId = ?", id); } + + private void updateDatabase(Blob blob, boolean newFormat) { + SQL.update("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?", blob, newFormat, id); + schemFormat = newFormat; + } } From 3409353a833aa6f03fbf217955b93802a024570e Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 21 Aug 2021 18:55:07 +0200 Subject: [PATCH 03/83] Use new FightInfo Signed-off-by: Lixfel --- .../bungeecore/comms/PacketIdManager.java | 4 + .../bungeecore/comms/SpigotHandler.java | 3 +- .../bungeecore/comms/SpigotReceiver.java | 19 +- .../comms/handlers/FightInfoHandler.java | 60 ++++ .../comms/handlers/ImALobbyHandler.java | 32 ++ .../handlers/InventoryCallbackHandler.java | 11 +- .../comms/handlers/PrepareSchemHandler.java | 9 +- .../comms/handlers/TablistNameHandler.java | 20 -- .../comms/packets/FightInfoPacket.java | 183 ++++++++++ .../bungeecore/listeners/TablistManager.java | 322 ++++++++++-------- 10 files changed, 479 insertions(+), 184 deletions(-) create mode 100644 src/de/steamwar/bungeecore/comms/handlers/FightInfoHandler.java create mode 100644 src/de/steamwar/bungeecore/comms/handlers/ImALobbyHandler.java delete mode 100644 src/de/steamwar/bungeecore/comms/handlers/TablistNameHandler.java create mode 100644 src/de/steamwar/bungeecore/comms/packets/FightInfoPacket.java diff --git a/src/de/steamwar/bungeecore/comms/PacketIdManager.java b/src/de/steamwar/bungeecore/comms/PacketIdManager.java index 8376d59..94c735b 100644 --- a/src/de/steamwar/bungeecore/comms/PacketIdManager.java +++ b/src/de/steamwar/bungeecore/comms/PacketIdManager.java @@ -30,4 +30,8 @@ public class PacketIdManager { public static final byte INVENTORY_PACKET = 0x10; public static final byte INVENTORY_CALLBACK_PACKET = 0x11; public static final byte INVENTORY_CLOSE_PACKET = 0x12; + + //0x2(X) Server Information System + public static final byte I_AM_A_LOBBY = 0x20; + public static final byte FIGHT_INFO = 0x21; } diff --git a/src/de/steamwar/bungeecore/comms/SpigotHandler.java b/src/de/steamwar/bungeecore/comms/SpigotHandler.java index 5c0f118..574e9a2 100644 --- a/src/de/steamwar/bungeecore/comms/SpigotHandler.java +++ b/src/de/steamwar/bungeecore/comms/SpigotHandler.java @@ -20,8 +20,9 @@ package de.steamwar.bungeecore.comms; import com.google.common.io.ByteArrayDataInput; +import net.md_5.bungee.api.config.ServerInfo; public interface SpigotHandler { - void handle(ByteArrayDataInput byteArrayDataInput); + void handle(ByteArrayDataInput in, ServerInfo info); } diff --git a/src/de/steamwar/bungeecore/comms/SpigotReceiver.java b/src/de/steamwar/bungeecore/comms/SpigotReceiver.java index f87646f..ab6d246 100644 --- a/src/de/steamwar/bungeecore/comms/SpigotReceiver.java +++ b/src/de/steamwar/bungeecore/comms/SpigotReceiver.java @@ -21,10 +21,9 @@ package de.steamwar.bungeecore.comms; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteStreams; -import de.steamwar.bungeecore.comms.handlers.InventoryCallbackHandler; -import de.steamwar.bungeecore.comms.handlers.PrepareSchemHandler; -import de.steamwar.bungeecore.comms.handlers.TablistNameHandler; +import de.steamwar.bungeecore.comms.handlers.*; import de.steamwar.bungeecore.listeners.BasicListener; +import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.event.PluginMessageEvent; import net.md_5.bungee.event.EventHandler; @@ -39,14 +38,14 @@ public class SpigotReceiver extends BasicListener { public void onPluginMessage(PluginMessageEvent event) { if(!event.getTag().equalsIgnoreCase("sw:bridge")) return; - if(!event.getSender().getAddress().getHostName().equals("localhost")){ - event.setCancelled(true); + + event.setCancelled(true); + if(!(event.getSender() instanceof Server)) return; - } + ByteArrayDataInput in = ByteStreams.newDataInput(event.getData()); Byte handler = in.readByte(); - handlerMap.get(handler).handle(in); - event.setCancelled(true); + handlerMap.get(handler).handle(in, ((Server) event.getSender()).getInfo()); } public static void registerHandler(Byte id, SpigotHandler handler) { @@ -55,7 +54,9 @@ public class SpigotReceiver extends BasicListener { static { registerHandler(PacketIdManager.INVENTORY_CALLBACK_PACKET, new InventoryCallbackHandler()); - registerHandler(PacketIdManager.TABLIST_NAME, new TablistNameHandler()); + registerHandler(PacketIdManager.TABLIST_NAME, (in, info) -> {}); registerHandler(PacketIdManager.PREPARE_SCHEM, new PrepareSchemHandler()); + registerHandler(PacketIdManager.I_AM_A_LOBBY, new ImALobbyHandler()); + registerHandler(PacketIdManager.FIGHT_INFO, new FightInfoHandler()); } } diff --git a/src/de/steamwar/bungeecore/comms/handlers/FightInfoHandler.java b/src/de/steamwar/bungeecore/comms/handlers/FightInfoHandler.java new file mode 100644 index 0000000..998e53e --- /dev/null +++ b/src/de/steamwar/bungeecore/comms/handlers/FightInfoHandler.java @@ -0,0 +1,60 @@ +/* + 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.handlers; + +import com.google.common.io.ByteArrayDataInput; +import de.steamwar.bungeecore.comms.SpigotHandler; +import de.steamwar.bungeecore.comms.packets.FightInfoPacket; +import de.steamwar.bungeecore.listeners.TablistManager; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class FightInfoHandler implements SpigotHandler { + + private static final Set lobbys = new HashSet<>(); + + public static void addLobby(ServerInfo lobby) { + lobbys.add(lobby); + } + + @Override + public void handle(ByteArrayDataInput in, ServerInfo info) { + FightInfoPacket packet = new FightInfoPacket(in); + packet.setServerName(info.getName()); + + TablistManager.newFightInfo(info, packet); + + Iterator lobbyIt = lobbys.iterator(); + while(lobbyIt.hasNext()) { + ServerInfo lobby = lobbyIt.next(); + Iterator it = lobby.getPlayers().iterator(); + if(!it.hasNext()){ + lobbyIt.remove(); + continue; + } + + packet.send(it.next()); + } + } +} diff --git a/src/de/steamwar/bungeecore/comms/handlers/ImALobbyHandler.java b/src/de/steamwar/bungeecore/comms/handlers/ImALobbyHandler.java new file mode 100644 index 0000000..8d2013d --- /dev/null +++ b/src/de/steamwar/bungeecore/comms/handlers/ImALobbyHandler.java @@ -0,0 +1,32 @@ +/* + 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.handlers; + +import com.google.common.io.ByteArrayDataInput; +import de.steamwar.bungeecore.comms.SpigotHandler; +import net.md_5.bungee.api.config.ServerInfo; + +public class ImALobbyHandler implements SpigotHandler { + + @Override + public void handle(ByteArrayDataInput in, ServerInfo info) { + FightInfoHandler.addLobby(info); + } +} diff --git a/src/de/steamwar/bungeecore/comms/handlers/InventoryCallbackHandler.java b/src/de/steamwar/bungeecore/comms/handlers/InventoryCallbackHandler.java index 07d37b7..0fd90a6 100644 --- a/src/de/steamwar/bungeecore/comms/handlers/InventoryCallbackHandler.java +++ b/src/de/steamwar/bungeecore/comms/handlers/InventoryCallbackHandler.java @@ -27,6 +27,7 @@ import de.steamwar.bungeecore.inventory.InvCallback; import de.steamwar.bungeecore.inventory.SWInventory; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.config.ServerInfo; import java.util.HashMap; import java.util.Map; @@ -36,9 +37,9 @@ public class InventoryCallbackHandler implements SpigotHandler { public static final Map inventoryHashMap = new HashMap<>(); @Override - public void handle(ByteArrayDataInput byteArrayDataInput) { - SteamwarUser owner = SteamwarUser.get(byteArrayDataInput.readInt()); - CallbackType type = CallbackType.valueOf(byteArrayDataInput.readUTF()); + public void handle(ByteArrayDataInput in, ServerInfo info) { + SteamwarUser owner = SteamwarUser.get(in.readInt()); + CallbackType type = CallbackType.valueOf(in.readUTF()); if(!inventoryHashMap.containsKey(owner.getId())) { BungeeCore.send(ProxyServer.getInstance().getPlayer(owner.getUuid()), BungeeCore.CHAT_PREFIX + "§cBitte erneut versuchen. Durch ein Softwareupdate konnte die übliche Aktion nicht durchgeführt werden."); if(type == CallbackType.CLICK) { @@ -47,8 +48,8 @@ public class InventoryCallbackHandler implements SpigotHandler { return; } if(type == CallbackType.CLICK) { - int pos = byteArrayDataInput.readInt(); - InvCallback.ClickType clickType = InvCallback.ClickType.valueOf(byteArrayDataInput.readUTF()); + int pos = in.readInt(); + InvCallback.ClickType clickType = InvCallback.ClickType.valueOf(in.readUTF()); inventoryHashMap.get(owner.getId()).handleCallback(clickType, pos); }else if(type == CallbackType.CLOSE) { if(inventoryHashMap.get(owner.getId()).isNext()) { diff --git a/src/de/steamwar/bungeecore/comms/handlers/PrepareSchemHandler.java b/src/de/steamwar/bungeecore/comms/handlers/PrepareSchemHandler.java index 46d1a03..14171c5 100644 --- a/src/de/steamwar/bungeecore/comms/handlers/PrepareSchemHandler.java +++ b/src/de/steamwar/bungeecore/comms/handlers/PrepareSchemHandler.java @@ -27,14 +27,15 @@ import de.steamwar.bungeecore.comms.SpigotHandler; import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; public class PrepareSchemHandler implements SpigotHandler { @Override - public void handle(ByteArrayDataInput byteArrayDataInput) { - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(byteArrayDataInput.readInt()).getUuid()); - int schematicID = byteArrayDataInput.readInt(); - ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(byteArrayDataInput.readUTF())); + public void handle(ByteArrayDataInput in, ServerInfo info) { + ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(in.readInt()).getUuid()); + int schematicID = in.readInt(); + ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(in.readUTF())); BauCommand.stopBauserver(player); SubserverSystem.startTestServer(player, mode, mode.getRandomMap(), 0, schematicID); diff --git a/src/de/steamwar/bungeecore/comms/handlers/TablistNameHandler.java b/src/de/steamwar/bungeecore/comms/handlers/TablistNameHandler.java deleted file mode 100644 index 678d930..0000000 --- a/src/de/steamwar/bungeecore/comms/handlers/TablistNameHandler.java +++ /dev/null @@ -1,20 +0,0 @@ -package de.steamwar.bungeecore.comms.handlers; - -import com.google.common.io.ByteArrayDataInput; -import de.steamwar.bungeecore.Subserver; -import de.steamwar.bungeecore.comms.SpigotHandler; -import de.steamwar.bungeecore.sql.SteamwarUser; -import net.md_5.bungee.api.ProxyServer; -import net.md_5.bungee.api.connection.ProxiedPlayer; - -public class TablistNameHandler implements SpigotHandler { - - @Override - public void handle(ByteArrayDataInput byteArrayDataInput) { - ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(byteArrayDataInput.readInt()).getUuid()); - Subserver subserver = Subserver.getSubserver(player.getServer().getInfo()); - if(subserver == null) - return; - subserver.getTablistNames().put(player, byteArrayDataInput.readUTF()); - } -} diff --git a/src/de/steamwar/bungeecore/comms/packets/FightInfoPacket.java b/src/de/steamwar/bungeecore/comms/packets/FightInfoPacket.java new file mode 100644 index 0000000..34f120a --- /dev/null +++ b/src/de/steamwar/bungeecore/comms/packets/FightInfoPacket.java @@ -0,0 +1,183 @@ +/* + 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.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; +import de.steamwar.bungeecore.comms.BungeePacket; +import de.steamwar.bungeecore.comms.PacketIdManager; + +import java.util.ArrayList; +import java.util.List; + +public class FightInfoPacket extends BungeePacket { + + private String serverName; // Name of the Server + private final String gameMode; // GameMode aka Schematictype (if known, else "") + private final String arena; // Name of the arena + private final String blueName; // Name of the blue team, expected to begin with "§a" colorcode + private final String redName; // Name of the red team, expected to begin with "§a" colorcode + private final String fightState; // Fight state (technical term) (if known, else "") + private final int countdown; // Countdown state in seconds (if known, else 0) + private final int blueLeader; // SWUserID of the blue team leader (if known, else 0) + private final int redLeader; // SWUserID of the red team leader (if known, else 0) + private final int blueSchem; // Blue SchemID (if known, else 0) + private final int redSchem; // Red SchemID (if known, else 0) + private final List bluePlayers; // List of Blue SWUserIDs + private final List redPlayers; // List of Red SWUserIDs + private final List spectators; // List of Spectator SWUserIDs + + public FightInfoPacket(String serverName, String gameMode, String arena, String blueName, String redName, String fightState, int countdown, int blueLeader, int redLeader, int blueSchem, int redSchem, List bluePlayers, List redPlayers, List spectators) { + this.serverName = serverName; + this.gameMode = gameMode; + this.arena = arena; + this.blueName = blueName; + this.redName = redName; + this.fightState = fightState; + this.countdown = countdown; + this.blueLeader = blueLeader; + this.redLeader = redLeader; + this.blueSchem = blueSchem; + this.redSchem = redSchem; + this.bluePlayers = bluePlayers; + this.redPlayers = redPlayers; + this.spectators = spectators; + } + + public FightInfoPacket(ByteArrayDataInput in) { + this.serverName = in.readUTF(); + this.gameMode = in.readUTF(); + this.arena = in.readUTF(); + this.blueName = in.readUTF(); + this.redName = in.readUTF(); + this.fightState = in.readUTF(); + this.countdown = in.readInt(); + this.blueLeader = in.readInt(); + this.redLeader = in.readInt(); + this.blueSchem = in.readInt(); + this.redSchem = in.readInt(); + this.bluePlayers = readPlayerList(in); + this.redPlayers = readPlayerList(in); + this.spectators = readPlayerList(in); + } + + @Override + public int getId() { + return PacketIdManager.FIGHT_INFO; + } + + @Override + public void writeVars(ByteArrayDataOutput out) { + out.writeUTF(serverName); + out.writeUTF(gameMode); + out.writeUTF(arena); + out.writeUTF(blueName); + out.writeUTF(redName); + out.writeUTF(fightState); + out.writeInt(countdown); + out.writeInt(blueLeader); + out.writeInt(redLeader); + out.writeInt(blueSchem); + out.writeInt(redSchem); + writePlayerList(out, bluePlayers); + writePlayerList(out, redPlayers); + writePlayerList(out, spectators); + } + + public String getServerName() { + return serverName; + } + + public void setServerName(String serverName) { + this.serverName = serverName; + } + + public String getGameMode() { + return gameMode; + } + + public String getArena() { + return arena; + } + + public String getBlueName() { + return blueName; + } + + public String getRedName() { + return redName; + } + + public String getFightState() { + return fightState; + } + + public int getCountdown() { + return countdown; + } + + public int getBlueLeader() { + return blueLeader; + } + + public int getRedLeader() { + return redLeader; + } + + public int getBlueSchem() { + return blueSchem; + } + + public int getRedSchem() { + return redSchem; + } + + public List getBluePlayers() { + return bluePlayers; + } + + public List getRedPlayers() { + return redPlayers; + } + + public List getSpectators() { + return spectators; + } + + public int playerSize(){ + return bluePlayers.size() + redPlayers.size() + spectators.size(); + } + + private static List readPlayerList(ByteArrayDataInput in) { + int length = in.readInt(); + List players = new ArrayList<>(length); + for(int i = 0; i < length; i++) { + players.add(in.readInt()); + } + return players; + } + + private void writePlayerList(ByteArrayDataOutput out, List players) { + out.writeInt(players.size()); + for(Integer player : players) { + out.writeInt(player); + } + } +} diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 7c92736..9a0e5e3 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -26,13 +26,12 @@ import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Subserver; +import de.steamwar.bungeecore.comms.packets.FightInfoPacket; import de.steamwar.bungeecore.sql.SteamwarUser; -import de.steamwar.bungeecore.sql.Team; import de.steamwar.bungeecore.sql.UserGroup; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.event.EventHandler; @@ -42,21 +41,39 @@ import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; public class TablistManager extends BasicListener { private static final Map tablists = new HashMap<>(); - private int seconds = 0; - private Icon darkGray; - private Icon gray; + @EventHandler + public synchronized void onJoin(PostLoginEvent e){ + tablists.put(e.getPlayer(), new Tablist(e.getPlayer())); + } + @EventHandler + public synchronized void onLeave(PlayerDisconnectEvent e){ + tablists.remove(e.getPlayer()); + } + + + private static final Map fightInfos = new HashMap<>(); + + public static synchronized void newFightInfo(ServerInfo info, FightInfoPacket packet) { + fightInfos.put(info, packet); + fightInfos.keySet().removeIf(serverInfo -> serverInfo.getPlayers().isEmpty()); + } + + + private static Icon darkGray; + private static Icon gray; + + private int seconds = 0; private int size; - private final TreeMap> playerMap = new TreeMap<>(); + private TablistGroup tablist; public TablistManager(){ - ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::updateCustomTablist, 1, 1, TimeUnit.SECONDS); + ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::updateTablist, 1, 1, TimeUnit.SECONDS); try{ BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/dark_gray.png")), (icon) -> darkGray = icon); BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/gray.png")), (icon) -> gray = icon); @@ -69,61 +86,39 @@ public class TablistManager extends BasicListener { } } - private void calculateSize() { - size = -1; - size += playerMap.size() * 2 + ProxyServer.getInstance().getPlayers().size(); - size = (size + 19) / 20; - if(size > 5) size = 5; - } - - private synchronized void updateCustomTablist(){ + private synchronized void updateTablist(){ //Calculate server-player-map - playerMap.clear(); - for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { - Server pserver = player.getServer(); - if (pserver == null) //Happens temporarily + tablist = new TablistGroup(true, ""); + TablistGroup bau = new TablistGroup(false, "Bau"); + tablist.addSubTablist(bau); + for (ServerInfo server : ProxyServer.getInstance().getServers().values()){ + if(server.getPlayers().isEmpty()) continue; - ServerInfo server = pserver.getInfo(); - String serverName = server.getName(); - Subserver subserver = Subserver.getSubserver(server); - if (subserver != null && subserver.getType() == Servertype.BAUSERVER) { - playerMap.computeIfAbsent("Bau", s -> new ArrayList<>()).add(player); - } else { - playerMap.computeIfAbsent(serverName, s -> new ArrayList<>()).add(player); - } + if(subserver != null && subserver.getType() == Servertype.BAUSERVER) + bau.addSubTablist(new TablistServer(server)); + else if(fightInfos.containsKey(server)) + tablist.addSubTablist(new TablistServer(server, fightInfos.get(server))); + else + tablist.addSubTablist(new TablistServer(server)); } - playerMap.forEach((server, players) -> players.sort((proxiedPlayer, t1) -> proxiedPlayer.getName().compareToIgnoreCase(t1.getName()))); - - //Set size - calculateSize(); - - for(Tablist tablist : tablists.values()) - tablist.refresh(); + size = (int) Math.ceil(tablist.size() / 20.0); + tablists.values().forEach(Tablist::refresh); seconds++; } - @EventHandler - public synchronized void onJoin(PostLoginEvent e){ - tablists.put(e.getPlayer(), new Tablist(e.getPlayer())); - } - - @EventHandler - public synchronized void onLeave(PlayerDisconnectEvent e){ - tablists.remove(e.getPlayer()); - } - private class Tablist extends DefaultCustomTablist { private final ProxiedPlayer player; + private int pos = 0; private Tablist(ProxiedPlayer player){ this.player = player; BungeeTabListPlusAPI.setCustomTabList(player, this); } - private String calcHeader(ProxiedPlayer player){ + private String header(){ int phase = (seconds % 16) / 3; switch(phase){ case 0: @@ -136,7 +131,7 @@ public class TablistManager extends BasicListener { } } - private String getPing(){ + private String ping(){ int ping = player.getPing(); if(ping < 50){ return "§a" + ping; @@ -151,126 +146,163 @@ public class TablistManager extends BasicListener { if (player.getServer() == null) { return; } - ServerInfo currentServer = player.getServer().getInfo(); - setHeader(calcHeader(player)); - // TABLIST_FOOTER=§e{0} {1}§8ms §eSpieler§8: §7{2} - setFooter("§e" + currentServer.getName() + " " + getPing() + "§8ms §eSpieler§8: §7" + ProxyServer.getInstance().getPlayers().size()); - setSize(size, 20); + pos = 0; + setHeader(header()); + setFooter("§e" + player.getServer().getInfo().getName() + " " + ping() + "§8ms §eSpieler§8: §7" + ProxyServer.getInstance().getPlayers().size()); + int currentSize = size > 4 ? tablist.slimSize(player) : size; + setSize(currentSize, 20); - if (size >= 5) { - refreshSlim(currentServer); - return; - } + tablist.print(this, size > 4); - try { - int i = 0; - for (String server : playerMap.navigableKeySet()) { - if (i > 0){ - setSlot(i%20, i/20, darkGray, "", 1000); - i++; - } - if(server.equals("Bau")) - server = Message.parse("TABLIST_BAU", player); - setSlot(i%20, i/20, gray, "§7§l" + server, 1000); - i++; - i = update(currentServer, playerMap.get(server), i); - } - - finish(i); - }catch(IndexOutOfBoundsException | NullPointerException e){ - //Ignore IndexOutOfBoundsException - //Ignore NPE, happens sometimes (only 1s long) when somebody is joining, server switching or disconnecting + while (pos < currentSize*20){ + setSlot(darkGray, "", 1000); } } - private void refreshSlim(ServerInfo currentServer) { - try { - int i = 0; - boolean spacer = true; - for (String server : playerMap.navigableKeySet()) { - if (i > 0 && spacer) { - setSlot(i%20, i/20, darkGray, "", 1000); - i++; - } - spacer = true; - Team team = getTeam(player); - List players = playerMap.get(server) - .stream() - .filter(p -> (p.getServer() != null && p.getServer().getInfo() == currentServer) || SteamwarUser.get(p).getUserGroup() != UserGroup.Member || (team != null && team == getTeam(p))) - .collect(Collectors.toList()); + private void setSlot(Icon icon, String name, int ping){ + setSlot(pos % 20, pos / 20, icon, name, ping); + pos++; + } + } - Subserver subserver = Subserver.getSubserver(player); - if (server.equals("Bau")) { - if (subserver != null && subserver.getType() == Servertype.BAUSERVER) { - players = playerMap.get(server); - } - server = Message.parse("TABLIST_BAU", player); - } - if (subserver != null && subserver.getType() == Servertype.ARENA && playerMap.get(server).size() == 1) { - players = playerMap.get(server); - } + private interface TablistPart { + int size(); + int slimSize(ProxiedPlayer viewer); + String name(); + void print(Tablist viewer, boolean slim); + } - int increment = playerMap.get(server).size() - players.size(); - if (players.isEmpty()) { - server += " §7(" + increment + ")"; - spacer = false; - } else if (increment != 0) { - server += " §7(+" + increment + ")"; - } + private static class TablistGroup implements TablistPart { - setSlot(i%20, i/20, gray, "§7§l" + server, 1000); - i++; - i = update(currentServer, players, i); - } + private final boolean withHeaders; + private final String orderName; + private final List subTablists = new ArrayList<>(); - finish(i); - }catch(IndexOutOfBoundsException | NullPointerException e){ - //Ignore IndexOutOfBoundsException - //Ignore NPE, happens sometimes (only 1s long) when somebody is joining, server switching or disconnecting - } + private TablistGroup(boolean withHeaders, String orderName) { + this.withHeaders = withHeaders; + this.orderName = orderName; } - private int update(ServerInfo currentServer, List players, int i) { - for (ProxiedPlayer p : players){ - boolean sameServer = currentServer == p.getServer().getInfo(); - setSlot(i % 20, i / 20, BungeeTabListPlusAPI.getIconFromPlayer(p), getTablistName(p), (sameServer ? 1 : 500)); - i++; - } - return i; + private void addSubTablist(TablistPart tablist){ + subTablists.add(tablist); + subTablists.sort((t1, t2) -> t1.name().compareToIgnoreCase(t2.name())); } - private void finish(int i) { - while (i < size*20){ - setSlot(i%20, i/20, darkGray, "", 1000); - i++; - } + @Override + public int size() { + int size = subTablists.stream().map(TablistPart::size).reduce(Integer::sum).orElse(0); + if(withHeaders) + size += Math.min(subTablists.size() - 1, 0); + return size; } - private Team getTeam(ProxiedPlayer p) { - Team team = Team.get(SteamwarUser.get(p).getTeam()); - return team.getTeamId() <= 0 ? null : team; + @Override + public int slimSize(ProxiedPlayer viewer) { + int size = subTablists.stream().map(tablist -> tablist.slimSize(viewer)).reduce(Integer::sum).orElse(0); + if(withHeaders) + size += Math.min(subTablists.size() - 1, 0); + return size; } - private String getTablistName(ProxiedPlayer p) { - Subserver server = Subserver.getSubserver(p); - if(server != null){ - String tablistName = server.getTablistNames().get(p); - if(tablistName != null) - return tablistName; + @Override + public String name() { + return orderName; + } + + @Override + public void print(Tablist viewer, boolean slim) { + subTablists.forEach(tablist -> { + if(withHeaders) + viewer.setSlot(gray, "§l" + tablist.name(), 1000); + tablist.print(viewer, slim); + if(withHeaders) + viewer.setSlot(darkGray, "", 1000); + }); + } + } + + private static class TablistServer implements TablistPart { + private static class TablistPlayer { + private final ProxiedPlayer player; + private final String defaultName; + + private TablistPlayer(ProxiedPlayer player, String defaultName) { + this.player = player; + this.defaultName = defaultName; } + } + private final List players = new ArrayList<>(); + private final ServerInfo info; + private final Subserver subserver; - StringBuilder st = new StringBuilder(); - UserGroup group = SteamwarUser.get(p).getUserGroup(); + private TablistServer(ServerInfo info, FightInfoPacket packet){ + this.info = info; + subserver = Subserver.getSubserver(info); + Collection onlinePlayers = info.getPlayers(); + addPlayers(packet.getBlueName().substring(0, 2), packet.getBluePlayers(), onlinePlayers); + addPlayers(packet.getRedName().substring(0, 2), packet.getRedPlayers(), onlinePlayers); + addPlayers("§7", packet.getSpectators(), onlinePlayers); + } - if (group == UserGroup.Member) { - Team team = getTeam(player); - if (team != null && team == getTeam(p)) st.append("§f"); - else st.append("§7"); - } else { - st.append(group.getColorCode()); + private void addPlayers(String prefix, List teamPlayers, Collection onlinePlayers){ + teamPlayers.stream().map(SteamwarUser::get).map( + user -> onlinePlayers.stream().filter(player -> player.getUniqueId().equals(user.getUuid())).findAny() + ).filter(Optional::isPresent).map(Optional::get).sorted( + (p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName()) + ).forEachOrdered(player -> players.add(new TablistPlayer(player, prefix + player.getName()))); + } + + private TablistServer(ServerInfo info) { + this.info = info; + subserver = Subserver.getSubserver(info); + for(ProxiedPlayer player : info.getPlayers()){ + players.add(new TablistPlayer(player, SteamwarUser.get(player.getUniqueId()).getUserGroup().getColorCode() + player.getName())); } + players.sort((tp1, tp2) -> tp1.player.getName().compareToIgnoreCase(tp2.player.getName())); + } - return st.append(p.getName()).toString(); + private boolean displaySlim(ProxiedPlayer viewer, ProxiedPlayer player){ + if(subserver != null && subserver.getType() == Servertype.ARENA && info.getPlayers().size() == 1) + return true; + + SteamwarUser user = SteamwarUser.get(player); + if(user.getUserGroup() != UserGroup.Member) + return true; + + return user.getTeam() != 0 && SteamwarUser.get(viewer).getTeam() == user.getTeam(); + } + + @Override + public int size() { + return 1 + players.size(); + } + + @Override + public int slimSize(ProxiedPlayer viewer) { + if(viewer.getServer().getInfo() == info) + return size(); + + int size = 1; + for(TablistPlayer player : players) + size += displaySlim(viewer, player.player) ? 1 : 0; + return size; + } + + @Override + public String name() { + return info.getName(); + } + + @Override + public void print(Tablist viewer, boolean slim) { + boolean sameServer = viewer.player.getServer().getInfo() == info; + + for(TablistPlayer player : players){ + if(sameServer) + viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 1); + else if(!slim || displaySlim(viewer.player, player.player)) + viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName, 500); + } } } } From 47291dff2740776802230f56e916122462d9ab98 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 21 Aug 2021 19:00:27 +0200 Subject: [PATCH 04/83] Team highlightning Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 9a0e5e3..f82a05c 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -297,8 +297,9 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { boolean sameServer = viewer.player.getServer().getInfo() == info; + SteamwarUser user = SteamwarUser.get(viewer.player.getUniqueId()); for(TablistPlayer player : players){ - if(sameServer) + if(sameServer || (user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam())) viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 1); else if(!slim || displaySlim(viewer.player, player.player)) viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName, 500); From cf436006448e7d2788cbdbbf2449adbf7935e8ce Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Fri, 27 Aug 2021 18:59:54 +0200 Subject: [PATCH 05/83] Fixing Signed-off-by: Chaoscaot --- .../bungeecore/bot/util/DiscordSchemAlert.java | 10 +++++----- .../steamwar/bungeecore/commands/CheckCommand.java | 14 +++++++------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java b/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java index b4b4261..f0d9d7b 100644 --- a/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java +++ b/src/de/steamwar/bungeecore/bot/util/DiscordSchemAlert.java @@ -20,7 +20,7 @@ package de.steamwar.bungeecore.bot.util; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; -import de.steamwar.bungeecore.sql.Schematic; +import de.steamwar.bungeecore.sql.SchematicNode; import de.steamwar.bungeecore.sql.SteamwarUser; import lombok.experimental.UtilityClass; import net.dv8tion.jda.api.EmbedBuilder; @@ -36,14 +36,14 @@ import java.time.Instant; @UtilityClass public class DiscordSchemAlert { - public void sendDecline(Schematic schematic, SteamwarUser user, String reason) { + public void sendDecline(SchematicNode schematic, SteamwarUser user, String reason) { if(user.getDiscordId() != null) { User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete(); EmbedBuilder builder = new EmbedBuilder(); builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png"); builder.setColor(Color.RED); builder.setTitle("SteamWar-Schematic Info"); - builder.setDescription("Deine Schematic **" + schematic.getSchemName() + "** wurde abgelehnt. **Grund:** \n" + reason); + builder.setDescription("Deine Schematic **" + schematic.getName() + "** wurde abgelehnt. **Grund:** \n" + reason); builder.setTimestamp(Instant.now()); MessageBuilder messageBuilder = new MessageBuilder(); @@ -56,14 +56,14 @@ public class DiscordSchemAlert { } } - public void sendAccept(Schematic schematic, SteamwarUser user) { + public void sendAccept(SchematicNode schematic, SteamwarUser user) { if(user.getDiscordId() != null) { User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete(); EmbedBuilder builder = new EmbedBuilder(); builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png"); builder.setColor(Color.GREEN); builder.setTitle("SteamWar-Schematic Info"); - builder.setDescription("Deine Schematic **" + schematic.getSchemName() + "** wurde angenommen."); + builder.setDescription("Deine Schematic **" + schematic.getName() + "** wurde angenommen."); builder.setTimestamp(Instant.now()); MessageBuilder messageBuilder = new MessageBuilder(); diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index 3144161..dde381b 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -121,9 +121,9 @@ public class CheckCommand extends BasicCommand { return schematicList; } - public static String getChecker(Schematic schematic) { - if (currentSchems.get(schematic.getSchemID()) == null) return null; - return currentSchems.get(schematic.getSchemID()).checker.getName(); + public static String getChecker(SchematicNode schematic) { + if (currentSchems.get(schematic.getId()) == null) return null; + return currentSchems.get(schematic.getId()).checker.getName(); } private void list(ProxiedPlayer player) { @@ -295,11 +295,11 @@ public class CheckCommand extends BasicCommand { SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) { - Message.send("CHECK_ACCEPTED", player, schematic.getSchemType().name(), schematic.getSchemName()); + Message.send("CHECK_ACCEPTED", player, schematic.getSchemtype().name(), schematic.getName()); } else { DiscordSchemAlert.sendAccept(schematic, user); } - Message.team("CHECK_ACCEPTED_TEAM", schematic.getSchemName(), user.getUserName()); + Message.team("CHECK_ACCEPTED_TEAM", schematic.getName(), user.getUserName()); stop(); } @@ -309,11 +309,11 @@ public class CheckCommand extends BasicCommand { SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) { - Message.send("CHECK_DECLINED", player, schematic.getSchemType().name(), schematic.getSchemName(), reason); + Message.send("CHECK_DECLINED", player, schematic.getSchemtype().name(), schematic.getName(), reason); } else { DiscordSchemAlert.sendDecline(schematic, user, reason); } - Message.team("CHECK_DECLINED_TEAM", schematic.getSchemName(), user.getUserName(), reason); + Message.team("CHECK_DECLINED_TEAM", schematic.getName(), user.getUserName(), reason); stop(); } From 6490ce28488015f777c6aa431b7b844a0fe0e9ac Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Wed, 8 Sep 2021 13:51:42 +0200 Subject: [PATCH 06/83] 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 7d8b005..a2facf0 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 67c3596..e09bbc8 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 eb4aaaf4348132709354b59d0c2e684201f6953a Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 16 Sep 2021 13:10:00 +0200 Subject: [PATCH 07/83] 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 7dee2ca..6609324 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 5f4ab53..23c00cf 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 08/83] 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 7dee2ca..c3bf994 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 59fda6c..0000000 --- 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 0000000..5edcd06 --- /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 d5e85b0..018c8a3 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 e827427..2965f08 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 1488dbf..ade3705 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 31cb6cc..5d32af1 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 09/83] 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 c3bf994..e438000 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 5edcd06..cb34986 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 10/83] 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 a2facf0..ac4f553 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 e09bbc8..2643d62 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 11/83] 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 cb34986..f0afc09 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 12/83] 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 f0afc09..d63093d 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 ade3705..b633fb5 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 13/83] 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 d63093d..5336491 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 14/83] 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 5336491..ea0a2ed 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 15/83] 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 23c00cf..8e357eb 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 16/83] 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 8e357eb..e20a704 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 17/83] 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 e20a704..4bfe84c 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 eac7650..c37538b 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 3cfd3f5beb6200eed20b8a2d4e7c3147278b98c5 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sun, 26 Sep 2021 23:34:15 +0200 Subject: [PATCH 18/83] Update Punishment system Simplify Punishment code overhead --- src/de/steamwar/bungeecore/BungeeCore.java | 8 + .../bungeecore/bot/commands/BanCommand.java | 6 +- .../bungeecore/bot/commands/MuteCommand.java | 7 +- .../bungeecore/bot/commands/UnbanCommand.java | 5 +- .../bot/listeners/IngameChatListener.java | 3 +- .../bungeecore/commands/BanCommand.java | 85 ----------- .../bungeecore/commands/MsgCommand.java | 5 +- .../bungeecore/commands/MuteCommand.java | 57 -------- .../commands/PunishmentCommand.java | 108 ++++++++++++++ .../bungeecore/commands/RCommand.java | 5 +- .../bungeecore/commands/UnbanCommand.java | 54 ------- .../bungeecore/listeners/BanListener.java | 6 +- .../bungeecore/listeners/ChatListener.java | 10 +- .../bungeecore/listeners/mods/Utils.java | 5 +- .../steamwar/bungeecore/sql/Punishment.java | 46 +++--- .../steamwar/bungeecore/sql/SteamwarUser.java | 138 ++++++++---------- .../steamwar/messages/BungeeCore.properties | 46 ++++-- 17 files changed, 261 insertions(+), 333 deletions(-) delete mode 100644 src/de/steamwar/bungeecore/commands/BanCommand.java delete mode 100644 src/de/steamwar/bungeecore/commands/MuteCommand.java create mode 100644 src/de/steamwar/bungeecore/commands/PunishmentCommand.java delete mode 100644 src/de/steamwar/bungeecore/commands/UnbanCommand.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 0b71cb5..2a725a6 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -20,6 +20,9 @@ package de.steamwar.bungeecore; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; +import de.steamwar.bungeecore.bot.commands.BanCommand; +import de.steamwar.bungeecore.bot.commands.MuteCommand; +import de.steamwar.bungeecore.bot.commands.UnbanCommand; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.commands.*; import de.steamwar.bungeecore.comms.SpigotReceiver; @@ -28,6 +31,7 @@ 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.Punishment; import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; @@ -130,6 +134,10 @@ public class BungeeCore extends Plugin { new StatCommand(); new VerifyCommand(); + // Punishment Commands: + new PunishmentCommand("ban", Punishment.PunishmentType.Ban); + new PunishmentCommand("mute", Punishment.PunishmentType.Mute); + if(!EVENT_MODE){ new BauCommand(); new WebregisterCommand(); diff --git a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java index e55b97e..5e06cb6 100644 --- a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java @@ -20,6 +20,8 @@ package de.steamwar.bungeecore.bot.commands; import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.commands.PunishmentCommand; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -49,7 +51,7 @@ public class BanCommand extends BasicDiscordCommand { return; } - Timestamp time = de.steamwar.bungeecore.commands.BanCommand.parseTime(null, event.getOption("time").getAsString()); + Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString()); if (time == null) { event.reply("Angegebene Zeit invalide").setEphemeral(true).queue(); return; @@ -58,7 +60,7 @@ public class BanCommand extends BasicDiscordCommand { String msg = event.getOption("reason").getAsString(); boolean isPerma = event.getOption("time").getAsString().equals("perma"); - target.ban(time, msg, sender.getId(), isPerma); + target.punish(Punishment.PunishmentType.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).queue(); } diff --git a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java index 1c0bc96..7847316 100644 --- a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java @@ -20,7 +20,8 @@ package de.steamwar.bungeecore.bot.commands; import de.steamwar.bungeecore.Message; -import de.steamwar.bungeecore.commands.BanCommand; +import de.steamwar.bungeecore.commands.PunishmentCommand; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -50,7 +51,7 @@ public class MuteCommand extends BasicDiscordCommand { return; } - Timestamp time = BanCommand.parseTime(null, event.getOption("time").getAsString()); + Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString()); if (time == null) { event.reply("Angegebene Zeit invalide").setEphemeral(true).complete(); return; @@ -59,7 +60,7 @@ public class MuteCommand extends BasicDiscordCommand { String msg = event.getOption("reason").getAsString(); boolean isPerma = event.getOption("time").getAsString().equals("perma"); - target.mute(time, msg, sender.getId(), isPerma); + target.punish(Punishment.PunishmentType.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).queue(); } diff --git a/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java b/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java index 925423f..f8d6185 100644 --- a/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/UnbanCommand.java @@ -19,6 +19,7 @@ package de.steamwar.bungeecore.bot.commands; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -47,12 +48,12 @@ public class UnbanCommand extends BasicDiscordCommand { return; } - if (!target.isBanned()) { + if (!target.isPunished(Punishment.PunishmentType.Ban)) { event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).queue(); return; } - target.ban(Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false); + target.punish(Punishment.PunishmentType.Ban, Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false); event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java index 7163985..e7b709d 100644 --- a/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java +++ b/src/de/steamwar/bungeecore/bot/listeners/IngameChatListener.java @@ -22,6 +22,7 @@ package de.steamwar.bungeecore.bot.listeners; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.listeners.ChatListener; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.UserGroup; import net.dv8tion.jda.api.MessageBuilder; @@ -50,7 +51,7 @@ public class IngameChatListener extends BasicDiscordListener { event.getMessage().delete().queue(); return; } - if (steamwarUser.isMuted() || steamwarUser.isBanned()) { + if (steamwarUser.isPunished(Punishment.PunishmentType.Mute) || steamwarUser.isPunished(Punishment.PunishmentType.Ban)) { event.getMessage().delete().queue(); return; } diff --git a/src/de/steamwar/bungeecore/commands/BanCommand.java b/src/de/steamwar/bungeecore/commands/BanCommand.java deleted file mode 100644 index 1b3f38d..0000000 --- a/src/de/steamwar/bungeecore/commands/BanCommand.java +++ /dev/null @@ -1,85 +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.commands; - -import de.steamwar.bungeecore.Message; -import de.steamwar.bungeecore.sql.SteamwarUser; -import net.md_5.bungee.api.CommandSender; - -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.Date; - -public class BanCommand extends BasicCommand { - - public BanCommand() { - super("ban", "bungeecore.ban"); - } - - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length < 3){ - Message.send("USAGE_BAN", sender); - return; - } - - SteamwarUser target = unsafeUser(sender, args[0]); - if(target == null) - return; - - Timestamp banTime = parseTime(sender, args[1]); - if(banTime == null) - return; - - StringBuilder banReason = new StringBuilder(); - for (int i = 2; i < args.length; i++){ - banReason.append(args[i]).append(" "); - } - boolean isPerma = args[1].equalsIgnoreCase("perma"); - String msg = banReason.toString(); - target.ban(banTime, msg, SteamwarUser.get(sender.getName()).getId(), isPerma); - Message.team("BAN_TEAM_BANNED", new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((isPerma?"BAN_PERMA":"BAN_UNTIL"), banTime), msg); - } - - public static Timestamp parseTime(CommandSender sender, String arg){ - if(arg.equalsIgnoreCase("perma")) { - return Timestamp.from(Instant.ofEpochSecond(946674800)); - }else{ - SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy_HH:mm"); - try{ - Date parsedDate = dateFormat.parse(arg); - return new java.sql.Timestamp(parsedDate.getTime()); - }catch(ParseException e){ - dateFormat = new SimpleDateFormat("dd.MM.yyyy"); - try{ - Date parsedDate = dateFormat.parse(arg.split("_")[0]); - return new java.sql.Timestamp(parsedDate.getTime()); - }catch(ParseException exception){ - if (sender != null) { - Message.send("INVALID_TIME", sender); - } - return null; - } - } - } - } -} diff --git a/src/de/steamwar/bungeecore/commands/MsgCommand.java b/src/de/steamwar/bungeecore/commands/MsgCommand.java index 8ec0d38..13dbb27 100644 --- a/src/de/steamwar/bungeecore/commands/MsgCommand.java +++ b/src/de/steamwar/bungeecore/commands/MsgCommand.java @@ -22,6 +22,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.IgnoreSystem; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; @@ -48,8 +49,8 @@ public class MsgCommand extends BasicCommand { } SteamwarUser user = SteamwarUser.get(player); - if(user.isMuted()){ - sender.sendMessage(user.muteMessage(player)); + if (user.isPunished(Punishment.PunishmentType.Mute)) { + sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, player)); return; } diff --git a/src/de/steamwar/bungeecore/commands/MuteCommand.java b/src/de/steamwar/bungeecore/commands/MuteCommand.java deleted file mode 100644 index 9ecfde1..0000000 --- a/src/de/steamwar/bungeecore/commands/MuteCommand.java +++ /dev/null @@ -1,57 +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.commands; - -import de.steamwar.bungeecore.Message; -import de.steamwar.bungeecore.sql.SteamwarUser; -import net.md_5.bungee.api.CommandSender; - -import java.sql.Timestamp; - -public class MuteCommand extends BasicCommand { - - public MuteCommand() { - super("mute", "bungeecore.ban"); - } - - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length < 3){ - Message.send("USAGE_MUTE", sender); - return; - } - - SteamwarUser target = unsafeUser(sender, args[0]); - if(target == null) - return; - - Timestamp muteTime = BanCommand.parseTime(sender, args[1]); - if(muteTime == null) - return; - - StringBuilder muteReason = new StringBuilder(); - for (int i = 2; i < args.length; i++){ - muteReason.append(args[i]).append(" "); - } - String msg = muteReason.toString(); - target.mute(muteTime, msg, SteamwarUser.get(sender.getName()).getId(), args[1].equalsIgnoreCase("perma")); - Message.team("MUTE_TEAM_MUTED", new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((args[1].equalsIgnoreCase("perma")?"BAN_PERMA":"BAN_UNTIL"), muteTime), msg); - } -} diff --git a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java new file mode 100644 index 0000000..6f425c1 --- /dev/null +++ b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java @@ -0,0 +1,108 @@ +/* + * 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.commands; + +import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.sql.Punishment; +import de.steamwar.bungeecore.sql.SteamwarUser; +import net.md_5.bungee.api.CommandSender; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; + +public class PunishmentCommand { + + public PunishmentCommand(String command, Punishment.PunishmentType punishmentType) { + new BasicCommand(command, "bungeecore.ban") { + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length < 3) { + Message.send("PUNISHMENT_USAGE", sender, command); + return; + } + + SteamwarUser target = unsafeUser(sender, args[0]); + if (target == null) + return; + + Timestamp banTime = parseTime(sender, args[1]); + if (banTime == null) + return; + + StringBuilder reason = new StringBuilder(); + for (int i = 2; i < args.length; i++) { + reason.append(args[i]).append(" "); + } + boolean isPerma = args[1].equalsIgnoreCase("perma"); + String msg = reason.toString(); + target.punish(punishmentType, banTime, msg, SteamwarUser.get(sender.getName()).getId(), isPerma); + Message.team(punishmentType.getTeamMessage(), new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((isPerma ? "PUNISHMENT_PERMA" : "PUNISHMENT_UNTIL"), banTime), msg); + } + }; + String antiCommand = "un" + command; + new BasicCommand(antiCommand, "bungeecore.ban") { + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length < 1) { + Message.send("UNPUNISHMENT_USAGE", sender, antiCommand); + return; + } + + SteamwarUser target = existingUser(sender, args[0]); + if (target == null) + return; + + if (!target.isPunished(punishmentType)) { + Message.send(punishmentType.getUsageNotPunished(), sender); + return; + } + + Message.send(punishmentType.getUnpunishmentMessage(), sender, target.getUserName()); + target.punish(punishmentType, Timestamp.from(new Date().toInstant()), antiCommand, SteamwarUser.get(sender.getName()).getId(), false); + } + }; + } + + public static Timestamp parseTime(CommandSender sender, String arg) { + if (arg.equalsIgnoreCase("perma")) { + return Timestamp.from(Instant.ofEpochSecond(946674800)); + } else { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy_HH:mm"); + try { + Date parsedDate = dateFormat.parse(arg); + return new java.sql.Timestamp(parsedDate.getTime()); + } catch (ParseException e) { + dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + try { + Date parsedDate = dateFormat.parse(arg.split("_")[0]); + return new java.sql.Timestamp(parsedDate.getTime()); + } catch (ParseException exception) { + if (sender != null) { + Message.send("INVALID_TIME", sender); + } + return null; + } + } + } + } +} diff --git a/src/de/steamwar/bungeecore/commands/RCommand.java b/src/de/steamwar/bungeecore/commands/RCommand.java index fef0031..7a208db 100644 --- a/src/de/steamwar/bungeecore/commands/RCommand.java +++ b/src/de/steamwar/bungeecore/commands/RCommand.java @@ -22,6 +22,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.IgnoreSystem; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -44,8 +45,8 @@ public class RCommand extends BasicCommand { } SteamwarUser user = SteamwarUser.get(player); - if(user.isMuted()){ - sender.sendMessage(user.muteMessage(player)); + if (user.isPunished(Punishment.PunishmentType.Mute)) { + sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, player)); return; } diff --git a/src/de/steamwar/bungeecore/commands/UnbanCommand.java b/src/de/steamwar/bungeecore/commands/UnbanCommand.java deleted file mode 100644 index 176029a..0000000 --- a/src/de/steamwar/bungeecore/commands/UnbanCommand.java +++ /dev/null @@ -1,54 +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.commands; - -import de.steamwar.bungeecore.Message; -import de.steamwar.bungeecore.sql.SteamwarUser; -import net.md_5.bungee.api.CommandSender; - -import java.sql.Timestamp; -import java.util.Date; - -public class UnbanCommand extends BasicCommand { - - public UnbanCommand() { - super("unban", "bungeecore.ban"); - } - - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length < 1){ - Message.send("UNBAN_USAGE", sender); - return; - } - - SteamwarUser target = existingUser(sender, args[0]); - if(target == null) - return; - - if(!target.isBanned()) { - Message.send("UNBAN_NOT_BANNED", sender); - return; - } - - Message.send("UNBAN_UNBANNED", sender, target.getUserName()); - target.ban(Timestamp.from(new Date().toInstant()), "Unban", SteamwarUser.get(sender.getName()).getId(), false); - } -} diff --git a/src/de/steamwar/bungeecore/listeners/BanListener.java b/src/de/steamwar/bungeecore/listeners/BanListener.java index 2daabde..195cc19 100644 --- a/src/de/steamwar/bungeecore/listeners/BanListener.java +++ b/src/de/steamwar/bungeecore/listeners/BanListener.java @@ -41,10 +41,10 @@ public class BanListener extends BasicListener { @EventHandler public void onLogin(LoginEvent event) { SteamwarUser user = SteamwarUser.getOrCreate(event.getConnection()); - if(user.isBanned()) { + if (user.isPunished(Punishment.PunishmentType.Ban)) { user.updateBanIP(event.getConnection().getAddress().getAddress().getHostAddress()); event.setCancelled(true); - event.setCancelReason(user.banMessage(ProxyServer.getInstance().getPlayer(event.getConnection().getUniqueId()))); + event.setCancelReason(user.punishmentMessage(Punishment.PunishmentType.Ban, ProxyServer.getInstance().getPlayer(event.getConnection().getUniqueId()))); return; } @@ -55,7 +55,7 @@ public class BanListener extends BasicListener { boolean perma = false; for(BannedUserIPs banned : ips) { SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID()); - if(bannedUser.isBanned()) { + if (bannedUser.isPunished(Punishment.PunishmentType.Ban)) { Punishment ban = bannedUser.getPunishment(Punishment.PunishmentType.Ban); if(ban.isPerma()) { perma = true; diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index e0e4472..a371a2e 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -21,9 +21,9 @@ 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.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; import de.steamwar.bungeecore.sql.UserGroup; @@ -145,8 +145,8 @@ public class ChatListener extends BasicListener { } SteamwarUser user = SteamwarUser.get(sender); - if(user.isMuted()){ - sender.sendMessage(user.muteMessage(sender)); + if (user.isPunished(Punishment.PunishmentType.Mute)) { + sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, sender)); e.setCancelled(true); return; } @@ -224,8 +224,8 @@ public class ChatListener extends BasicListener { } SteamwarUser user = SteamwarUser.get(sender); - if(user.isMuted()){ - sender.sendMessage(user.muteMessage(sender)); + if (user.isPunished(Punishment.PunishmentType.Mute)) { + sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, sender)); e.setCancelled(true); return; } diff --git a/src/de/steamwar/bungeecore/listeners/mods/Utils.java b/src/de/steamwar/bungeecore/listeners/mods/Utils.java index e6907c5..9ed160a 100644 --- a/src/de/steamwar/bungeecore/listeners/mods/Utils.java +++ b/src/de/steamwar/bungeecore/listeners/mods/Utils.java @@ -23,6 +23,7 @@ import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.Mod; import de.steamwar.bungeecore.sql.Mod.ModType; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -75,7 +76,7 @@ class Utils { if(max == ModType.YELLOW) player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_SING", player, mods.get(0).getModName()))); else{ - user.ban(Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_SING", player, mods.get(0).getModName()), 0, false); + user.punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_SING", player, mods.get(0).getModName()), 0, false); BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen des Mods " + mods.get(0).getModName() + " gebannt."); } }else{ @@ -85,7 +86,7 @@ class Utils { if(max == ModType.YELLOW) player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_PLUR", player, sb.toString()))); else{ - user.ban(Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_PLUR", player, sb.toString()), 0, false); + user.punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_PLUR", player, sb.toString()), 0, false); BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + sb.toString() + " gebannt."); } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index 914e6b8..0bd0962 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -19,9 +19,8 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; -import de.steamwar.bungeecore.Message; -import net.md_5.bungee.api.connection.ProxiedPlayer; +import lombok.AllArgsConstructor; +import lombok.Getter; import java.sql.ResultSet; import java.sql.SQLException; @@ -39,7 +38,7 @@ public class Punishment { public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { return getPunishment.select(rs -> { - if(rs.next()) + if (rs.next()) return new Punishment(rs); return null; }, user, type.name()); @@ -116,35 +115,34 @@ public class Punishment { return perma; } - public void updateEndTime(int from, String newreason, Timestamp newUpdate, boolean 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, - SteamwarUser.get(from).getUserName(), - getBantime(endTime, this.perma), - getBantime(newUpdate, perma), - newreason); - - update.update(newUpdate, newReason, perma, id); - this.reason = newReason; - this.perma = perma; - this.endTime = newUpdate; - } - public String getBantime(Timestamp endTime, boolean perma) { - if(perma) + if (perma) { return "permanent"; - else + } else { return endTime.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")); + } } public boolean isCurrent() { return isPerma() || getEndTime().after(new Date()); } + @AllArgsConstructor + @Getter public enum PunishmentType { - Ban, - Mute; + Ban("BAN_TEAM_BANNED", "BANNED_MESSAGE_PERMA", "BANNED_MESSAGE_UNTIL", "UNBAN_NOT_BANNED", "UNBAN_UNBANNED"), + Mute( "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), + AntiSchemAdd("ANTISCHEMADD_TEAM_ANTISCHEMADD", "ANTISCHEMADD_MESSAGE_PERMA", "ANTISCHEMADD_MESSAGE_UNTIL", "UNANTISCHEMADD_NOT_ANTISCHEMADD", "UNANTISCHEMADD_UNANTISCHEMADDED"), + AntiSchemAdded("ANTISCHEMADDED_TEAM_ANTISCHEMADDED", "ANTISCHEMADDED_MESSAGE_PERMA", "ANTISCHEMADDED_MESSAGE_UNTIL", "UNANTISCHEMADDED_NOT_ANTISCHEMADDED", "UNANTISCHEMADDED_UNANTISCHEMADDED"), + // AntiSchemDownload("UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED"), + // AntiSchemUpload("UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED"), + // AntiBauJoin("UNANTIBAUJOIN_NOT_ANTIBAUJOINED"); + ; + + private String teamMessage; + private String playerMessagePerma; + private String playerMessageUntil; + private String usageNotPunished; + private String unpunishmentMessage; } } diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 67c3596..f83d76c 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -97,25 +97,27 @@ public class SteamwarUser { 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); } - public static SteamwarUser getOrCreate(PendingConnection connection){ + public static SteamwarUser getOrCreate(PendingConnection connection) { SteamwarUser user = SteamwarUser.get(connection.getUniqueId()); - if(user != null){ + if (user != null) { String userName = connection.getName(); - if(!user.userName.equals(userName)){ + if (!user.userName.equals(userName)) { updateName.update(userName, user.id); WebregisterCommand.changeUsername(user.userName, userName); user.userName = userName; } - }else{ + } else { user = SteamwarUser.createUserInDatabase(connection.getUniqueId(), connection.getName()); - if(user == null) + if (user == null) { throw new SecurityException("user == null"); + } ConnectionListener.newPlayer(user.uuid); } @@ -124,7 +126,7 @@ public class SteamwarUser { return user; } - public static SteamwarUser getOrCreateOfflinePlayer(String name){ + public static SteamwarUser getOrCreateOfflinePlayer(String name) { SteamwarUser user = SteamwarUser.get(name); if (user != null) { return user; @@ -143,34 +145,37 @@ public class SteamwarUser { return get(uuid); } - public static SteamwarUser get(String userName){ + public static SteamwarUser get(String userName) { userName = userName.toLowerCase(); - if(usersByName.containsKey(userName)) + if (usersByName.containsKey(userName)) { return usersByName.get(userName); + } return byName.select(rs -> { - if(rs.next()) + if (rs.next()) return new SteamwarUser(rs); return null; }, userName); } - public static SteamwarUser get(UUID uuid){ - if(usersByUUID.containsKey(uuid)) + public static SteamwarUser get(UUID uuid) { + if (usersByUUID.containsKey(uuid)) { return usersByUUID.get(uuid); + } return byUUID.select(rs -> { - if(rs.next()) + if (rs.next()) return new SteamwarUser(rs); return null; }, uuid.toString()); } - public static SteamwarUser get(ProxiedPlayer player){ + public static SteamwarUser get(ProxiedPlayer player) { return get(player.getUniqueId()); } - public static SteamwarUser get(int id){ - if(usersById.containsKey(id)) + public static SteamwarUser get(int id) { + if (usersById.containsKey(id)) { return usersById.get(id); + } return byID.select(rs -> { rs.next(); return new SteamwarUser(rs); @@ -178,16 +183,16 @@ public class SteamwarUser { } public static SteamwarUser get(Long discordId) { - if(usersByDiscord.containsKey(discordId.toString())) + if (usersByDiscord.containsKey(discordId.toString())) return usersByDiscord.get(discordId.toString()); return byDiscord.select(rs -> { - if(rs.next()) + if (rs.next()) return new SteamwarUser(rs); return null; }, discordId); } - public static void clearCache(){ + public static void clearCache() { usersById.clear(); usersByName.clear(); usersByUUID.clear(); @@ -205,7 +210,7 @@ public class SteamwarUser { } } - public void setTeam(int team){ + public void setTeam(int team) { this.team = team; updateTeam.update(team, id); setLeader(false); @@ -227,7 +232,7 @@ public class SteamwarUser { return userGroup; } - public int getTeam(){ + public int getTeam() { return team; } @@ -243,89 +248,64 @@ public class SteamwarUser { usersByDiscord.remove(this.discordId); this.discordId = discordId; updateDiscord.update(discordId, id); - if(discordId != null) { + if (discordId != null) { usersByDiscord.put(discordId, this); } } - public boolean isBanned() { - if(!punishments.containsKey(Punishment.PunishmentType.Ban)) + public boolean isPunished(Punishment.PunishmentType punishment) { + if (!punishments.containsKey(punishment)) { return false; - if(!punishments.get(Punishment.PunishmentType.Ban).isCurrent()) { - deleteIPs.update(id); - punishments.remove(Punishment.PunishmentType.Ban); + } + if (!punishments.get(punishment).isCurrent()) { + if (punishment == Punishment.PunishmentType.Ban) { + deleteIPs.update(id); + } + punishments.remove(punishment); return false; } return true; } - public boolean isMuted(){ - if(!punishments.containsKey(Punishment.PunishmentType.Mute)) - return false; - if(!punishments.get(Punishment.PunishmentType.Mute).isCurrent()) { - punishments.remove(Punishment.PunishmentType.Mute); - return false; - } - return true; - } + public void punish(Punishment.PunishmentType punishment, Timestamp time, String banReason, int from, boolean perma) { + punishments.remove(punishment); + punishments.put(punishment, Punishment.createPunishment(id, from, punishment, banReason, time, perma)); - public TextComponent banMessage(ProxiedPlayer player){ - Punishment punishment = punishments.get(Punishment.PunishmentType.Ban); - if (punishment.isPerma()) { - return BungeeCore.stringToText(Message.parsePrefixed("BANNED_MESSAGE_PERMA", player, punishment.getReason())); - } else { - return BungeeCore.stringToText(Message.parsePrefixed("BANNED_MESSAGE_UNTIL", player, punishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), - punishment.getReason())); - } - } - - public TextComponent muteMessage(ProxiedPlayer player){ - Punishment punishment = punishments.get(Punishment.PunishmentType.Mute); - if (punishment.isPerma()) { - return BungeeCore.stringToText(Message.parsePrefixed("MUTED_MESSAGE_PERMA", player, punishment.getReason())); - } else { - return BungeeCore.stringToText(Message.parsePrefixed("MUTED_MESSAGE_UNTIL", player, punishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), punishment.getReason())); - } - } - - public void updateBanIP(String ip){ - BannedUserIPs.banIP(this, ip); - } - - public void ban(Timestamp time, String banReason, int from, boolean perma){ - if(isBanned()) { - punishments.get(Punishment.PunishmentType.Ban).updateEndTime(from, banReason, time, perma); + if (punishment != Punishment.PunishmentType.Ban) { return; } - punishments.remove(Punishment.PunishmentType.Ban); - punishments.put(Punishment.PunishmentType.Ban, Punishment.createPunishment(id, from, Punishment.PunishmentType.Ban, banReason, time, perma)); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); - if(player != null){ + if (player != null) { updateBanIP(player.getAddress().getAddress().getHostAddress()); - player.disconnect(banMessage(player)); - for (BannedUserIPs banned: - BannedUserIPs.get(player.getAddress().getAddress().getHostAddress())) { + player.disconnect(punishmentMessage(punishment, player)); + for (BannedUserIPs banned : BannedUserIPs.get(player.getAddress().getAddress().getHostAddress())) { SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID()); - if(bannedUser.isBanned() && banned.getTimestamp().before(time)) - bannedUser.ban(time, banReason, from, perma); + if (isPunished(punishment) && banned.getTimestamp().before(time)) { + bannedUser.punish(punishment, time, banReason, from, perma); + } } - }else + } else { updateBanIP(""); + } } - public void mute(Timestamp time, String muteReason, int from, boolean perma){ - if(isMuted()) { - punishments.get(Punishment.PunishmentType.Mute).updateEndTime(from, muteReason, time, perma); - return; + public TextComponent punishmentMessage(Punishment.PunishmentType punishment, ProxiedPlayer player) { + Punishment currentPunishment = punishments.get(punishment); + if (currentPunishment.isPerma()) { + return BungeeCore.stringToText(Message.parsePrefixed(punishment.getPlayerMessagePerma(), player, currentPunishment.getReason())); + } else { + return BungeeCore.stringToText(Message.parsePrefixed(punishment.getPlayerMessageUntil(), player, currentPunishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), currentPunishment.getReason())); } - punishments.remove(Punishment.PunishmentType.Mute); - punishments.put(Punishment.PunishmentType.Mute, Punishment.createPunishment(id, from, Punishment.PunishmentType.Mute, muteReason, time, perma)); + } + + public void updateBanIP(String ip) { + BannedUserIPs.banIP(this, ip); } public double getOnlinetime() { return getPlaytime.select(rs -> { - if(rs.next()) + if (rs.next()) return rs.getBigDecimal("Playtime").doubleValue(); return 0.0; }, id); @@ -333,7 +313,7 @@ public class SteamwarUser { public Timestamp getFirstjoin() { return getFirstjoin.select(rs -> { - if(rs.next()) + if (rs.next()) return rs.getTimestamp("FirstJoin"); return null; }, id); diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 5d32af1..7632238 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -95,8 +95,6 @@ HELP_BAU_TESTARENA_HOVER=§eTestarena starten #Usage description of various commands USAGE_ALERT=§8/§7alert §8[§eNachricht§8] -USAGE_BAN=§8/§7ban §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8] -USAGE_MUTE=§8/§7mute §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8] USAGE_IGNORE=§8/§7ignore §8[§eSpieler§8] #ModListener @@ -110,21 +108,50 @@ ALERT=§f{0} 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} +PUNISHMENT_USAGE=§8/§7{0} §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8] +UNPUNISHMENT_USAGE=§8/§7{0} §8[§eSpieler§8] + +PUNISHMENT_UNTIL=bis zum {0} +PUNISHMENT_PERMA=permanent + +BAN_TEAM_BANNED={0} §c{1} wurde von {2} {3} gebannt. §f§lGrund§r: §f{4} BANNED_MESSAGE_PERMA=§cDu bist permanent gebannt. §r§lGrund§r: §c{0} BANNED_MESSAGE_UNTIL=§cDu bist bis zum {0} gebannt. §r§lGrund§r: §c{1} -MUTE_TEAM_MUTED={0} §c{1} wurde von {2} {3} gemuted. §f§lGrund: §f{4} +UNBAN_NOT_BANNED=§cDer Spieler ist nicht gebannt. +UNBAN_UNBANNED=Du hast {0} entbannt. + +MUTE_TEAM_MUTED={0} §c{1} wurde von {2} {3} gemuted. §f§lGrund§r: §f{4} MUTED_MESSAGE_PERMA=§cDu bist permanent gemuted. §r§lGrund§r: §c{0} MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1} -BAN_CHANGED={0}verändert von {1} von {2} auf {3} wegen {4} -BAN_PERMA=permanent -BAN_UNTIL=bis zum {0} +UNMUTE_NOT_MUTED=§cDer Spieler ist nicht gemutet. +UNMUTE_UNMUTED=Du hast {0} entmutet. + +ANTISCHEMADD_TEAM_ANTISCHEMADD={0} §c{1} wurde von {2} {3} schem adden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} +UNANTISCHEMADD_NOT_ANTISCHEMADD=§cDer Spieler ist nicht vom schem adden ausgeschlossen. +UNANTISCHEMADD_UNANTISCHEMADDED=Du hast {0} das schem adden zurückgegeben. + +ANTISCHEMADDED_TEAM_ANTISCHEMADDED={0} §c{1} wurde von {2} {3} schem add ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem add ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem add ausgeschlossen. §f§lGrund§r: §f{4} +UNANTISCHEMADDED_NOT_ANTISCHEMADDED=§cDer Spieler ist nicht vom schem add ausgeschlossen. +UNANTISCHEMADDED_UNANTISCHEMADDED=Du hast {0} das schem add zurückgegeben. + +UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics runterzuladen. + +UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics hochzuladen. + +UNANTIBAUJOIN_NOT_ANTIBAUJOINED=§cDer Spieler ist nicht vom joinen von Baus ausgeschlossen. + BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c BAN_AVOIDING_LIST={0} §e{1} §c BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung +#BugCommand BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. +#IgnoreCommand IGNORE_YOURSELF=§cWie willst du dich selber ignorieren? IGNORE_ALREADY=§cDu ignorierst diesen Spieler bereits. IGNORE_MESSAGE=§7Du ignorierst nun §e{0}§8. @@ -423,11 +450,6 @@ TP_USAGE=§8/§7tp §8[§eSpieler§8] TP_USAGE_EVENT=§8/§7tp §8[§eSpieler §7oder §eTeam§8] TP_NOT_FOUND=§cKonnte das angegebene Ziel nicht finden. -#UnbanCommand -UNBAN_USAGE=§8/§7unban §8[§eSpieler§8] -UNBAN_NOT_BANNED=§cDer Spieler ist nicht gebannt. -UNBAN_UNBANNED=Du hast {0} entbannt. - #UnignoreCommand UNIGNORE_USAGE=§8/§7unignore §8[§eSpieler§8] UNIGNORE_NOT_PLAYER=§cDiesen Spieler gibt es nicht! From b5a9ecc9997ebde7a1af6c8790b7a6d236357c92 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sun, 26 Sep 2021 23:36:41 +0200 Subject: [PATCH 19/83] Remove unintended imports --- src/de/steamwar/bungeecore/BungeeCore.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 2a725a6..accae59 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -20,9 +20,6 @@ package de.steamwar.bungeecore; import de.steamwar.bungeecore.bot.SteamwarDiscordBot; -import de.steamwar.bungeecore.bot.commands.BanCommand; -import de.steamwar.bungeecore.bot.commands.MuteCommand; -import de.steamwar.bungeecore.bot.commands.UnbanCommand; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.commands.*; import de.steamwar.bungeecore.comms.SpigotReceiver; @@ -111,8 +108,6 @@ public class BungeeCore extends Plugin { new JoinmeCommand(); new TpCommand(); new HelpCommand(); - new BanCommand(); - new UnbanCommand(); new DenyCommand("watchcat", "wc"); new TeamCommand(); new ServerTeamchatCommand(); @@ -121,7 +116,6 @@ public class BungeeCore extends Plugin { new EventreloadCommand(); new EventRescheduleCommand(); new PollCommand(); - new MuteCommand(); new BugCommand(); new WhoisCommand(); new RegelnCommand(); From a886936cf3f2b44c3c92b00e375fd237c29731b7 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sun, 26 Sep 2021 23:38:43 +0200 Subject: [PATCH 20/83] Add grouping to messages --- src/de/steamwar/messages/BungeeCore.properties | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 7632238..bcf0b15 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -120,6 +120,10 @@ BANNED_MESSAGE_UNTIL=§cDu bist bis zum {0} gebannt. §r§lGrund§r: §c{1} UNBAN_NOT_BANNED=§cDer Spieler ist nicht gebannt. UNBAN_UNBANNED=Du hast {0} entbannt. +BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c +BAN_AVOIDING_LIST={0} §e{1} §c +BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung + MUTE_TEAM_MUTED={0} §c{1} wurde von {2} {3} gemuted. §f§lGrund§r: §f{4} MUTED_MESSAGE_PERMA=§cDu bist permanent gemuted. §r§lGrund§r: §c{0} MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1} @@ -144,10 +148,6 @@ UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED=§cDer Spieler ist nicht ausgeschlossen UNANTIBAUJOIN_NOT_ANTIBAUJOINED=§cDer Spieler ist nicht vom joinen von Baus ausgeschlossen. -BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c -BAN_AVOIDING_LIST={0} §e{1} §c -BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung - #BugCommand BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. From 0b6b2c6b6b3158fe2ad06849d580bfb7ad1a2bbe Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 08:47:56 +0200 Subject: [PATCH 21/83] Update Punishments and commands for each punishment --- src/de/steamwar/bungeecore/BungeeCore.java | 6 +++ .../steamwar/bungeecore/sql/Punishment.java | 8 ++-- .../steamwar/messages/BungeeCore.properties | 38 ++++++++++++++----- 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index accae59..ae333db 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -131,6 +131,12 @@ public class BungeeCore extends Plugin { // Punishment Commands: new PunishmentCommand("ban", Punishment.PunishmentType.Ban); new PunishmentCommand("mute", Punishment.PunishmentType.Mute); + new PunishmentCommand("antischemadd", Punishment.PunishmentType.AntiSchemAdd); + new PunishmentCommand("antischemadded", Punishment.PunishmentType.AntiSchemAdded); + new PunishmentCommand("antischemdownload", Punishment.PunishmentType.AntiSchemDownload); + new PunishmentCommand("antischemupload", Punishment.PunishmentType.AntiSchemUpload); + new PunishmentCommand("antibaujoin", Punishment.PunishmentType.AntiBauJoin); + new PunishmentCommand("antifightjoin", Punishment.PunishmentType.AntiFightJoin); if(!EVENT_MODE){ new BauCommand(); diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index 0bd0962..0352bbb 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -134,10 +134,10 @@ public class Punishment { Mute( "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), AntiSchemAdd("ANTISCHEMADD_TEAM_ANTISCHEMADD", "ANTISCHEMADD_MESSAGE_PERMA", "ANTISCHEMADD_MESSAGE_UNTIL", "UNANTISCHEMADD_NOT_ANTISCHEMADD", "UNANTISCHEMADD_UNANTISCHEMADDED"), AntiSchemAdded("ANTISCHEMADDED_TEAM_ANTISCHEMADDED", "ANTISCHEMADDED_MESSAGE_PERMA", "ANTISCHEMADDED_MESSAGE_UNTIL", "UNANTISCHEMADDED_NOT_ANTISCHEMADDED", "UNANTISCHEMADDED_UNANTISCHEMADDED"), - // AntiSchemDownload("UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED"), - // AntiSchemUpload("UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED"), - // AntiBauJoin("UNANTIBAUJOIN_NOT_ANTIBAUJOINED"); - ; + AntiSchemDownload("ANTISCHEMDOWNLOAD_TEAM_ANTISCHEMDOWNLOADED", "ANTISCHEMDOWNLOAD_MESSAGE_PERMA", "ANTISCHEMDOWNLOAD_MESSAGE_UNTIL", "UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED", "UNANTISCHEMDOWNLOAD_UNANTISCHEMDOWNLOADED"), + AntiSchemUpload("ANTISCHEMUPLOAD_TEAM_ANTISCHEMUPLOADED", "ANTISCHEMUPLOAD_MESSAGE_PERMA", "ANTISCHEMUPLOAD_MESSAGE_UNTIL", "UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED", "UNANTISCHEMUPLOAD_ANTISCHEMUPLOADED"), + AntiBauJoin("ANTIBAUJOIN_TEAM_ANTIBAUJOINED", "ANTIBAUJOIN_MESSAGE_PERMA", "ANTIBAUJOIN_MESSAGE_UNTIL", "UNANTIBAUJOIN_NOT_ANTIBAUJOINED", "UNANTIBAUJOIN_ANTIBAUJOINED"), + AntiFightJoin("ANTIFIGHTJOIN_TEAM_ANTIFIGHTJOINED", "ANTIFIGHTJOIN_MESSAGE_PERMA", "ANTIFIGHTJOIN_MESSAGE_UNTIL", "UNANTIFIGHTJOIN_NOT_ANTIFIGHTJOINED", "UNANTIFIGHTJOIN_ANTIFIGHTJOINED"); private String teamMessage; private String playerMessagePerma; diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index bcf0b15..a98c5e5 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -130,23 +130,41 @@ MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1} UNMUTE_NOT_MUTED=§cDer Spieler ist nicht gemutet. UNMUTE_UNMUTED=Du hast {0} entmutet. -ANTISCHEMADD_TEAM_ANTISCHEMADD={0} §c{1} wurde von {2} {3} schem adden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} -UNANTISCHEMADD_NOT_ANTISCHEMADD=§cDer Spieler ist nicht vom schem adden ausgeschlossen. -UNANTISCHEMADD_UNANTISCHEMADDED=Du hast {0} das schem adden zurückgegeben. +ANTISCHEMADD_TEAM_ANTISCHEMADD={0} §c{1} wurde von {2} {3} schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} +UNANTISCHEMADD_NOT_ANTISCHEMADD=§cDer Spieler ist nicht vom schem geaddet werden ausgeschlossen. +UNANTISCHEMADD_UNANTISCHEMADDED=Du hast {0} das schem geaddet werden zurückgegeben. -ANTISCHEMADDED_TEAM_ANTISCHEMADDED={0} §c{1} wurde von {2} {3} schem add ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem add ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem add ausgeschlossen. §f§lGrund§r: §f{4} -UNANTISCHEMADDED_NOT_ANTISCHEMADDED=§cDer Spieler ist nicht vom schem add ausgeschlossen. -UNANTISCHEMADDED_UNANTISCHEMADDED=Du hast {0} das schem add zurückgegeben. +ANTISCHEMADDED_TEAM_ANTISCHEMADDED={0} §c{1} wurde von {2} {3} schem adden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} +UNANTISCHEMADDED_NOT_ANTISCHEMADDED=§cDer Spieler ist nicht vom schem adden ausgeschlossen. +UNANTISCHEMADDED_UNANTISCHEMADDED=Du hast {0} das schem adden wiederhergestellt. +ANTISCHEMDOWNLOAD_TEAM_ANTISCHEMDOWNLOADED={0} §c{1} wurde von {2} {3} schem download ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMDOWNLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem download ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMDOWNLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem download ausgeschlossen. §f§lGrund§r: §f{4} UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics runterzuladen. +UNANTISCHEMDOWNLOAD_UNANTISCHEMDOWNLOADED=Du hast {0} das schem downloaden wiederhergestellt. +ANTISCHEMUPLOAD_TEAM_ANTISCHEMUPLOADED={0} §c{1} wurde von {2} {3} schem upload ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMUPLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem upload ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMUPLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem upload ausgeschlossen. §f§lGrund§r: §f{4} UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics hochzuladen. +UNANTISCHEMUPLOAD_ANTISCHEMUPLOADED=Du hast {0} das schem upload wiederhergestellt. +ANTIBAUJOIN_TEAM_ANTIBAUJOINED={0} §c{1} wurde von {2} {3} joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} +ANTIBAUJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} +ANTIBAUJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} UNANTIBAUJOIN_NOT_ANTIBAUJOINED=§cDer Spieler ist nicht vom joinen von Baus ausgeschlossen. +UNANTIBAUJOIN_ANTIBAUJOINED=Du hast {0} das joinen von Baus wiederhergestellt. + +ANTIFIGHTJOIN_TEAM_ANTIFIGHTJOINED={0} §c{1} wurde von {2} {3} joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} +ANTIFIGHTJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} +ANTIFIGHTJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} +UNANTIFIGHTJOIN_NOT_ANTIFIGHTJOINED=§cDer Spieler ist nicht vom joinen von Fights ausgeschlossen. +UNANTIFIGHTJOIN_ANTIFIGHTJOINED=Du hast {0} das joinen von Fights wiederhergestellt. #BugCommand BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. From bb9627b74c62845ea16ddc9b7e436cd5297be3aa Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 09:29:51 +0200 Subject: [PATCH 22/83] Add punishment implementations --- src/de/steamwar/bungeecore/BungeeCore.java | 8 ++++-- src/de/steamwar/bungeecore/Node.java | 3 +++ .../bot/config/SteamwarDiscordBotConfig.java | 2 ++ .../bungeecore/commands/BauCommand.java | 10 ++++++- .../bungeecore/commands/ChallengeCommand.java | 8 ++++++ .../bungeecore/commands/DevCommand.java | 9 +++++++ .../bungeecore/commands/FightCommand.java | 8 ++++++ .../bungeecore/commands/HistoricCommand.java | 9 +++++++ .../bungeecore/commands/MsgCommand.java | 3 +-- .../commands/PunishmentCommand.java | 3 +++ .../bungeecore/commands/RCommand.java | 3 +-- .../bungeecore/commands/RankedCommand.java | 14 ++++++++-- .../bungeecore/listeners/ChatListener.java | 6 ++--- .../listeners/ConnectionListener.java | 26 ++++++++++++++++--- .../steamwar/bungeecore/sql/Punishment.java | 1 - .../steamwar/bungeecore/sql/SteamwarUser.java | 8 ++++++ 16 files changed, 103 insertions(+), 18 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index ae333db..23660f8 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -162,7 +162,9 @@ public class BungeeCore extends Plugin { Team.clearCache(); }, 1, 1, TimeUnit.HOURS); - new SteamwarDiscordBot(); + if (SteamwarDiscordBotConfig.loaded) { + new SteamwarDiscordBot(); + } } @Override @@ -275,7 +277,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/Node.java b/src/de/steamwar/bungeecore/Node.java index ea0a2ed..c5bed1e 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -194,6 +194,9 @@ public abstract class Node { } catch (IOException e) { BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); c = 1; + } catch (NumberFormatException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); + c = 1; } cores = c; BungeeCore.get().getLogger().log(Level.INFO, "Adding node " + remote + " with " + cores + " cores."); diff --git a/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java b/src/de/steamwar/bungeecore/bot/config/SteamwarDiscordBotConfig.java index f69a3ac..34c65e8 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; } } diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index 2965f08..ae8282c 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -24,6 +24,7 @@ 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.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; @@ -38,8 +39,15 @@ public class BauCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { - if(!(sender instanceof ProxiedPlayer)) + if(!(sender instanceof ProxiedPlayer)) { return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiBauJoin)) { + return; + } ProxiedPlayer p = (ProxiedPlayer) sender; diff --git a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java index 3d4150d..03a8a3d 100644 --- a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java +++ b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java @@ -22,6 +22,8 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.sql.IgnoreSystem; +import de.steamwar.bungeecore.sql.Punishment; +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.chat.ClickEvent; @@ -39,6 +41,12 @@ public class ChallengeCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { + return; + } + if(args.length < 1){ Message.send("CHALLENGE_USAGE", sender); return; diff --git a/src/de/steamwar/bungeecore/commands/DevCommand.java b/src/de/steamwar/bungeecore/commands/DevCommand.java index dcc4b7f..6fafeee 100644 --- a/src/de/steamwar/bungeecore/commands/DevCommand.java +++ b/src/de/steamwar/bungeecore/commands/DevCommand.java @@ -20,6 +20,8 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.sql.Punishment; +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; @@ -45,6 +47,13 @@ public class DevCommand extends BasicCommand { if (!(sender instanceof ProxiedPlayer)) { return; } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiBauJoin)) { + return; + } + String[] devServer = DevServerDir.list(); if (devServer == null || devServer.length == 0) { Message.send("DEV_NO_SERVER", sender); diff --git a/src/de/steamwar/bungeecore/commands/FightCommand.java b/src/de/steamwar/bungeecore/commands/FightCommand.java index 984bc06..878e5af 100644 --- a/src/de/steamwar/bungeecore/commands/FightCommand.java +++ b/src/de/steamwar/bungeecore/commands/FightCommand.java @@ -21,6 +21,8 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; +import de.steamwar.bungeecore.sql.Punishment; +import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ClickEvent; @@ -163,6 +165,12 @@ public class FightCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { + return; + } + createArena(sender, "/fight ", args, 0, false, (player, mode, map) -> { Subserver arena = SubserverSystem.startArena(mode, map, 0, 0, 0, null, null, player.getUniqueId(), null, false); arena.sendPlayer(player); diff --git a/src/de/steamwar/bungeecore/commands/HistoricCommand.java b/src/de/steamwar/bungeecore/commands/HistoricCommand.java index ebf9312..f727590 100644 --- a/src/de/steamwar/bungeecore/commands/HistoricCommand.java +++ b/src/de/steamwar/bungeecore/commands/HistoricCommand.java @@ -20,8 +20,11 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; +import de.steamwar.bungeecore.sql.Punishment; +import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.connection.ProxiedPlayer; import java.util.LinkedList; @@ -32,6 +35,12 @@ public class HistoricCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { + return; + } + FightCommand.createArena(sender, "/historic ", args, 0, true, (player, mode, map) -> { Subserver arena = SubserverSystem.startArena(mode, map, 0, 0, 0, null, null, player.getUniqueId(), null, false); arena.sendPlayer(player); diff --git a/src/de/steamwar/bungeecore/commands/MsgCommand.java b/src/de/steamwar/bungeecore/commands/MsgCommand.java index 13dbb27..67f7013 100644 --- a/src/de/steamwar/bungeecore/commands/MsgCommand.java +++ b/src/de/steamwar/bungeecore/commands/MsgCommand.java @@ -49,8 +49,7 @@ public class MsgCommand extends BasicCommand { } SteamwarUser user = SteamwarUser.get(player); - if (user.isPunished(Punishment.PunishmentType.Mute)) { - sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, player)); + if (user.isPunishedWithMessage(player, Punishment.PunishmentType.Mute)) { return; } diff --git a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java index 6f425c1..ce66981 100644 --- a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java +++ b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java @@ -22,6 +22,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; +import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.CommandSender; import java.sql.Timestamp; @@ -29,10 +30,12 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; +import java.util.logging.Level; public class PunishmentCommand { public PunishmentCommand(String command, Punishment.PunishmentType punishmentType) { + BungeeCord.getInstance().getLogger().log(Level.INFO, "CMD: " + command + " " + punishmentType); new BasicCommand(command, "bungeecore.ban") { @Override public void execute(CommandSender sender, String[] args) { diff --git a/src/de/steamwar/bungeecore/commands/RCommand.java b/src/de/steamwar/bungeecore/commands/RCommand.java index 7a208db..c9d70dd 100644 --- a/src/de/steamwar/bungeecore/commands/RCommand.java +++ b/src/de/steamwar/bungeecore/commands/RCommand.java @@ -45,8 +45,7 @@ public class RCommand extends BasicCommand { } SteamwarUser user = SteamwarUser.get(player); - if (user.isPunished(Punishment.PunishmentType.Mute)) { - sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, player)); + if (user.isPunishedWithMessage(player, Punishment.PunishmentType.Mute)) { return; } diff --git a/src/de/steamwar/bungeecore/commands/RankedCommand.java b/src/de/steamwar/bungeecore/commands/RankedCommand.java index 1a978b5..3fb70cf 100644 --- a/src/de/steamwar/bungeecore/commands/RankedCommand.java +++ b/src/de/steamwar/bungeecore/commands/RankedCommand.java @@ -21,6 +21,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.sql.Elo; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; @@ -49,11 +50,20 @@ public class RankedCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { + if(!(sender instanceof ProxiedPlayer)) { + return; + } + + ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; + SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { + return; + } + if(args.length < 1){ getModes(sender, "/ranked "); return; - }else if(!(sender instanceof ProxiedPlayer)) - return; + } ArenaMode mode = FightCommand.getMode(sender, args[0]); if(mode == null) diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index a371a2e..c50c782 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -145,8 +145,7 @@ public class ChatListener extends BasicListener { } SteamwarUser user = SteamwarUser.get(sender); - if (user.isPunished(Punishment.PunishmentType.Mute)) { - sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, sender)); + if (user.isPunishedWithMessage(sender, Punishment.PunishmentType.Mute)) { e.setCancelled(true); return; } @@ -224,8 +223,7 @@ public class ChatListener extends BasicListener { } SteamwarUser user = SteamwarUser.get(sender); - if (user.isPunished(Punishment.PunishmentType.Mute)) { - sender.sendMessage(user.punishmentMessage(Punishment.PunishmentType.Mute, sender)); + if (user.isPunishedWithMessage(sender, Punishment.PunishmentType.Mute)) { e.setCancelled(true); return; } diff --git a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java index 9506ea2..53a11dd 100644 --- a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java +++ b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java @@ -27,6 +27,7 @@ import de.steamwar.bungeecore.bot.util.DiscordRanks; import de.steamwar.bungeecore.commands.ChallengeCommand; import de.steamwar.bungeecore.commands.CheckCommand; import de.steamwar.bungeecore.commands.MsgCommand; +import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.UserGroup; import net.md_5.bungee.api.AbstractReconnectHandler; @@ -34,10 +35,7 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.event.PlayerDisconnectEvent; -import net.md_5.bungee.api.event.PostLoginEvent; -import net.md_5.bungee.api.event.ServerDisconnectEvent; -import net.md_5.bungee.api.event.ServerKickEvent; +import net.md_5.bungee.api.event.*; import net.md_5.bungee.event.EventHandler; import java.util.*; @@ -144,4 +142,24 @@ public class ConnectionListener extends BasicListener { if(players.isEmpty() || (players.size() == 1 && players.contains(player))) ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), subserver::waitForTermination); } + + @EventHandler + public void onServerConnect(ServerConnectEvent e) { + ServerInfo server = e.getTarget(); + Subserver subserver = Subserver.getSubserver(server); + if (subserver == null) { + return; + } + SteamwarUser steamwarUser = SteamwarUser.get(e.getPlayer()); + + if (subserver.getType() == Servertype.BAUSERVER) { + if (steamwarUser.isPunishedWithMessage(e.getPlayer(), Punishment.PunishmentType.AntiBauJoin)) { + e.setCancelled(true); + } + } else { + if (steamwarUser.isPunishedWithMessage(e.getPlayer(), Punishment.PunishmentType.AntiFightJoin)) { + e.setCancelled(true); + } + } + } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index 0352bbb..c6ca242 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -34,7 +34,6 @@ public class Punishment { 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) { return getPunishment.select(rs -> { diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index f83d76c..bc66108 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -267,6 +267,14 @@ public class SteamwarUser { return true; } + public boolean isPunishedWithMessage(ProxiedPlayer player, Punishment.PunishmentType punishment) { + if (!isPunished(punishment)) { + return false; + } + player.sendMessage(punishmentMessage(punishment, player)); + return true; + } + public void punish(Punishment.PunishmentType punishment, Timestamp time, String banReason, int from, boolean perma) { punishments.remove(punishment); punishments.put(punishment, Punishment.createPunishment(id, from, punishment, banReason, time, perma)); From 3d49d907a463085473c65013453e4e18fb3ac3a4 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 09:37:50 +0200 Subject: [PATCH 23/83] Fix messages --- .../steamwar/messages/BungeeCore.properties | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index a98c5e5..59755d0 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -131,38 +131,38 @@ UNMUTE_NOT_MUTED=§cDer Spieler ist nicht gemutet. UNMUTE_UNMUTED=Du hast {0} entmutet. ANTISCHEMADD_TEAM_ANTISCHEMADD={0} §c{1} wurde von {2} {3} schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{0} +ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{1} UNANTISCHEMADD_NOT_ANTISCHEMADD=§cDer Spieler ist nicht vom schem geaddet werden ausgeschlossen. UNANTISCHEMADD_UNANTISCHEMADDED=Du hast {0} das schem geaddet werden zurückgegeben. ANTISCHEMADDED_TEAM_ANTISCHEMADDED={0} §c{1} wurde von {2} {3} schem adden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{0} +ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{1} UNANTISCHEMADDED_NOT_ANTISCHEMADDED=§cDer Spieler ist nicht vom schem adden ausgeschlossen. UNANTISCHEMADDED_UNANTISCHEMADDED=Du hast {0} das schem adden wiederhergestellt. ANTISCHEMDOWNLOAD_TEAM_ANTISCHEMDOWNLOADED={0} §c{1} wurde von {2} {3} schem download ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMDOWNLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem download ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMDOWNLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem download ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMDOWNLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem download ausgeschlossen. §f§lGrund§r: §f{0} +ANTISCHEMDOWNLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem download ausgeschlossen. §f§lGrund§r: §f{1} UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics runterzuladen. UNANTISCHEMDOWNLOAD_UNANTISCHEMDOWNLOADED=Du hast {0} das schem downloaden wiederhergestellt. ANTISCHEMUPLOAD_TEAM_ANTISCHEMUPLOADED={0} §c{1} wurde von {2} {3} schem upload ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMUPLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem upload ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMUPLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem upload ausgeschlossen. §f§lGrund§r: §f{4} +ANTISCHEMUPLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem upload ausgeschlossen. §f§lGrund§r: §f{0} +ANTISCHEMUPLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem upload ausgeschlossen. §f§lGrund§r: §f{1} UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics hochzuladen. UNANTISCHEMUPLOAD_ANTISCHEMUPLOADED=Du hast {0} das schem upload wiederhergestellt. ANTIBAUJOIN_TEAM_ANTIBAUJOINED={0} §c{1} wurde von {2} {3} joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} -ANTIBAUJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} -ANTIBAUJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} +ANTIBAUJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{0} +ANTIBAUJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{1} UNANTIBAUJOIN_NOT_ANTIBAUJOINED=§cDer Spieler ist nicht vom joinen von Baus ausgeschlossen. UNANTIBAUJOIN_ANTIBAUJOINED=Du hast {0} das joinen von Baus wiederhergestellt. ANTIFIGHTJOIN_TEAM_ANTIFIGHTJOINED={0} §c{1} wurde von {2} {3} joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} -ANTIFIGHTJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} -ANTIFIGHTJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} +ANTIFIGHTJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{0} +ANTIFIGHTJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{1} UNANTIFIGHTJOIN_NOT_ANTIFIGHTJOINED=§cDer Spieler ist nicht vom joinen von Fights ausgeschlossen. UNANTIFIGHTJOIN_ANTIFIGHTJOINED=Du hast {0} das joinen von Fights wiederhergestellt. From 5b5a1796efca7b88d3da971fd5dfefae64102e8e Mon Sep 17 00:00:00 2001 From: Lixfel Date: Mon, 27 Sep 2021 15:23:20 +0200 Subject: [PATCH 24/83] 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 0000000..432a095 --- /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 25/83] 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 0b71cb5..6b46fbb 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 f69a3ac..34c65e8 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 26/83] 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 ea0a2ed..465778c 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 5918a2530af80fa83aa2c8b3fa16d3bc3b0462f3 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 16:46:26 +0200 Subject: [PATCH 27/83] 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 c5bed1e..ab53071 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; } catch (NumberFormatException e) { From 064796ec483fe8e22d62752770eb2014862a1565 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Mon, 27 Sep 2021 16:55:54 +0200 Subject: [PATCH 28/83] Fix Node NumberFormatException --- src/de/steamwar/bungeecore/Node.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index ab53071..465778c 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -194,9 +194,6 @@ public abstract class Node { } catch (IOException | NumberFormatException e) { BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); c = 1; - } catch (NumberFormatException e) { - BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e); - c = 1; } cores = c; BungeeCore.get().getLogger().log(Level.INFO, "Adding node " + remote + " with " + cores + " cores."); From 5bcc87aa1e89fb69009649b756b0c3cdcd461639 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 30 Sep 2021 12:26:47 +0200 Subject: [PATCH 29/83] 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 c37538b..9b1628c 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 30/83] 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 6b46fbb..9a5dfc1 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 4bfe84c..80b417f 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 ecaba65f79cfbed0555fdc9de63d53f09e9c2e91 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Thu, 30 Sep 2021 13:47:21 +0200 Subject: [PATCH 31/83] Update Punishment, messages not final --- src/de/steamwar/bungeecore/BungeeCore.java | 9 ++-- .../bungeecore/commands/BauCommand.java | 6 --- .../bungeecore/commands/ChallengeCommand.java | 6 --- .../bungeecore/commands/DevCommand.java | 2 +- .../bungeecore/commands/FightCommand.java | 6 --- .../bungeecore/commands/HistoricCommand.java | 6 --- .../commands/PunishmentCommand.java | 7 +++ .../bungeecore/commands/RankedCommand.java | 6 --- .../listeners/ConnectionListener.java | 11 ----- .../steamwar/bungeecore/sql/Punishment.java | 9 ++-- .../steamwar/messages/BungeeCore.properties | 48 ++++++------------- 11 files changed, 29 insertions(+), 87 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 23660f8..3b67b64 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -131,12 +131,9 @@ public class BungeeCore extends Plugin { // Punishment Commands: new PunishmentCommand("ban", Punishment.PunishmentType.Ban); new PunishmentCommand("mute", Punishment.PunishmentType.Mute); - new PunishmentCommand("antischemadd", Punishment.PunishmentType.AntiSchemAdd); - new PunishmentCommand("antischemadded", Punishment.PunishmentType.AntiSchemAdded); - new PunishmentCommand("antischemdownload", Punishment.PunishmentType.AntiSchemDownload); - new PunishmentCommand("antischemupload", Punishment.PunishmentType.AntiSchemUpload); - new PunishmentCommand("antibaujoin", Punishment.PunishmentType.AntiBauJoin); - new PunishmentCommand("antifightjoin", Punishment.PunishmentType.AntiFightJoin); + new PunishmentCommand("noschemreceiving", Punishment.PunishmentType.NoSchemReceiving); + new PunishmentCommand("noschemsharing", Punishment.PunishmentType.NoSchemSharing); + new PunishmentCommand("nodev", Punishment.PunishmentType.NoDevServer); if(!EVENT_MODE){ new BauCommand(); diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index ae8282c..846af9c 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -43,12 +43,6 @@ public class BauCommand extends BasicCommand { return; } - ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiBauJoin)) { - return; - } - ProxiedPlayer p = (ProxiedPlayer) sender; if(args.length == 0){ diff --git a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java index 03a8a3d..91df5cc 100644 --- a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java +++ b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java @@ -41,12 +41,6 @@ public class ChallengeCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { - ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { - return; - } - if(args.length < 1){ Message.send("CHALLENGE_USAGE", sender); return; diff --git a/src/de/steamwar/bungeecore/commands/DevCommand.java b/src/de/steamwar/bungeecore/commands/DevCommand.java index 6fafeee..6a2a79d 100644 --- a/src/de/steamwar/bungeecore/commands/DevCommand.java +++ b/src/de/steamwar/bungeecore/commands/DevCommand.java @@ -50,7 +50,7 @@ public class DevCommand extends BasicCommand { ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiBauJoin)) { + if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.NoDevServer)) { return; } diff --git a/src/de/steamwar/bungeecore/commands/FightCommand.java b/src/de/steamwar/bungeecore/commands/FightCommand.java index 878e5af..45e40a1 100644 --- a/src/de/steamwar/bungeecore/commands/FightCommand.java +++ b/src/de/steamwar/bungeecore/commands/FightCommand.java @@ -165,12 +165,6 @@ public class FightCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { - ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { - return; - } - createArena(sender, "/fight ", args, 0, false, (player, mode, map) -> { Subserver arena = SubserverSystem.startArena(mode, map, 0, 0, 0, null, null, player.getUniqueId(), null, false); arena.sendPlayer(player); diff --git a/src/de/steamwar/bungeecore/commands/HistoricCommand.java b/src/de/steamwar/bungeecore/commands/HistoricCommand.java index f727590..c144795 100644 --- a/src/de/steamwar/bungeecore/commands/HistoricCommand.java +++ b/src/de/steamwar/bungeecore/commands/HistoricCommand.java @@ -35,12 +35,6 @@ public class HistoricCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { - ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { - return; - } - FightCommand.createArena(sender, "/historic ", args, 0, true, (player, mode, map) -> { Subserver arena = SubserverSystem.startArena(mode, map, 0, 0, 0, null, null, player.getUniqueId(), null, false); arena.sendPlayer(player); diff --git a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java index ce66981..d214e7b 100644 --- a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java +++ b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java @@ -24,6 +24,7 @@ import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; import java.sql.Timestamp; import java.text.ParseException; @@ -39,6 +40,9 @@ public class PunishmentCommand { new BasicCommand(command, "bungeecore.ban") { @Override public void execute(CommandSender sender, String[] args) { + if (punishmentType == Punishment.PunishmentType.NoDevServer && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { + return; + } if (args.length < 3) { Message.send("PUNISHMENT_USAGE", sender, command); return; @@ -66,6 +70,9 @@ public class PunishmentCommand { new BasicCommand(antiCommand, "bungeecore.ban") { @Override public void execute(CommandSender sender, String[] args) { + if (punishmentType == Punishment.PunishmentType.NoDevServer && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { + return; + } if (args.length < 1) { Message.send("UNPUNISHMENT_USAGE", sender, antiCommand); return; diff --git a/src/de/steamwar/bungeecore/commands/RankedCommand.java b/src/de/steamwar/bungeecore/commands/RankedCommand.java index 3fb70cf..c4318be 100644 --- a/src/de/steamwar/bungeecore/commands/RankedCommand.java +++ b/src/de/steamwar/bungeecore/commands/RankedCommand.java @@ -54,12 +54,6 @@ public class RankedCommand extends BasicCommand { return; } - ProxiedPlayer proxiedPlayer = (ProxiedPlayer) sender; - SteamwarUser steamwarUser = SteamwarUser.get(proxiedPlayer); - if (steamwarUser.isPunishedWithMessage(proxiedPlayer, Punishment.PunishmentType.AntiFightJoin)) { - return; - } - if(args.length < 1){ getModes(sender, "/ranked "); return; diff --git a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java index 53a11dd..e006e8e 100644 --- a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java +++ b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java @@ -150,16 +150,5 @@ public class ConnectionListener extends BasicListener { if (subserver == null) { return; } - SteamwarUser steamwarUser = SteamwarUser.get(e.getPlayer()); - - if (subserver.getType() == Servertype.BAUSERVER) { - if (steamwarUser.isPunishedWithMessage(e.getPlayer(), Punishment.PunishmentType.AntiBauJoin)) { - e.setCancelled(true); - } - } else { - if (steamwarUser.isPunishedWithMessage(e.getPlayer(), Punishment.PunishmentType.AntiFightJoin)) { - e.setCancelled(true); - } - } } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index c6ca242..872e646 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -131,12 +131,9 @@ public class Punishment { public enum PunishmentType { Ban("BAN_TEAM_BANNED", "BANNED_MESSAGE_PERMA", "BANNED_MESSAGE_UNTIL", "UNBAN_NOT_BANNED", "UNBAN_UNBANNED"), Mute( "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), - AntiSchemAdd("ANTISCHEMADD_TEAM_ANTISCHEMADD", "ANTISCHEMADD_MESSAGE_PERMA", "ANTISCHEMADD_MESSAGE_UNTIL", "UNANTISCHEMADD_NOT_ANTISCHEMADD", "UNANTISCHEMADD_UNANTISCHEMADDED"), - AntiSchemAdded("ANTISCHEMADDED_TEAM_ANTISCHEMADDED", "ANTISCHEMADDED_MESSAGE_PERMA", "ANTISCHEMADDED_MESSAGE_UNTIL", "UNANTISCHEMADDED_NOT_ANTISCHEMADDED", "UNANTISCHEMADDED_UNANTISCHEMADDED"), - AntiSchemDownload("ANTISCHEMDOWNLOAD_TEAM_ANTISCHEMDOWNLOADED", "ANTISCHEMDOWNLOAD_MESSAGE_PERMA", "ANTISCHEMDOWNLOAD_MESSAGE_UNTIL", "UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED", "UNANTISCHEMDOWNLOAD_UNANTISCHEMDOWNLOADED"), - AntiSchemUpload("ANTISCHEMUPLOAD_TEAM_ANTISCHEMUPLOADED", "ANTISCHEMUPLOAD_MESSAGE_PERMA", "ANTISCHEMUPLOAD_MESSAGE_UNTIL", "UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED", "UNANTISCHEMUPLOAD_ANTISCHEMUPLOADED"), - AntiBauJoin("ANTIBAUJOIN_TEAM_ANTIBAUJOINED", "ANTIBAUJOIN_MESSAGE_PERMA", "ANTIBAUJOIN_MESSAGE_UNTIL", "UNANTIBAUJOIN_NOT_ANTIBAUJOINED", "UNANTIBAUJOIN_ANTIBAUJOINED"), - AntiFightJoin("ANTIFIGHTJOIN_TEAM_ANTIFIGHTJOINED", "ANTIFIGHTJOIN_MESSAGE_PERMA", "ANTIFIGHTJOIN_MESSAGE_UNTIL", "UNANTIFIGHTJOIN_NOT_ANTIFIGHTJOINED", "UNANTIFIGHTJOIN_ANTIFIGHTJOINED"); + NoSchemReceiving("NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING", "NOSCHEMRECEIVING_MESSAGE_PERMA", "NOSCHEMRECEIVING_MESSAGE_UNTIL", "UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING", "UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING"), + NoSchemSharing("NOSCHEMSHARING_TEAM_NOSCHEMSHARING", "NOSCHEMSHARING_MESSAGE_PERMA", "NOSCHEMSHARING_MESSAGE_UNTIL", "UNNOSCHEMSHARING_NOT_NOSCHEMSHARING", "UNNOSCHEMSHARING_UNNOSCHEMSHARING"), + NoDevServer("NODEVSERVER_TEAM_NODEVSERVER", "NODEVSERVER_MESSAGE_PERMA", "NODEVSERVER_MESSAGE_UNTIL", "UNNODEVSERVER_NOT_NODEVSERVER", "UNNODEVSERVER_UNNODEVSERVER"); private String teamMessage; private String playerMessagePerma; diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 59755d0..2fc7b51 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -130,41 +130,23 @@ MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1} UNMUTE_NOT_MUTED=§cDer Spieler ist nicht gemutet. UNMUTE_UNMUTED=Du hast {0} entmutet. -ANTISCHEMADD_TEAM_ANTISCHEMADD={0} §c{1} wurde von {2} {3} schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADD_MESSAGE_PERMA=§cDu bist permanent vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{0} -ANTISCHEMADD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem geaddet werden ausgeschlossen. §f§lGrund§r: §f{1} -UNANTISCHEMADD_NOT_ANTISCHEMADD=§cDer Spieler ist nicht vom schem geaddet werden ausgeschlossen. -UNANTISCHEMADD_UNANTISCHEMADDED=Du hast {0} das schem geaddet werden zurückgegeben. +NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING={0} §c{1} wurde von {2} {3} vom schem erhalten ausgeschlossen. §f§lGrund§r: §f{4} +NOSCHEMRECEIVING_MESSAGE_PERMA=§cDu bist permanent vom erhalten von schems ausgeschlossen. §f§lGrund§r: §f{0} +NOSCHEMRECEIVING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom erhalten von schems ausgeschlossen. §f§lGrund§r: §f{1} +UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING=§cDer Spieler ist nicht vom erhalten von schems ausgeschlossen. +UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING=Du hast {0} das schems erhalten zurückgegeben. -ANTISCHEMADDED_TEAM_ANTISCHEMADDED={0} §c{1} wurde von {2} {3} schem adden ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMADDED_MESSAGE_PERMA=§cDu bist permanent vom schem adden ausgeschlossen. §f§lGrund§r: §f{0} -ANTISCHEMADDED_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem adden ausgeschlossen. §f§lGrund§r: §f{1} -UNANTISCHEMADDED_NOT_ANTISCHEMADDED=§cDer Spieler ist nicht vom schem adden ausgeschlossen. -UNANTISCHEMADDED_UNANTISCHEMADDED=Du hast {0} das schem adden wiederhergestellt. +NOSCHEMSHARING_TEAM_NOSCHEMSHARING={0} §c{1} wurde von {2} {3} vom schem verteilen ausgeschlossen. §f§lGrund§r: §f{4} +NOSCHEMSHARING_MESSAGE_PERMA=§cDu bist permanent vom verteilen von schems ausgeschlossen. §f§lGrund§r: §f{0} +NOSCHEMSHARING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom verteilen von schems ausgeschlossen. §f§lGrund§r: §f{1} +UNNOSCHEMSHARING_NOT_NOSCHEMSHARING=§cDer Spieler ist nicht vom verteilen von schems ausgeschlossen. +UNNOSCHEMSHARING_UNNOSCHEMSHARING=Du hast {0} das schems verteilen zurückgegeben. -ANTISCHEMDOWNLOAD_TEAM_ANTISCHEMDOWNLOADED={0} §c{1} wurde von {2} {3} schem download ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMDOWNLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem download ausgeschlossen. §f§lGrund§r: §f{0} -ANTISCHEMDOWNLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem download ausgeschlossen. §f§lGrund§r: §f{1} -UNANTISCHEMDOWNLOAD_NOT_ANTISCHEMDOWNLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics runterzuladen. -UNANTISCHEMDOWNLOAD_UNANTISCHEMDOWNLOADED=Du hast {0} das schem downloaden wiederhergestellt. - -ANTISCHEMUPLOAD_TEAM_ANTISCHEMUPLOADED={0} §c{1} wurde von {2} {3} schem upload ausgeschlossen. §f§lGrund§r: §f{4} -ANTISCHEMUPLOAD_MESSAGE_PERMA=§cDu bist permanent vom schem upload ausgeschlossen. §f§lGrund§r: §f{0} -ANTISCHEMUPLOAD_MESSAGE_UNTIL=§cDu bist bis zum {0} vom schem upload ausgeschlossen. §f§lGrund§r: §f{1} -UNANTISCHEMUPLOAD_NOT_ANTISCHEMUPLOADED=§cDer Spieler ist nicht ausgeschlossen Schematics hochzuladen. -UNANTISCHEMUPLOAD_ANTISCHEMUPLOADED=Du hast {0} das schem upload wiederhergestellt. - -ANTIBAUJOIN_TEAM_ANTIBAUJOINED={0} §c{1} wurde von {2} {3} joinen von Baus ausgeschlossen. §f§lGrund§r: §f{4} -ANTIBAUJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{0} -ANTIBAUJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Baus ausgeschlossen. §f§lGrund§r: §f{1} -UNANTIBAUJOIN_NOT_ANTIBAUJOINED=§cDer Spieler ist nicht vom joinen von Baus ausgeschlossen. -UNANTIBAUJOIN_ANTIBAUJOINED=Du hast {0} das joinen von Baus wiederhergestellt. - -ANTIFIGHTJOIN_TEAM_ANTIFIGHTJOINED={0} §c{1} wurde von {2} {3} joinen von Fights ausgeschlossen. §f§lGrund§r: §f{4} -ANTIFIGHTJOIN_MESSAGE_PERMA=§cDu bist permanent vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{0} -ANTIFIGHTJOIN_MESSAGE_UNTIL=§cDu bist bis zum {0} vom joinen von Fights ausgeschlossen. §f§lGrund§r: §f{1} -UNANTIFIGHTJOIN_NOT_ANTIFIGHTJOINED=§cDer Spieler ist nicht vom joinen von Fights ausgeschlossen. -UNANTIFIGHTJOIN_ANTIFIGHTJOINED=Du hast {0} das joinen von Fights wiederhergestellt. +NODEVSERVER_TEAM_NODEVSERVER={0} §c{1} wurde von {2} {3} vom dev server ausgeschlossen. §f§lGrund§r: §f{4} +NODEVSERVER_MESSAGE_PERMA=§cDu bist permanent vom dev server ausgeschlossen. §f§lGrund§r: §f{0} +NODEVSERVER_MESSAGE_UNTIL=§cDu bist bis zum {0} vom dev server ausgeschlossen. §f§lGrund§r: §f{1} +UNNODEVSERVER_NOT_NODEVSERVER=§cDer Spieler ist nicht vom dev server ausgeschlossen. +UNNODEVSERVER_UNNODEVSERVER=Du hast {0} das das joinen des dev servers zurückgegeben. #BugCommand BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. From f9b42ad0c1a184bd9b71d35d82cf998137129b39 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 30 Sep 2021 16:21:24 +0200 Subject: [PATCH 32/83] 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 e0e4472..0e85917 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 33/83] 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 9a5dfc1..16e8e9d 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 8ff2dfc..3a4c2b3 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 b9b0ab1..f9c589b 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 0e85917..b4ff5e9 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 34/83] 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 16e8e9d..be2007a 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 35/83] 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 3a4c2b3..e614c5e 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 36/83] 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 be2007a..13a27a0 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); } From 3f417d8ecb6fd00f8fd713e2cce59e24c1e50652 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 2 Oct 2021 19:07:50 +0200 Subject: [PATCH 37/83] Cyclic port running to reduce failing server starts Signed-off-by: Lixfel --- .../steamwar/bungeecore/SubserverSystem.java | 68 ++++++++++++------- 1 file changed, 42 insertions(+), 26 deletions(-) diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index 018c8a3..66ec037 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -29,7 +29,9 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import java.io.File; import java.net.InetSocketAddress; import java.time.format.DateTimeFormatter; +import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; public class SubserverSystem { private SubserverSystem(){} @@ -39,14 +41,9 @@ public class SubserverSystem { private static final String SERVER_PATH = BACKBONE + "server/"; private static final String EVENT_PATH = BACKBONE + "event/"; - private static final int FIRST_ARENA_PORT; - - static { - if(BungeeCore.EVENT_MODE) - FIRST_ARENA_PORT = 6000; - else - FIRST_ARENA_PORT = 2500; - } + private static final boolean MAIN_SERVER = ProxyServer.getInstance().getConfig().getListeners().stream().anyMatch(info -> ((InetSocketAddress) info.getSocketAddress()).getPort() == 25565); + private static final Portrange bauPorts = MAIN_SERVER ? new Portrange(10100, 20000) : new Portrange(2100, 2200); + private static final Portrange arenaPorts = MAIN_SERVER ? new Portrange(3000, 3100) : (BungeeCore.EVENT_MODE ? new Portrange(4000, 5000) : bauPorts); /** * This function starts every arena (even test- and eventarenas). @@ -88,13 +85,13 @@ 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); + int port = arenaPorts.freePort(); if(serverName == null){ if(ranked) - serverName = "Ranked" + (port - FIRST_ARENA_PORT); + serverName = "Ranked" + (port - arenaPorts.start); else - serverName = modus.getDisplayName() + (port - FIRST_ARENA_PORT); + serverName = modus.getDisplayName() + (port - arenaPorts.start); } if(mapName == null) mapName = serverName; @@ -159,7 +156,7 @@ public class SubserverSystem { SteamwarUser user = SteamwarUser.get(owner); File directory = new File(SERVER_PATH, serverName); Node node = Node.getNode(); - int port = freePort(4000); + int port = bauPorts.freePort(); new Bauserver(user.getUserName() + "s Bau", owner, port, node.startServer( serverJar, directory, worldDir, worldName, port, xmx, "logPath=" + worldName @@ -213,21 +210,40 @@ public class SubserverSystem { Node.local.execute("cp", "-r", sourcePath, targetPath); } - private static int freePort(int start){ - synchronized (Subserver.getServerList()){ - int port = start; - boolean isFree = false; - while(!isFree){ - port++; - isFree = true; - for(Subserver server : Subserver.getServerList()){ - if(((InetSocketAddress)server.getServer().getSocketAddress()).getPort() == port){ - isFree = false; - break; - } - } + + private static class Portrange { + + private final int start; + private final int end; + private int current; + + private Portrange(int start, int end) { + this.start = start; + this.end = end; + current = start; + } + + private void increment() { + current++; + + if(current == end) + current = start; + } + + private synchronized int freePort() { + Set usedPorts; + + synchronized (Subserver.getServerList()) { + usedPorts = Subserver.getServerList().stream().map(server -> ((InetSocketAddress) server.getServer().getSocketAddress()).getPort()).collect(Collectors.toSet()); } - return port; + + while(usedPorts.contains(current)) { + increment(); + } + + int result = current; + increment(); + return result; } } } From 4f7ccf20283a2d1bf7651df25fe2ae7b73dfcb8f Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sat, 2 Oct 2021 21:24:32 +0200 Subject: [PATCH 38/83] Fix stuff --- .../bungeecore/commands/FightCommand.java | 2 -- .../bungeecore/commands/HistoricCommand.java | 8 +++---- .../commands/PunishmentCommand.java | 7 ++----- .../bungeecore/commands/RankedCommand.java | 1 - .../listeners/ConnectionListener.java | 15 ++++--------- .../steamwar/bungeecore/sql/Punishment.java | 21 ++++++++++--------- 6 files changed, 21 insertions(+), 33 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/FightCommand.java b/src/de/steamwar/bungeecore/commands/FightCommand.java index 45e40a1..984bc06 100644 --- a/src/de/steamwar/bungeecore/commands/FightCommand.java +++ b/src/de/steamwar/bungeecore/commands/FightCommand.java @@ -21,8 +21,6 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; -import de.steamwar.bungeecore.sql.Punishment; -import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ClickEvent; diff --git a/src/de/steamwar/bungeecore/commands/HistoricCommand.java b/src/de/steamwar/bungeecore/commands/HistoricCommand.java index c144795..0ddfef2 100644 --- a/src/de/steamwar/bungeecore/commands/HistoricCommand.java +++ b/src/de/steamwar/bungeecore/commands/HistoricCommand.java @@ -19,12 +19,12 @@ package de.steamwar.bungeecore.commands; -import de.steamwar.bungeecore.*; -import de.steamwar.bungeecore.sql.Punishment; -import de.steamwar.bungeecore.sql.SteamwarUser; +import de.steamwar.bungeecore.ArenaMode; +import de.steamwar.bungeecore.Message; +import de.steamwar.bungeecore.Subserver; +import de.steamwar.bungeecore.SubserverSystem; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.connection.ProxiedPlayer; import java.util.LinkedList; diff --git a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java index d214e7b..eda5c8b 100644 --- a/src/de/steamwar/bungeecore/commands/PunishmentCommand.java +++ b/src/de/steamwar/bungeecore/commands/PunishmentCommand.java @@ -22,7 +22,6 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; -import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -31,16 +30,14 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; -import java.util.logging.Level; public class PunishmentCommand { public PunishmentCommand(String command, Punishment.PunishmentType punishmentType) { - BungeeCord.getInstance().getLogger().log(Level.INFO, "CMD: " + command + " " + punishmentType); new BasicCommand(command, "bungeecore.ban") { @Override public void execute(CommandSender sender, String[] args) { - if (punishmentType == Punishment.PunishmentType.NoDevServer && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { + if (punishmentType.isNeedsAdmin() && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { return; } if (args.length < 3) { @@ -70,7 +67,7 @@ public class PunishmentCommand { new BasicCommand(antiCommand, "bungeecore.ban") { @Override public void execute(CommandSender sender, String[] args) { - if (punishmentType == Punishment.PunishmentType.NoDevServer && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { + if (punishmentType.isNeedsAdmin() && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) { return; } if (args.length < 1) { diff --git a/src/de/steamwar/bungeecore/commands/RankedCommand.java b/src/de/steamwar/bungeecore/commands/RankedCommand.java index c4318be..f1649cb 100644 --- a/src/de/steamwar/bungeecore/commands/RankedCommand.java +++ b/src/de/steamwar/bungeecore/commands/RankedCommand.java @@ -21,7 +21,6 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.sql.Elo; -import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; diff --git a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java index e006e8e..9506ea2 100644 --- a/src/de/steamwar/bungeecore/listeners/ConnectionListener.java +++ b/src/de/steamwar/bungeecore/listeners/ConnectionListener.java @@ -27,7 +27,6 @@ import de.steamwar.bungeecore.bot.util.DiscordRanks; import de.steamwar.bungeecore.commands.ChallengeCommand; import de.steamwar.bungeecore.commands.CheckCommand; import de.steamwar.bungeecore.commands.MsgCommand; -import de.steamwar.bungeecore.sql.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.UserGroup; import net.md_5.bungee.api.AbstractReconnectHandler; @@ -35,7 +34,10 @@ import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; -import net.md_5.bungee.api.event.*; +import net.md_5.bungee.api.event.PlayerDisconnectEvent; +import net.md_5.bungee.api.event.PostLoginEvent; +import net.md_5.bungee.api.event.ServerDisconnectEvent; +import net.md_5.bungee.api.event.ServerKickEvent; import net.md_5.bungee.event.EventHandler; import java.util.*; @@ -142,13 +144,4 @@ public class ConnectionListener extends BasicListener { if(players.isEmpty() || (players.size() == 1 && players.contains(player))) ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), subserver::waitForTermination); } - - @EventHandler - public void onServerConnect(ServerConnectEvent e) { - ServerInfo server = e.getTarget(); - Subserver subserver = Subserver.getSubserver(server); - if (subserver == null) { - return; - } - } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index 872e646..02b2dea 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -129,16 +129,17 @@ public class Punishment { @AllArgsConstructor @Getter public enum PunishmentType { - Ban("BAN_TEAM_BANNED", "BANNED_MESSAGE_PERMA", "BANNED_MESSAGE_UNTIL", "UNBAN_NOT_BANNED", "UNBAN_UNBANNED"), - Mute( "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), - NoSchemReceiving("NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING", "NOSCHEMRECEIVING_MESSAGE_PERMA", "NOSCHEMRECEIVING_MESSAGE_UNTIL", "UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING", "UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING"), - NoSchemSharing("NOSCHEMSHARING_TEAM_NOSCHEMSHARING", "NOSCHEMSHARING_MESSAGE_PERMA", "NOSCHEMSHARING_MESSAGE_UNTIL", "UNNOSCHEMSHARING_NOT_NOSCHEMSHARING", "UNNOSCHEMSHARING_UNNOSCHEMSHARING"), - NoDevServer("NODEVSERVER_TEAM_NODEVSERVER", "NODEVSERVER_MESSAGE_PERMA", "NODEVSERVER_MESSAGE_UNTIL", "UNNODEVSERVER_NOT_NODEVSERVER", "UNNODEVSERVER_UNNODEVSERVER"); + Ban(false, "BAN_TEAM_BANNED", "BANNED_MESSAGE_PERMA", "BANNED_MESSAGE_UNTIL", "UNBAN_NOT_BANNED", "UNBAN_UNBANNED"), + Mute( false, "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), + NoSchemReceiving(false, "NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING", "NOSCHEMRECEIVING_MESSAGE_PERMA", "NOSCHEMRECEIVING_MESSAGE_UNTIL", "UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING", "UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING"), + NoSchemSharing(false, "NOSCHEMSHARING_TEAM_NOSCHEMSHARING", "NOSCHEMSHARING_MESSAGE_PERMA", "NOSCHEMSHARING_MESSAGE_UNTIL", "UNNOSCHEMSHARING_NOT_NOSCHEMSHARING", "UNNOSCHEMSHARING_UNNOSCHEMSHARING"), + NoDevServer(true, "NODEVSERVER_TEAM_NODEVSERVER", "NODEVSERVER_MESSAGE_PERMA", "NODEVSERVER_MESSAGE_UNTIL", "UNNODEVSERVER_NOT_NODEVSERVER", "UNNODEVSERVER_UNNODEVSERVER"); - private String teamMessage; - private String playerMessagePerma; - private String playerMessageUntil; - private String usageNotPunished; - private String unpunishmentMessage; + private final boolean needsAdmin; + private final String teamMessage; + private final String playerMessagePerma; + private final String playerMessageUntil; + private final String usageNotPunished; + private final String unpunishmentMessage; } } From 0f5087c76c81a33fab21aaf18695c0b5fd82b90d Mon Sep 17 00:00:00 2001 From: yoyosource Date: Wed, 6 Oct 2021 11:28:11 +0200 Subject: [PATCH 39/83] Add Punishment.PunishmentType.NoSchemSubmitting --- src/de/steamwar/bungeecore/BungeeCore.java | 1 + src/de/steamwar/bungeecore/sql/Punishment.java | 1 + src/de/steamwar/messages/BungeeCore.properties | 6 ++++++ 3 files changed, 8 insertions(+) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index f8b0ec2..4167c11 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -135,6 +135,7 @@ public class BungeeCore extends Plugin { new PunishmentCommand("mute", Punishment.PunishmentType.Mute); new PunishmentCommand("noschemreceiving", Punishment.PunishmentType.NoSchemReceiving); new PunishmentCommand("noschemsharing", Punishment.PunishmentType.NoSchemSharing); + new PunishmentCommand("noschemsubmitting", Punishment.PunishmentType.NoSchemSubmitting); new PunishmentCommand("nodev", Punishment.PunishmentType.NoDevServer); if(!EVENT_MODE){ diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index 02b2dea..c021f64 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -133,6 +133,7 @@ public class Punishment { Mute( false, "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), NoSchemReceiving(false, "NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING", "NOSCHEMRECEIVING_MESSAGE_PERMA", "NOSCHEMRECEIVING_MESSAGE_UNTIL", "UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING", "UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING"), NoSchemSharing(false, "NOSCHEMSHARING_TEAM_NOSCHEMSHARING", "NOSCHEMSHARING_MESSAGE_PERMA", "NOSCHEMSHARING_MESSAGE_UNTIL", "UNNOSCHEMSHARING_NOT_NOSCHEMSHARING", "UNNOSCHEMSHARING_UNNOSCHEMSHARING"), + NoSchemSubmitting(true, "NOSCHEMSUBMITTING_TEAM_NOSCHEMSUBMITTING", "NOSCHEMSUBMITTING_MESSAGE_PERMA", "NOSCHEMSUBMITTING_MESSAGE_UNTIL", "UNNOSCHEMSUBMITTING_NOT_NOSCHEMSUBMITTING", "UNNOSCHEMSUBMITTING_UNNOSCHEMSUBMITTING"), NoDevServer(true, "NODEVSERVER_TEAM_NODEVSERVER", "NODEVSERVER_MESSAGE_PERMA", "NODEVSERVER_MESSAGE_UNTIL", "UNNODEVSERVER_NOT_NODEVSERVER", "UNNODEVSERVER_UNNODEVSERVER"); private final boolean needsAdmin; diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 2fc7b51..483a2a2 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -142,6 +142,12 @@ NOSCHEMSHARING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom verteilen von schems aus UNNOSCHEMSHARING_NOT_NOSCHEMSHARING=§cDer Spieler ist nicht vom verteilen von schems ausgeschlossen. UNNOSCHEMSHARING_UNNOSCHEMSHARING=Du hast {0} das schems verteilen zurückgegeben. +NOSCHEMSUBMITTING_TEAM_NOSCHEMSUBMITTING={0} §c{1} wurde von {2} {3} vom schem einreichen ausgeschlossen. §f§lGrund§r: §f{4} +NOSCHEMSUBMITTING_MESSAGE_PERMA=§cDu bist permanent vom einreichen von schems ausgeschlossen. §f§lGrund§r: §f{0} +NOSCHEMSUBMITTING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom einreichen von schems ausgeschlossen. §f§lGrund§r: §f{1} +UNNOSCHEMSUBMITTING_NOT_NOSCHEMSUBMITTING=§cDer Spieler ist nicht vom einreichen von schems ausgeschlossen. +UNNOSCHEMSUBMITTING_UNNOSCHEMSUBMITTING=Du hast {0} das schems einreichen zurückgegeben. + NODEVSERVER_TEAM_NODEVSERVER={0} §c{1} wurde von {2} {3} vom dev server ausgeschlossen. §f§lGrund§r: §f{4} NODEVSERVER_MESSAGE_PERMA=§cDu bist permanent vom dev server ausgeschlossen. §f§lGrund§r: §f{0} NODEVSERVER_MESSAGE_UNTIL=§cDu bist bis zum {0} vom dev server ausgeschlossen. §f§lGrund§r: §f{1} From 2ef2f81496dd12e5fcf4dcca32298f81a564d6c3 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Thu, 7 Oct 2021 10:28:53 +0200 Subject: [PATCH 40/83] Update imports --- src/de/steamwar/bungeecore/commands/BauCommand.java | 1 - src/de/steamwar/bungeecore/commands/ChallengeCommand.java | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index 846af9c..b555494 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -24,7 +24,6 @@ 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.Punishment; import de.steamwar.bungeecore.sql.SteamwarUser; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; diff --git a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java index 91df5cc..1025eea 100644 --- a/src/de/steamwar/bungeecore/commands/ChallengeCommand.java +++ b/src/de/steamwar/bungeecore/commands/ChallengeCommand.java @@ -22,14 +22,13 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.sql.IgnoreSystem; -import de.steamwar.bungeecore.sql.Punishment; -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.chat.ClickEvent; import net.md_5.bungee.api.connection.ProxiedPlayer; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedList; import static de.steamwar.bungeecore.Storage.challenges; From fe2c6fc0b5cc9ed69152edb5f2d7ee3e9e18de37 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Thu, 7 Oct 2021 10:55:59 +0200 Subject: [PATCH 41/83] Update messages --- .../bungeecore/bot/commands/BanCommand.java | 2 +- .../bungeecore/bot/commands/MuteCommand.java | 2 +- .../steamwar/bungeecore/sql/Punishment.java | 12 ++-- .../steamwar/messages/BungeeCore.properties | 60 +++++++++---------- 4 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java index 5e06cb6..e328997 100644 --- a/src/de/steamwar/bungeecore/bot/commands/BanCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/BanCommand.java @@ -61,7 +61,7 @@ public class BanCommand extends BasicDiscordCommand { boolean isPerma = event.getOption("time").getAsString().equals("perma"); target.punish(Punishment.PunishmentType.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); + Message.team("BAN_TEAM", 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).queue(); } } diff --git a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java index 7847316..086cf77 100644 --- a/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java +++ b/src/de/steamwar/bungeecore/bot/commands/MuteCommand.java @@ -61,7 +61,7 @@ public class MuteCommand extends BasicDiscordCommand { boolean isPerma = event.getOption("time").getAsString().equals("perma"); target.punish(Punishment.PunishmentType.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); + Message.team("MUTE_TEAM", 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).queue(); } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index c021f64..7f9a24e 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -129,12 +129,12 @@ public class Punishment { @AllArgsConstructor @Getter public enum PunishmentType { - Ban(false, "BAN_TEAM_BANNED", "BANNED_MESSAGE_PERMA", "BANNED_MESSAGE_UNTIL", "UNBAN_NOT_BANNED", "UNBAN_UNBANNED"), - Mute( false, "MUTE_TEAM_MUTED", "MUTED_MESSAGE_PERMA", "MUTED_MESSAGE_UNTIL", "UNMUTE_NOT_MUTED", "UNMUTE_UNMUTED"), - NoSchemReceiving(false, "NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING", "NOSCHEMRECEIVING_MESSAGE_PERMA", "NOSCHEMRECEIVING_MESSAGE_UNTIL", "UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING", "UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING"), - NoSchemSharing(false, "NOSCHEMSHARING_TEAM_NOSCHEMSHARING", "NOSCHEMSHARING_MESSAGE_PERMA", "NOSCHEMSHARING_MESSAGE_UNTIL", "UNNOSCHEMSHARING_NOT_NOSCHEMSHARING", "UNNOSCHEMSHARING_UNNOSCHEMSHARING"), - NoSchemSubmitting(true, "NOSCHEMSUBMITTING_TEAM_NOSCHEMSUBMITTING", "NOSCHEMSUBMITTING_MESSAGE_PERMA", "NOSCHEMSUBMITTING_MESSAGE_UNTIL", "UNNOSCHEMSUBMITTING_NOT_NOSCHEMSUBMITTING", "UNNOSCHEMSUBMITTING_UNNOSCHEMSUBMITTING"), - NoDevServer(true, "NODEVSERVER_TEAM_NODEVSERVER", "NODEVSERVER_MESSAGE_PERMA", "NODEVSERVER_MESSAGE_UNTIL", "UNNODEVSERVER_NOT_NODEVSERVER", "UNNODEVSERVER_UNNODEVSERVER"); + Ban(false, "BAN_TEAM", "BAN_PERMA", "BAN_UNTIL", "UNBAN_ERROR", "UNBAN"), + Mute( false, "MUTE_TEAM", "MUTE_PERMA", "MUTE_UNTIL", "UNMUTE_ERROR", "UNMUTE"), + NoSchemReceiving(false, "NOSCHEMRECEIVING_TEAM", "NOSCHEMRECEIVING_PERMA", "NOSCHEMRECEIVING_UNTIL", "UNNOSCHEMRECEIVING_ERROR", "UNNOSCHEMRECEIVING"), + NoSchemSharing(false, "NOSCHEMSHARING_TEAM", "NOSCHEMSHARING_PERMA", "NOSCHEMSHARING_UNTIL", "UNNOSCHEMSHARING_ERROR", "UNNOSCHEMSHARING"), + NoSchemSubmitting(true, "NOSCHEMSUBMITTING_TEAM", "NOSCHEMSUBMITTING_PERMA", "NOSCHEMSUBMITTING_UNTIL", "UNNOSCHEMSUBMITTING_ERROR", "UNNOSCHEMSUBMITTING"), + NoDevServer(true, "NODEVSERVER_TEAM", "NODEVSERVER_PERMA", "NODEVSERVER_UNTIL", "UNNODEVSERVER_ERROR", "UNNODEVSERVER"); private final boolean needsAdmin; private final String teamMessage; diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index 483a2a2..cc7d8af 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -114,45 +114,45 @@ UNPUNISHMENT_USAGE=§8/§7{0} §8[§eSpieler§8] PUNISHMENT_UNTIL=bis zum {0} PUNISHMENT_PERMA=permanent -BAN_TEAM_BANNED={0} §c{1} wurde von {2} {3} gebannt. §f§lGrund§r: §f{4} -BANNED_MESSAGE_PERMA=§cDu bist permanent gebannt. §r§lGrund§r: §c{0} -BANNED_MESSAGE_UNTIL=§cDu bist bis zum {0} gebannt. §r§lGrund§r: §c{1} -UNBAN_NOT_BANNED=§cDer Spieler ist nicht gebannt. -UNBAN_UNBANNED=Du hast {0} entbannt. +BAN_TEAM={0} §e{1} §7wurde von §e{2} {3} §e§lgebannt§8. §7Grund§8: §f{4} +BAN_PERMA=§7Du bist §epermanent §e§lgebannt§8. §7Grund§8: §e{0} +BAN_UNTIL=§7Du bist §ebis zum {0} §e§lgebannt§8. §7Grund§8: §e{1} +UNBAN_ERROR=§cDer Spieler ist nicht gebannt. +UNBAN=§7Du hast §e{0} §e§lentbannt. BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c BAN_AVOIDING_LIST={0} §e{1} §c BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung -MUTE_TEAM_MUTED={0} §c{1} wurde von {2} {3} gemuted. §f§lGrund§r: §f{4} -MUTED_MESSAGE_PERMA=§cDu bist permanent gemuted. §r§lGrund§r: §c{0} -MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1} -UNMUTE_NOT_MUTED=§cDer Spieler ist nicht gemutet. -UNMUTE_UNMUTED=Du hast {0} entmutet. +MUTE_TEAM={0} §e{1} §7wurde von §e{2} {3} §e§lgemuted§8. §7Grund§8: §f{4} +MUTE_PERMA=§7Du bist §epermanent §e§lgemuted§8. §7Grund§8: §e{0} +MUTE_UNTIL=§7Du bist §ebis zum {0} §e§lgemuted§8. §7Grund§8: §e{1} +UNMUTE_ERROR=§cDer Spieler ist nicht gemuted. +UNMUTE=§7Du hast §e{0} §e§lentmuted. -NOSCHEMRECEIVING_TEAM_NOSCHEMRECEIVING={0} §c{1} wurde von {2} {3} vom schem erhalten ausgeschlossen. §f§lGrund§r: §f{4} -NOSCHEMRECEIVING_MESSAGE_PERMA=§cDu bist permanent vom erhalten von schems ausgeschlossen. §f§lGrund§r: §f{0} -NOSCHEMRECEIVING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom erhalten von schems ausgeschlossen. §f§lGrund§r: §f{1} -UNNOSCHEMRECEIVING_NOT_NOSCHEMRECEIVING=§cDer Spieler ist nicht vom erhalten von schems ausgeschlossen. -UNNOSCHEMRECEIVING_UNNOSCHEMRECEIVING=Du hast {0} das schems erhalten zurückgegeben. +NOSCHEMRECEIVING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematicerhalten ausgeschlossen§8. §7Grund§8: §f{4} +NOSCHEMRECEIVING_PERMA=§7Du bist §epermanent §7vom Erhalten von §e§lSchematics ausgeschlossen§8. §7Grund§8: §e{0} +NOSCHEMRECEIVING_UNTIL=§7Du bist §ebis zum {0} §7vom Erhalten von §e§lSchematics ausgeschlossen§8. §7Grund§8: §e{1} +UNNOSCHEMRECEIVING_ERROR=§cDer Spieler ist nicht vom Erhalten von Schematics ausgeschlossen. +UNNOSCHEMRECEIVING=§e{0} §7darf nun wieder §e§lSchematics erhalten§8. -NOSCHEMSHARING_TEAM_NOSCHEMSHARING={0} §c{1} wurde von {2} {3} vom schem verteilen ausgeschlossen. §f§lGrund§r: §f{4} -NOSCHEMSHARING_MESSAGE_PERMA=§cDu bist permanent vom verteilen von schems ausgeschlossen. §f§lGrund§r: §f{0} -NOSCHEMSHARING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom verteilen von schems ausgeschlossen. §f§lGrund§r: §f{1} -UNNOSCHEMSHARING_NOT_NOSCHEMSHARING=§cDer Spieler ist nicht vom verteilen von schems ausgeschlossen. -UNNOSCHEMSHARING_UNNOSCHEMSHARING=Du hast {0} das schems verteilen zurückgegeben. +NOSCHEMSHARING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematicverteilen ausgeschlossen§8. §7Grund§8: §f{4} +NOSCHEMSHARING_PERMA=§7Du bist §epermanent §7vom §e§lVerteilen von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{0} +NOSCHEMSHARING_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lVerteilen von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{1} +UNNOSCHEMSHARING_ERROR=§cDer Spieler ist nicht vom Verteilen von Schematics ausgeschlossen. +UNNOSCHEMSHARING=§e{0} §7darf nun wieder §e§lSchematics verteilen§8. -NOSCHEMSUBMITTING_TEAM_NOSCHEMSUBMITTING={0} §c{1} wurde von {2} {3} vom schem einreichen ausgeschlossen. §f§lGrund§r: §f{4} -NOSCHEMSUBMITTING_MESSAGE_PERMA=§cDu bist permanent vom einreichen von schems ausgeschlossen. §f§lGrund§r: §f{0} -NOSCHEMSUBMITTING_MESSAGE_UNTIL=§cDu bist bis zum {0} vom einreichen von schems ausgeschlossen. §f§lGrund§r: §f{1} -UNNOSCHEMSUBMITTING_NOT_NOSCHEMSUBMITTING=§cDer Spieler ist nicht vom einreichen von schems ausgeschlossen. -UNNOSCHEMSUBMITTING_UNNOSCHEMSUBMITTING=Du hast {0} das schems einreichen zurückgegeben. +NOSCHEMSUBMITTING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematiceinsenden ausgeschlossen§8. §7Grund§8: §f{4} +NOSCHEMSUBMITTING_PERMA=§7Du bist §epermanent §7vom §e§lEinsenden von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{0} +NOSCHEMSUBMITTING_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lEinsenden von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{1} +UNNOSCHEMSUBMITTING_ERROR=§cDer Spieler ist nicht vom Einsenden von Schematics ausgeschlossen. +UNNOSCHEMSUBMITTING=§e{0} §7darf nun wieder §e§lSchematis einsenden§8. -NODEVSERVER_TEAM_NODEVSERVER={0} §c{1} wurde von {2} {3} vom dev server ausgeschlossen. §f§lGrund§r: §f{4} -NODEVSERVER_MESSAGE_PERMA=§cDu bist permanent vom dev server ausgeschlossen. §f§lGrund§r: §f{0} -NODEVSERVER_MESSAGE_UNTIL=§cDu bist bis zum {0} vom dev server ausgeschlossen. §f§lGrund§r: §f{1} -UNNODEVSERVER_NOT_NODEVSERVER=§cDer Spieler ist nicht vom dev server ausgeschlossen. -UNNODEVSERVER_UNNODEVSERVER=Du hast {0} das das joinen des dev servers zurückgegeben. +NODEVSERVER_TEAM={0} §e{1} §7hat §e{2} §7mit Grund §f{4}§7 zu generft und hat daher §e§lDevserververbot §7erhalten§8, §e{3} +NODEVSERVER_PERMA=§7Du bist §epermanent §7vom §e§lDevserver §7ausgeschlossen§8. §7Grund§8: §e{0} +NODEVSERVER_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lDevserver §7ausgeschlossen§8. §7Grund§8: §e{1} +UNNODEVSERVER_ERROR=§cDer Spieler ist nicht vom Devserver ausgeschlossen. +UNNODEVSERVER=§e{0} §7darf nun wieder dem §e§lDevserver beitreten§8. #BugCommand BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. From 89f1a17c9102acc891dd310a7bcf75a962e43732 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 8 Oct 2021 07:25:06 +0200 Subject: [PATCH 42/83] Hotfix tablist Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index f82a05c..0275ce0 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -90,7 +90,6 @@ public class TablistManager extends BasicListener { //Calculate server-player-map tablist = new TablistGroup(true, ""); TablistGroup bau = new TablistGroup(false, "Bau"); - tablist.addSubTablist(bau); for (ServerInfo server : ProxyServer.getInstance().getServers().values()){ if(server.getPlayers().isEmpty()) continue; @@ -103,6 +102,8 @@ public class TablistManager extends BasicListener { else tablist.addSubTablist(new TablistServer(server)); } + if(bau.size() > 0) + tablist.addSubTablist(bau); size = (int) Math.ceil(tablist.size() / 20.0); tablists.values().forEach(Tablist::refresh); @@ -213,7 +214,7 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { subTablists.forEach(tablist -> { if(withHeaders) - viewer.setSlot(gray, "§l" + tablist.name(), 1000); + viewer.setSlot(gray, "§l§7" + tablist.name(), 1000); tablist.print(viewer, slim); if(withHeaders) viewer.setSlot(darkGray, "", 1000); From 9bf51461142c4c464710fca8130eb2c826685ef3 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 8 Oct 2021 07:27:40 +0200 Subject: [PATCH 43/83] Hotfix tablist Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 0275ce0..798f113 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -214,7 +214,7 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { subTablists.forEach(tablist -> { if(withHeaders) - viewer.setSlot(gray, "§l§7" + tablist.name(), 1000); + viewer.setSlot(gray, "§7§l" + tablist.name(), 1000); tablist.print(viewer, slim); if(withHeaders) viewer.setSlot(darkGray, "", 1000); From 1cc289c11eb7221b1cbc0a124435173178e832a1 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sat, 9 Oct 2021 12:57:53 +0200 Subject: [PATCH 44/83] Fix Bot Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/bot/events/EventManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/bot/events/EventManager.java b/src/de/steamwar/bungeecore/bot/events/EventManager.java index 398f05d..79ef2e3 100644 --- a/src/de/steamwar/bungeecore/bot/events/EventManager.java +++ b/src/de/steamwar/bungeecore/bot/events/EventManager.java @@ -93,7 +93,7 @@ public class EventManager { MessageBuilder messageBuilder = new MessageBuilder(); messageBuilder.setEmbeds(embedBuilder.build()); - if(!events.isEmpty()) { + if(events.stream().anyMatch(event -> event.getDeadline().after(Timestamp.from(Instant.now())))) { messageBuilder.setActionRows(ActionRow.of(menuBuilder.build())); } if (message == null) { From 6210cdf16dd1697a37253f947332c97addbd2865 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 9 Oct 2021 16:06:14 +0200 Subject: [PATCH 45/83] WIP tablist Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 798f113..16b49a2 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -298,10 +298,14 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { boolean sameServer = viewer.player.getServer().getInfo() == info; + //TODO: Correct size prediction + //TODO: Devserver SteamwarUser user = SteamwarUser.get(viewer.player.getUniqueId()); for(TablistPlayer player : players){ - if(sameServer || (user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam())) + if(sameServer) viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 1); + else if(user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam()) + viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 500); else if(!slim || displaySlim(viewer.player, player.player)) viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName, 500); } From 801d9da2e1b1b69a6c92d098ed59e698b4a15b08 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 9 Oct 2021 16:06:31 +0200 Subject: [PATCH 46/83] OpenJ9 Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index 465778c..a9273a9 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -32,8 +32,7 @@ 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 OPENJ9_ARGS = Arrays.asList("-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB private static final List nodes = new ArrayList<>(); @@ -74,21 +73,15 @@ public abstract class Node { 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"); + protected void constructServerstart(File directory, List cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) { + cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/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("-Xshareclasses:nonfatal,name=" + directory.getName()); + cmd.addAll(OPENJ9_ARGS); cmd.add("-jar"); cmd.add("/binarys/" + serverJar); cmd.add("--log-strip-color"); @@ -126,7 +119,7 @@ public abstract class Node { @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); + constructServerstart(directory, cmd, serverJar, worldDir, levelName, port, xmx, dParams); ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(directory); return builder; @@ -172,7 +165,7 @@ public abstract class Node { public RemoteNode(String remote) { this.remote = remote; - //Determin core count + //Determine core count Process process; try { process = new ProcessBuilder("ssh", remote, "nproc").start(); @@ -213,7 +206,7 @@ public abstract class Node { cmd.add("cd"); cmd.add(directory.getPath()); cmd.add(";"); - constructServerstart(cmd, serverJar, worldDir, levelName, port, xmx, dParams); + constructServerstart(directory, cmd, serverJar, worldDir, levelName, port, xmx, dParams); return new ProcessBuilder(cmd); } From 0c5c9e7d42c8e38ca8bc28c73381349c65cbbcc0 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 9 Oct 2021 21:53:50 +0200 Subject: [PATCH 47/83] Reduce arena RAM Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/SubserverSystem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index 66ec037..dc10eaa 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -107,7 +107,7 @@ public class SubserverSystem { File directory = new File(SERVER_PATH, modus.getFolder()); ProcessBuilder builder = node.startServer( - modus.serverJar(), directory, worldDir, mapName, port, "2G", + modus.serverJar(), directory, worldDir, mapName, port, "512M", "logPath=" + mapName, "config=" + modus.getConfig(), "fightID=" + eventFightID, "ranked=" + ranked, "checkSchemID=" + checkSchemID, "prepareSchemID=" + prepareSchemID, From 2352410f2bacf764a8d4d7c5600dc9fe9e7ee583 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 9 Oct 2021 22:51:08 +0200 Subject: [PATCH 48/83] Fix tablist issues Signed-off-by: Lixfel --- .../bungeecore/commands/DevCommand.java | 100 +++++++++++------- .../bungeecore/listeners/TablistManager.java | 50 ++++----- 2 files changed, 82 insertions(+), 68 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/DevCommand.java b/src/de/steamwar/bungeecore/commands/DevCommand.java index dcc4b7f..6794b8d 100644 --- a/src/de/steamwar/bungeecore/commands/DevCommand.java +++ b/src/de/steamwar/bungeecore/commands/DevCommand.java @@ -20,6 +20,7 @@ package de.steamwar.bungeecore.commands; import de.steamwar.bungeecore.Message; +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; @@ -27,14 +28,15 @@ import net.md_5.bungee.api.connection.ProxiedPlayer; import java.io.File; import java.net.InetSocketAddress; -import java.util.Arrays; import java.util.Collections; -import java.util.function.Predicate; +import java.util.HashMap; +import java.util.Map; import java.util.stream.Collectors; public class DevCommand extends BasicCommand { - private final File DevServerDir = new File("/configs/DevServer"); + private final File devServerDir = new File("/configs/DevServer"); + private final Map devServers = new HashMap<>(); public DevCommand() { super("dev", ""); @@ -42,56 +44,74 @@ public class DevCommand extends BasicCommand { @Override public void execute(CommandSender sender, String[] args) { - if (!(sender instanceof ProxiedPlayer)) { + if (!(sender instanceof ProxiedPlayer)) return; - } - String[] devServer = DevServerDir.list(); - if (devServer == null || devServer.length == 0) { + ProxiedPlayer player = (ProxiedPlayer) sender; + + updateDevServers(); + if(devServers.isEmpty()) { Message.send("DEV_NO_SERVER", sender); - } else if (devServer.length == 1) { - String[] server = devServer[0].split("\\."); - sendToServer((ProxiedPlayer) sender, server[0], Integer.parseInt(server[1])); + } else if (devServers.size() == 1) { + player.connect(devServers.values().stream().findAny().get()); + } else if (args.length == 0) { + ServerInfo info = devServers.get(player.getName().toLowerCase()); + if (info == null) { + Message.send("DEV_UNKNOWN_SERVER", player); + return; + } + + player.connect(info); } else { - if (args.length == 0) { - 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)); + ServerInfo info = devServers.get(args[0].toLowerCase()); + if (info == null) { + Message.send("DEV_NO_SERVER", player); + return; } - } - } - private void send(String[] devServer, ProxiedPlayer sender, Predicate test, Runnable error) { - for (String s : devServer) { - String[] server = s.split("\\."); - if (test.test(server[0])) { - sendToServer(sender, server[0], Integer.parseInt(server[1])); - break; - } + player.connect(info); } - error.run(); - } - - private void sendToServer(ProxiedPlayer proxiedPlayer, String name, int port) { - InetSocketAddress address = new InetSocketAddress("127.0.0.1", port); - ServerInfo serverInfo = ProxyServer.getInstance().constructServerInfo("Dev-" + name, address, "SteamWar.de - Subserver", false); - proxiedPlayer.connect(serverInfo); } @Override public Iterable onTabComplete(CommandSender sender, String[] args) { - if (!(sender instanceof ProxiedPlayer)) { + if (!(sender instanceof ProxiedPlayer) || args.length > 1) { return Collections.emptyList(); } - String[] devSever = DevServerDir.list(); - if (devSever == null) { - return Collections.emptyList(); - } - if (args.length > 1) { - return Collections.emptyList(); - } - return Arrays.stream(devSever).map(s -> s.split("\\.")).map(s -> s[0]).filter(s -> { + + updateDevServers(); + return devServers.keySet().stream().filter(s -> { if (args.length == 0) return true; - return s.startsWith(args[0]); + return s.startsWith(args[0].toLowerCase()); }).collect(Collectors.toList()); } + + private void updateDevServers() { + String[] serverFiles = devServerDir.list(); + + Map devServerFiles = new HashMap<>(); + if(serverFiles != null) { + for(String serverFile : serverFiles) { + String[] server = serverFile.split("\\."); + devServerFiles.put(server[0], Integer.parseInt(server[1])); + } + } + + devServers.entrySet().removeIf(entry -> { + if(!devServerFiles.containsKey(entry.getKey())) { + ProxyServer.getInstance().getServers().remove(entry.getValue().getName()); + return true; + } + return false; + }); + + devServerFiles.forEach((key, value) -> { + if (devServers.containsKey(key)) + return; + + SteamwarUser user = SteamwarUser.get(key); + ServerInfo info = ProxyServer.getInstance().constructServerInfo("Dev " + user.getUserName(), new InetSocketAddress("127.0.0.1", value), "SteamWar.de - Subserver", false); + ProxyServer.getInstance().getServers().put(info.getName(), info); + devServers.put(user.getUserName().toLowerCase(), info); + }); + } } diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 16b49a2..506fbe0 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -81,9 +81,7 @@ public class TablistManager extends BasicListener { throw new SecurityException("Could not load icons", e); } - for(ProxiedPlayer p : ProxyServer.getInstance().getPlayers()){ - tablists.put(p, new Tablist(p)); - } + ProxyServer.getInstance().getPlayers().forEach(p -> tablists.put(p, new Tablist(p))); } private synchronized void updateTablist(){ @@ -161,6 +159,9 @@ public class TablistManager extends BasicListener { } private void setSlot(Icon icon, String name, int ping){ + if(pos / 20 >= getColumns()) + return; + setSlot(pos % 20, pos / 20, icon, name, ping); pos++; } @@ -191,17 +192,14 @@ public class TablistManager extends BasicListener { @Override public int size() { - int size = subTablists.stream().map(TablistPart::size).reduce(Integer::sum).orElse(0); - if(withHeaders) - size += Math.min(subTablists.size() - 1, 0); - return size; + return slimSize(null); } @Override public int slimSize(ProxiedPlayer viewer) { - int size = subTablists.stream().map(tablist -> tablist.slimSize(viewer)).reduce(Integer::sum).orElse(0); + int size = subTablists.stream().mapToInt(tPart -> viewer == null ? tPart.size() : tPart.slimSize(viewer)).sum(); if(withHeaders) - size += Math.min(subTablists.size() - 1, 0); + size += subTablists.size() + Math.min(subTablists.size() - 1, 0); return size; } @@ -212,10 +210,10 @@ public class TablistManager extends BasicListener { @Override public void print(Tablist viewer, boolean slim) { - subTablists.forEach(tablist -> { + subTablists.forEach(tPart -> { if(withHeaders) - viewer.setSlot(gray, "§7§l" + tablist.name(), 1000); - tablist.print(viewer, slim); + viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); + tPart.print(viewer, slim); if(withHeaders) viewer.setSlot(darkGray, "", 1000); }); @@ -256,13 +254,14 @@ public class TablistManager extends BasicListener { private TablistServer(ServerInfo info) { this.info = info; subserver = Subserver.getSubserver(info); - for(ProxiedPlayer player : info.getPlayers()){ - players.add(new TablistPlayer(player, SteamwarUser.get(player.getUniqueId()).getUserGroup().getColorCode() + player.getName())); - } + info.getPlayers().forEach(player -> players.add(new TablistPlayer(player, SteamwarUser.get(player.getUniqueId()).getUserGroup().getColorCode() + player.getName()))); players.sort((tp1, tp2) -> tp1.player.getName().compareToIgnoreCase(tp2.player.getName())); } private boolean displaySlim(ProxiedPlayer viewer, ProxiedPlayer player){ + if(viewer.getServer().getInfo() == info) + return true; + if(subserver != null && subserver.getType() == Servertype.ARENA && info.getPlayers().size() == 1) return true; @@ -275,7 +274,7 @@ public class TablistManager extends BasicListener { @Override public int size() { - return 1 + players.size(); + return players.size(); } @Override @@ -283,10 +282,7 @@ public class TablistManager extends BasicListener { if(viewer.getServer().getInfo() == info) return size(); - int size = 1; - for(TablistPlayer player : players) - size += displaySlim(viewer, player.player) ? 1 : 0; - return size; + return players.stream().mapToInt(player -> displaySlim(viewer, player.player) ? 1 : 0).sum(); } @Override @@ -298,16 +294,14 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { boolean sameServer = viewer.player.getServer().getInfo() == info; - //TODO: Correct size prediction - //TODO: Devserver SteamwarUser user = SteamwarUser.get(viewer.player.getUniqueId()); for(TablistPlayer player : players){ - if(sameServer) - viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 1); - else if(user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam()) - viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName.startsWith("§7") ? "§f" + player.player.getName() : player.defaultName, 500); - else if(!slim || displaySlim(viewer.player, player.player)) - viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), player.defaultName, 500); + if(slim && !displaySlim(viewer.player, player.player)) + continue; + + int ping = sameServer ? 1 : 500; + String name = player.defaultName.startsWith("§7") && user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam() ? "§f" + player.player.getName() : player.defaultName; + viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), name, ping); } } } From adeb5de0340e2f727d52ce6241fb99d1c5b69c8e Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 10 Oct 2021 08:20:30 +0200 Subject: [PATCH 49/83] Fix whois NPE on never connected user Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 2643d62..0599bc1 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -329,7 +329,7 @@ public class SteamwarUser { public double getOnlinetime() { return getPlaytime.select(rs -> { - if(rs.next()) + if(rs.next() && rs.getBigDecimal("Playtime") != null) return rs.getBigDecimal("Playtime").doubleValue(); return 0.0; }, id); From d37a68f373265d25df4ae01da5ca84ea5bcfdc38 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 12 Oct 2021 13:11:23 +0200 Subject: [PATCH 50/83] Fix missing log4jconfiguration file Signed-off-by: Lixfel --- 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 a9273a9..267cd42 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -32,7 +32,7 @@ import java.util.logging.Level; public abstract class Node { - private static final List OPENJ9_ARGS = Arrays.asList("-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings"); + private static final List OPENJ9_ARGS = Arrays.asList("-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-Dlog4j.configurationFile=log4j2.xml"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB private static final List nodes = new ArrayList<>(); From 1c3208934d83beb944e8d5cea80a9d69e6aa4904 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 12 Oct 2021 13:42:47 +0200 Subject: [PATCH 51/83] Fix FAWE 1.9-1.12 Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index 267cd42..f9a9e0c 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -32,6 +32,7 @@ import java.util.logging.Level; public abstract class Node { + private static final List OPENJDK8_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", "-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); private static final List OPENJ9_ARGS = Arrays.asList("-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-Dlog4j.configurationFile=log4j2.xml"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB @@ -74,14 +75,22 @@ public abstract class Node { public abstract double getLoad(); protected void constructServerstart(File directory, List cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) { - cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/java"); + boolean openjdk8 = !serverJar.contains("1.8.9") && !serverJar.contains("1.15.2"); + if(openjdk8) + cmd.add("java"); + else + cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/java"); for(String param : dParams){ cmd.add("-D" + param); } cmd.add("-Xmx" + xmx); - cmd.add("-Xshareclasses:nonfatal,name=" + directory.getName()); - cmd.addAll(OPENJ9_ARGS); + if(openjdk8) + cmd.addAll(OPENJDK8_ARGS); + else { + cmd.add("-Xshareclasses:nonfatal,name=" + directory.getName()); + cmd.addAll(OPENJ9_ARGS); + } cmd.add("-jar"); cmd.add("/binarys/" + serverJar); cmd.add("--log-strip-color"); From eb8b5e3bc60380bf472321c18e7b5b1af0e42adf Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 12 Oct 2021 18:07:28 +0200 Subject: [PATCH 52/83] Fix tablist size Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 506fbe0..b4d6ac1 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -199,7 +199,7 @@ public class TablistManager extends BasicListener { public int slimSize(ProxiedPlayer viewer) { int size = subTablists.stream().mapToInt(tPart -> viewer == null ? tPart.size() : tPart.slimSize(viewer)).sum(); if(withHeaders) - size += subTablists.size() + Math.min(subTablists.size() - 1, 0); + size += subTablists.size() * 2; return size; } From 317df7b7a853a037cc7d2fef192741d73a66a7af Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 22 Oct 2021 20:13:31 +0200 Subject: [PATCH 53/83] Improved stability Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 4 ++-- src/de/steamwar/bungeecore/Node.java | 2 +- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 9 +++------ 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index e834234..65fd3ce 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -92,8 +92,8 @@ public class BungeeCore extends Plugin { new BrandListener(); new Node.LocalNode(); - new Node.RemoteNode("lx"); - new Node.RemoteNode("az"); + //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 f9a9e0c..8f8d95f 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -33,7 +33,7 @@ import java.util.logging.Level; public abstract class Node { private static final List OPENJDK8_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", "-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); - private static final List OPENJ9_ARGS = Arrays.asList("-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-Dlog4j.configurationFile=log4j2.xml"); + private static final List OPENJ9_ARGS = Arrays.asList("-Xgc:excessiveGCratio=80", "-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-Dlog4j.configurationFile=log4j2.xml"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB private static final List nodes = new ArrayList<>(); diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index e721913..ccc174e 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -37,10 +37,7 @@ import java.sql.ResultSet; import java.sql.SQLException; 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.*; import java.util.logging.Level; @@ -207,8 +204,8 @@ public class SteamwarUser { final URL url = new URL(API_URL + playerName); 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) { - BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID", e); + } catch (NoSuchElementException | IOException e) { + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID " + playerName, e); return null; } } From 9ba20d7426d98d2711e48c4d58ae0c793e2d6966 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 24 Oct 2021 16:26:27 +0200 Subject: [PATCH 54/83] Ciao on OutOfMemory! Signed-off-by: Lixfel --- 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 8f8d95f..9c714c6 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -33,7 +33,7 @@ import java.util.logging.Level; public abstract class Node { private static final List OPENJDK8_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", "-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); - private static final List OPENJ9_ARGS = Arrays.asList("-Xgc:excessiveGCratio=80", "-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-Dlog4j.configurationFile=log4j2.xml"); + private static final List OPENJ9_ARGS = Arrays.asList("-Xgc:excessiveGCratio=80", "-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-XX:-HeapDumpOnOutOfMemory", "-XX:+ExitOnOutOfMemoryError", "-Dlog4j.configurationFile=log4j2.xml"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB private static final List nodes = new ArrayList<>(); From 62681be8d4b7e3dfd4b6b41a65e982134f17f02c Mon Sep 17 00:00:00 2001 From: Lixfel Date: Mon, 25 Oct 2021 09:13:48 +0200 Subject: [PATCH 55/83] Comma seperated team info Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/commands/TeamCommand.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/TeamCommand.java b/src/de/steamwar/bungeecore/commands/TeamCommand.java index 3889da2..58a3c35 100644 --- a/src/de/steamwar/bungeecore/commands/TeamCommand.java +++ b/src/de/steamwar/bungeecore/commands/TeamCommand.java @@ -441,10 +441,7 @@ public class TeamCommand extends BasicCommand { Set events = TeamTeilnahme.getEvents(team.getTeamId()); if(!events.isEmpty()){ - StringBuilder sb = new StringBuilder(); - for(Event e : events) - sb.append(e.getEventName()).append(" "); - Message.sendPrefixless("TEAM_INFO_EVENTS", player, sb.toString()); + Message.sendPrefixless("TEAM_INFO_EVENTS", player, events.stream().map(Event::getEventName).collect(Collectors.joining(", "))); } } From 87641dbfc253a082a48a714912b6597c35b69ac6 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Mon, 25 Oct 2021 09:16:01 +0200 Subject: [PATCH 56/83] Prevent ConcurrentModException Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index b4d6ac1..59f44bf 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -88,7 +88,7 @@ public class TablistManager extends BasicListener { //Calculate server-player-map tablist = new TablistGroup(true, ""); TablistGroup bau = new TablistGroup(false, "Bau"); - for (ServerInfo server : ProxyServer.getInstance().getServers().values()){ + for (ServerInfo server : ProxyServer.getInstance().getServersCopy().values()){ if(server.getPlayers().isEmpty()) continue; From 75d5e00c68033d40ea3e9b08e678951cb36b1470 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 26 Oct 2021 17:08:48 +0200 Subject: [PATCH 57/83] Reduce OOM-Crashes Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/SubserverSystem.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index dc10eaa..9e08df5 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -107,7 +107,7 @@ public class SubserverSystem { File directory = new File(SERVER_PATH, modus.getFolder()); ProcessBuilder builder = node.startServer( - modus.serverJar(), directory, worldDir, mapName, port, "512M", + modus.serverJar(), directory, worldDir, mapName, port, "768M", "logPath=" + mapName, "config=" + modus.getConfig(), "fightID=" + eventFightID, "ranked=" + ranked, "checkSchemID=" + checkSchemID, "prepareSchemID=" + prepareSchemID, @@ -169,7 +169,7 @@ public class SubserverSystem { private static void sendToBau15(ProxiedPlayer p, UUID owner, String serverJar){ SteamwarUser user = SteamwarUser.get(owner); - sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, serverJar, "/home/minecraft/userworlds15", String.valueOf(user.getId()), "512M", "Bau15"); + sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, serverJar, "/home/minecraft/userworlds15", String.valueOf(user.getId()), "768M", "Bau15"); } public static void sendToBau15(ProxiedPlayer p, UUID owner){ From 3ac81810c43274b5f1f82314e1cdf31d8e81c338 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Fri, 12 Nov 2021 15:52:15 +0100 Subject: [PATCH 58/83] Fixing Merge Conflicts & Updating! --- .../bot/events/SchematicsManager.java | 6 +- .../bungeecore/commands/CheckCommand.java | 16 +- .../bungeecore/sql/CheckedSchematic.java | 87 ++++++-- .../steamwar/bungeecore/sql/NodeMember.java | 43 ++-- .../bungeecore/sql/SchematicNode.java | 204 +++++++++--------- 5 files changed, 194 insertions(+), 162 deletions(-) diff --git a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java index 82a8370..e407cf9 100644 --- a/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java +++ b/src/de/steamwar/bungeecore/bot/events/SchematicsManager.java @@ -53,13 +53,13 @@ public class SchematicsManager { CheckCommand.getSchemsToCheck().forEach(schematic -> { StringBuilder st = new StringBuilder(); - st.append("Typ: ").append(schematic.getSchemType().getKuerzel()); - st.append("\nVon: ").append(SteamwarUser.get(schematic.getSchemOwner()).getUserName()); + st.append("Typ: ").append(schematic.getSchemtype().getKuerzel()); + st.append("\nVon: ").append(SteamwarUser.get(schematic.getOwner()).getUserName()); String checker = CheckCommand.getChecker(schematic); if (checker != null) { st.append("\nWird Geprüft von: ").append(checker); } - embedBuilder.addField(schematic.getSchemName(), st.toString(), true); + embedBuilder.addField(schematic.getName(), st.toString(), true); }); MessageBuilder messageBuilder = new MessageBuilder(); diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index bbfd55f..3ae1626 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -111,7 +111,7 @@ public class CheckCommand extends BasicCommand { } } - private static List getSchemsToCheck(){ + public static List getSchemsToCheck(){ List schematicList = new LinkedList<>(); for (SchematicType type : SchematicType.values()) { @@ -243,8 +243,8 @@ public class CheckCommand extends BasicCommand { SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getId(), 0); currentCheckers.put(checker.getUniqueId(), this); currentSchems.put(schematic.getId(), this); - for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic.getId())) - Message.sendPrefixless("CHECK_SCHEMATIC_PREVIOUS", checker, previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getReason()); + for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic)) + Message.sendPrefixless("CHECK_SCHEMATIC_PREVIOUS", checker, previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getDeclineReason()); next(0); }); } @@ -294,7 +294,7 @@ public class CheckCommand extends BasicCommand { } schematic.setType(schematic.getSchemtype().fightType().toDB()); - CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben"); + CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben"); SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) { @@ -308,7 +308,7 @@ public class CheckCommand extends BasicCommand { private void decline(String reason){ schematic.setType(SchematicType.Normal.toDB()); - CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason); + CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason); SteamwarUser user = SteamwarUser.get(schematic.getOwner()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); if(player != null) { @@ -321,13 +321,13 @@ public class CheckCommand extends BasicCommand { } private void abort(){ - CheckedSchematic.create(schematic.getId(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen"); + CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen"); stop(); } private void stop(){ currentCheckers.remove(checker.getUniqueId()); - currentSchems.remove(schematic.getSchemID()); + currentSchems.remove(schematic.getId()); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(checker.getUniqueId())) { @@ -340,7 +340,7 @@ public class CheckCommand extends BasicCommand { private void remove() { currentCheckers.remove(checker.getUniqueId()); - currentSchems.remove(schematic.getSchemID()); + currentSchems.remove(schematic.getId()); } } } diff --git a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java index 499a2f0..82b7133 100644 --- a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java +++ b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java @@ -24,56 +24,97 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; +import java.util.UUID; 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; + private static final Statement checkHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId IN (SELECT NodeId FROM SchematicNode WHERE NodeOwner = ?) AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' AND NodeId is not NULL ORDER BY EndTime DESC"); + private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); + private static final Statement insert = new Statement("INSERT INTO CheckedSchematic (NodeId, NodeName, NodeOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?)"); + private final Integer node; private final int validator; private final Timestamp startTime; private final Timestamp endTime; - private final String reason; + private final String declineReason; private CheckedSchematic(ResultSet rs) throws SQLException { - nodeId = rs.getInt("NodeId"); - validator = rs.getInt("Validator"); - startTime = rs.getTimestamp("StartTime"); - endTime = rs.getTimestamp("EndTime"); - reason = rs.getString("DeclineReason"); + this.node = rs.getInt("NodeId"); + this.validator = rs.getInt("Validator"); + this.startTime = rs.getTimestamp("StartTime"); + this.endTime = rs.getTimestamp("EndTime"); + this.declineReason = rs.getString("DeclineReason"); } - 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); + public static void create(int nodeId, String name, int owner, int validator, Timestamp startTime, Timestamp endTime, String reason){ + insert.update(nodeId, name, owner, 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 { + public static void create(SchematicNode node, int validator, Timestamp startTime, Timestamp endTime, String reason){ + create(node.getId(), node.getName(), node.getOwner(), validator, startTime, endTime, reason); + } + + public static List previousChecks(SchematicNode node){ + return nodeHistory.select(rs -> { + List schematics = new ArrayList<>(); while(rs.next()) schematics.add(new CheckedSchematic(rs)); return schematics; - }, schemName, schemOwner); + }, node.getId()); + } + + public static List getLastDeclinedOfNode(SchematicNode node){ + return getLastDeclinedOfNode(node.getId()); + } + + public static List getLastDeclinedOfNode(int node){ + return nodeHistory.select(rs -> { + List lastDeclined = new ArrayList<>(); + while(rs.next()){ + lastDeclined.add(new CheckedSchematic(rs)); + } + return lastDeclined; + }, node); + } + + public static List getLastDeclined(UUID uuid){ + return getLastDelined(SteamwarUser.get(uuid).getId()); + } + + public static List getLastDelined(int schemOwner){ + return checkHistory.select(rs -> { + List history = new ArrayList<>(); + while(rs.next()) + history.add(new CheckedSchematic(rs)); + return history; + }, schemOwner); } public int getValidator() { return validator; } + public Timestamp getStartTime() { + return startTime; + } + public Timestamp getEndTime() { return endTime; } - public String getReason() { - return reason; + public String getDeclineReason() { + return declineReason; } - public int getNodeId() { - return nodeId; + public int getNode() { + return node; + } + + public String getSchemName() { + return SchematicNode.getSchematicNode(node).getName(); + } + + public int getSchemOwner() { + return SchematicNode.getSchematicNode(node).getId(); } } diff --git a/src/de/steamwar/bungeecore/sql/NodeMember.java b/src/de/steamwar/bungeecore/sql/NodeMember.java index 76c91e4..063dd48 100644 --- a/src/de/steamwar/bungeecore/sql/NodeMember.java +++ b/src/de/steamwar/bungeecore/sql/NodeMember.java @@ -25,43 +25,40 @@ import java.util.HashSet; import java.util.Set; public class NodeMember { + private static final Statement getNodeMember = new Statement("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?"); + private static final Statement getNodeMembers = new Statement("SELECT * FROM NodeMember WHERE NodeId = ?"); + private static final Statement getSchematics = new Statement("SELECT * FROM NodeMember WHERE UserId = ?"); + private static final Statement createNodeMember = new Statement("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)"); + private static final Statement deleteNodeMember = new Statement("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?"); + public static NodeMember getNodeMember(int node, int member) { - ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?", node, member); - try { - if(!set.next()) + return getNodeMember.select(rs -> { + if(!rs.next()) return null; - return new NodeMember(set); - } catch (SQLException e) { - throw new SecurityException("Could not load NodeMember", e); - } + return new NodeMember(rs); + }, node, member); } public static Set getNodeMembers(int node) { - ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE NodeId = ?", node); - try { + return getNodeMembers.select(rs -> { Set members = new HashSet<>(); - while (set.next()) - members.add(new NodeMember(set)); + while (rs.next()) + members.add(new NodeMember(rs)); return members; - } catch (SQLException e) { - throw new SecurityException("Could not load NodeMember", e); - } + }, node); } public static Set getSchematics(int member) { - ResultSet set = SQL.select("SELECT * FROM NodeMember WHERE UserId = ?", member); - try { + return getSchematics.select(rs -> { Set members = new HashSet<>(); - while (set.next()) - members.add(new NodeMember(set)); + while (rs.next()) + members.add(new NodeMember(rs)); return members; - } catch (SQLException e) { - throw new SecurityException("Could not load NodeMember", e); - } + }, member); } public static NodeMember createNodeMember(int node, int member) { - SQL.update("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)", node, member); + createNodeMember.update(node, member); return getNodeMember(node, member); } @@ -82,6 +79,6 @@ public class NodeMember { } public void delete() { - SQL.update("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?", node, member); + deleteNodeMember.update(node, member); } } diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java index c419c09..b111a2d 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicNode.java +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -29,6 +29,23 @@ import java.util.function.Predicate; public class SchematicNode { + private static final Statement createNode = new Statement("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)"); + private static final Statement getSchematicNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); + private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); + private static final Statement getSchematicsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL"); + private static final Statement getSchematicsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ?"); + private static final Statement getSchematicDirectory_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL"); + private static final Statement getSchematicDirectory = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?"); + private static final Statement getSchematicNodeO_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL"); + private static final Statement getSchematicNodeO = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?"); + private static final Statement getSchematicNodeId = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?"); + private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?"); + private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?"); + private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName"); + private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); + private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?"); + private static final Statement deleteNode = new Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); + public static SchematicNode createSchematic(int owner, String name, Integer parent) { return createSchematicNode(owner, name, parent, SchematicType.Normal.toDB(), ""); } @@ -40,8 +57,7 @@ public class SchematicNode { public static SchematicNode createSchematicNode(int owner, String name, Integer parent, String type, String item) { if (parent == 0) parent = null; - SQL.update("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)", - name, owner, parent, type, item); + createNode.update(name, owner, parent, type, item); return getSchematicNode(owner, name, parent); } @@ -77,105 +93,85 @@ public class SchematicNode { } public static SchematicNode getSchematicNode(int owner, String name, Integer parent) { - if (parent != null && parent == 0) + if (parent != null && parent == 0) { parent = null; - ResultSet set; - if (parent == null) { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL", owner, name); - } else { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?", owner, name, parent); } - try { - while (set.next()) { - SchematicNode node = new SchematicNode(set); + Statement.ResultSetUser user = rs -> { + while (rs.next()) { + SchematicNode node = new SchematicNode(rs); return node; } - List nodes = getSchematicNodeInNode(parent); - for (SchematicNode node:nodes) { - if (node.name.equals(name) && NodeMember.getNodeMember(node.getId(), owner) != null) - return node; - } return null; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); + }; + if(parent == null) { + return getSchematicNode_Null.select(user, owner, name); + } else { + return getSchematicNode.select(user, owner, name, parent); } } public static List getSchematicNodeInNode(Integer parent) { if(parent != null && parent == 0) parent = null; - ResultSet set; - if(parent == null) { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL"); - }else { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ?", parent); - } - try { + Statement.ResultSetUser> user = rs -> { List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); + while (rs.next()) + nodes.add(new SchematicNode(rs)); return nodes; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); + }; + if(parent == null) { + return getSchematicsInNode_Null.select(user); + }else { + return getSchematicsInNode.select(user, parent); } } public static SchematicNode getSchematicDirectory(String name, Integer parent) { if(parent != null && parent == 0) parent = null; - ResultSet set; - if(parent == null) { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name, parent); - }else { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); - } - try { - while (set.next()) { - SchematicNode node = new SchematicNode(set); + Statement.ResultSetUser user = rs -> { + while (rs.next()) { + SchematicNode node = new SchematicNode(rs); if(node.isDir()) return node; } return null; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); + }; + + if(parent == null) { + return getSchematicDirectory_Null.select(user, name); + }else { + return getSchematicDirectory.select(user, name, parent); } } - public static SchematicNode getSchematicInParent(String name, Integer parent) { + public static SchematicNode getSchematicNode(String name, Integer parent) { if(parent != null && parent == 0) parent = null; - ResultSet set; - if(parent == null) { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL", name); - }else { - set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?", name, parent); - } - try { - while (set.next()) { - SchematicNode node = new SchematicNode(set); - if(!node.isDir()) - return node; + Statement.ResultSetUser user = rs -> { + while (rs.next()) { + return new SchematicNode(rs); } return null; - }catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); + }; + if(parent == null) { + return getSchematicNodeO_Null.select(user, name); + }else { + return getSchematicNodeO.select(user, name, parent); } } public static SchematicNode getSchematicNode(int id) { - ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?", id); - try { - if (!set.next()) + return getSchematicNodeId.select(rs -> { + if (!rs.next()) return null; - return new SchematicNode(set); - } catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } + return new SchematicNode(rs); + }); } public static List getSchematicsOfType(int owner, String schemType, Integer parent) { List schems = getAllSchematicsAccessibleByUser(owner); - schems.removeIf(node -> !node.getType().equals(schemType)); + schems.removeIf(node -> node.isDir() || !node.getType().equals(schemType)); Map nodesInParent = new LinkedHashMap<>(); for (SchematicNode schematicNode : schems) { SchematicNode currentNode = schematicNode; @@ -188,27 +184,22 @@ public class SchematicNode { } public static List getAllSchematicsOfType(int owner, String schemType) { - ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?", owner, schemType); - try { + return getAllSchemsOfTypeOwner.select(rs -> { List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); + while (rs.next()) + nodes.add(new SchematicNode(rs)); return nodes; - } catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } + }, owner, schemType); } + public static List getAllSchematicsOfType(String schemType) { - ResultSet set = SQL.select("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?", schemType); - try { + return getAllSchemsOfType.select(rs -> { List nodes = new ArrayList<>(); - while (set.next()) - nodes.add(new SchematicNode(set)); + while (rs.next()) + nodes.add(new SchematicNode(rs)); return nodes; - } catch (SQLException e) { - throw new SecurityException("Failed to load Schemnodes", e); - } + }, schemType); } public static List deepGet(Integer parent, Predicate filter) { @@ -241,29 +232,29 @@ public class SchematicNode { if(isAdded) return getSchematicNodeInNode(parent); } else { - ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName", user, user); - try{ + return getAccessibleByUser.select(rs -> { List nodes = new ArrayList<>(); - while(set.next()) - nodes.add(new SchematicNode(set)); + while(rs.next()) + nodes.add(new SchematicNode(rs)); return nodes; - }catch(SQLException e){ - throw new SecurityException("Failed listing schematics", e); - } + }, user, user); } return Collections.emptyList(); } public static List getAllSchematicsAccessibleByUser(int user) { - ResultSet set = SQL.select("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember nm ON nm.NodeId = s.NodeId WHERE s.NodeOwner = ? OR nm.UserId = ? GROUP BY s.NodeId ORDER BY s.NodeName", user, user); - try{ + return getAccessibleByUser.select(rs -> { List nodes = new ArrayList<>(); - while(set.next()) - nodes.add(new SchematicNode(set)); + while(rs.next()) { + SchematicNode node = new SchematicNode(rs); + if(node.isDir()) { + nodes.addAll(deepGet(node.getId(), node1 -> true)); + } else { + nodes.add(node); + } + } return nodes; - }catch(SQLException e){ - throw new SecurityException("Failed listing schematics", e); - } + }, user, user); } private final int id; @@ -275,6 +266,7 @@ public class SchematicNode { private boolean schemFormat; private int rank; private final boolean isDir; + private Map brCache = new HashMap<>(); public static List filterSchems(int user, Predicate filter) { List finalList = new ArrayList<>(); @@ -291,14 +283,12 @@ public class SchematicNode { } public static Integer countNodes() { - ResultSet set = SQL.select("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); - try { - if (set.next()) - return set.getInt("count"); + return countNodes.select(rs -> { + if (rs.next()) { + return rs.getInt("count"); + } return 0; - } catch (SQLException e) { - throw new SecurityException("Failed listing schematics", e); - } + }); } public int getId() { @@ -322,7 +312,7 @@ public class SchematicNode { return parent; } - public void setParent(int parent) { + public void setParent(Integer parent) { this.parent = parent; updateDB(); } @@ -394,7 +384,7 @@ public class SchematicNode { } public String generateBreadcrumbs(SteamwarUser user) { - return generateBreadcrumbs("/", user); + return brCache.computeIfAbsent(user.getId(), integer -> generateBreadcrumbs("/", user)); } public String generateBreadcrumbs(String split, SteamwarUser user) { @@ -413,20 +403,24 @@ public class SchematicNode { } private void updateDB() { - SQL.update("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?", - name, owner, parent == 0 ? null : parent, item, type, rank, id); + updateDB.update(name, owner, parent == 0 ? null : parent, item, type, rank, id); this.lastUpdate = Timestamp.from(Instant.now()); + this.brCache.clear(); } public void delete() { if (isDir()) { getSchematicNodeInNode(getId()).forEach(SchematicNode::delete); } - SQL.update("DELETE FROM SchematicNode WHERE NodeId = ?", id); + deleteNode.update(id); } - private void updateDatabase(Blob blob, boolean newFormat) { - SQL.update("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?", blob, newFormat, id); - schemFormat = newFormat; + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SchematicNode)) + return false; + + SchematicNode node = (SchematicNode) obj; + return node.getId() == id; } } From e32a2234768e133c1a201a06750b4fb646fa0b3b Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 12 Nov 2021 17:14:56 +0100 Subject: [PATCH 59/83] Using new config Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ArenaMode.java | 41 ++++++++----- src/de/steamwar/bungeecore/BungeeCore.java | 3 - .../bungeecore/commands/CheckCommand.java | 13 +--- .../bungeecore/sql/SchematicType.java | 59 +++++++++++-------- 4 files changed, 65 insertions(+), 51 deletions(-) diff --git a/src/de/steamwar/bungeecore/ArenaMode.java b/src/de/steamwar/bungeecore/ArenaMode.java index 4d5a868..5005bdf 100644 --- a/src/de/steamwar/bungeecore/ArenaMode.java +++ b/src/de/steamwar/bungeecore/ArenaMode.java @@ -20,8 +20,13 @@ package de.steamwar.bungeecore; import de.steamwar.bungeecore.sql.SchematicType; +import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; +import java.io.File; +import java.io.IOException; import java.util.*; public class ArenaMode { @@ -32,9 +37,18 @@ public class ArenaMode { private static final List allModes = new LinkedList<>(); private static final Random random = new Random(); - static void init(Configuration config){ - for(String internalName : config.getKeys()){ - new ArenaMode(internalName, config.getSection(internalName)); + static { + File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem"); + + for(File configFile : folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))) { + Configuration config; + try { + config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + } catch (IOException e) { + throw new SecurityException("Could not load SchematicTypes", e); + } + + new ArenaMode(configFile.getName().replace(".yml", ""), config); } } @@ -84,19 +98,16 @@ public class ArenaMode { private final String schemType; private ArenaMode(String internalName, Configuration config){ - this.folder = config.getString("folder"); - this.serverJar = config.getString("serverJar"); - this.config = config.getString("config"); - this.maps = config.getStringList("maps"); - this.displayName = config.getString("displayName", internalName); - if(config.contains("chatNames")) - this.chatNames = config.getStringList("chatNames"); - else - this.chatNames = Collections.emptyList(); - this.historic = config.getBoolean("historic", false); - this.schemType = config.getString("schemType", "").toLowerCase(); + this.folder = config.getString("Server.Folder"); + this.serverJar = config.getString("Server.ServerJar"); + this.config = internalName + ".yml"; + this.maps = config.getStringList("Server.Maps"); + this.displayName = config.getString("GameName", internalName); + this.chatNames = config.getStringList("Server.ChatNames"); + this.schemType = config.getString("Schematic.Type", "").toLowerCase(); - this.ranked = config.getBoolean("ranked", false); + this.ranked = config.getBoolean("Server.Ranked", false); + this.historic = config.getBoolean("Server.Historic", false); allModes.add(this); byInternal.put(internalName, this); diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 65fd3ce..bd744da 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -269,8 +269,6 @@ public class BungeeCore extends Plugin { EVENT_MODE = config.getBoolean("eventmode"); Broadcaster.setBroadCastMsgs(config.getStringList("broadcasts").toArray(new String[1])); PollSystem.init(config.getString("poll.question"), config.getStringList("poll.answers")); - CheckCommand.loadCheckQuestions(config.getSection("checkquestions")); - CheckCommand.loadRanks(config.getSection("checkranks")); Persistent.setChatPrefix(CHAT_PREFIX); Persistent.setLobbyServer(LOBBY_SERVER); @@ -280,7 +278,6 @@ public class BungeeCore extends Plugin { config.getString("db.password") ); - ArenaMode.init(config.getSection("games")); if (config.getSection("discord") != null) { SteamwarDiscordBotConfig.loadConfig(config.getSection("discord")); } diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index e61dd71..b19d4a3 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -47,16 +47,9 @@ public class CheckCommand extends BasicCommand { private static Map currentCheckers = new HashMap<>(); private static Map currentSchems = new HashMap<>(); - public static void loadCheckQuestions(Configuration config){ - for(String schemType : config.getKeys()){ - checkQuestions.put(SchematicType.fromDB(schemType), config.getStringList(schemType)); - } - } - - public static void loadRanks(Configuration config){ - for(String schemType : config.getKeys()){ - ranks.put(SchematicType.fromDB(schemType), config.getStringList(schemType)); - } + public static void setCheckQuestions(SchematicType checkType, Configuration config) { + checkQuestions.put(checkType, config.getStringList("CheckQuestions")); + ranks.put(checkType, config.getStringList("Ranks")); } public static boolean isChecking(ProxiedPlayer player){ diff --git a/src/de/steamwar/bungeecore/sql/SchematicType.java b/src/de/steamwar/bungeecore/sql/SchematicType.java index 975eedf..54290d8 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicType.java +++ b/src/de/steamwar/bungeecore/sql/SchematicType.java @@ -19,7 +19,8 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; +import de.steamwar.bungeecore.commands.CheckCommand; +import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; @@ -35,18 +36,8 @@ public class SchematicType { private static final Map fightType; private static final List types; - static{ - File file = new File(BungeeCore.get().getDataFolder(), "SchematicTypes.yml"); - - if(!file.exists()) - throw new SecurityException("SchematicType-ConfigFile not found!"); - - Configuration config; - try { - config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file); - } catch (IOException e) { - throw new SecurityException("Could not load SchematicTypes", e); - } + static { + File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem"); List tmpTypes = new LinkedList<>(); Map tmpFromDB = new HashMap<>(); @@ -55,15 +46,37 @@ public class SchematicType { tmpTypes.add(Normal); tmpFromDB.put(Normal.name().toLowerCase(), Normal); - for(String type : config.getKeys()){ - Configuration section = config.getSection(type); - assert section != null; - String checktype = section.getString("checktype"); - SchematicType current = new SchematicType(type, section.getString("kuerzel"), Type.valueOf(section.getString("type")), checktype != null ? tmpFromDB.get(checktype.toLowerCase()) : null); - tmpTypes.add(current); - if(current.checkType != null) - tmpFightType.put(current.checkType, current); - tmpFromDB.put(type.toLowerCase(), current); + if(folder.exists()) { + for(File configFile : folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))) { + Configuration config; + try { + config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + } catch (IOException e) { + throw new SecurityException("Could not load SchematicTypes", e); + } + + if(!config.contains("Schematic")) + continue; + + String type = config.getString("Schematic.Type"); + assert type != null; + String shortcut = config.getString("Schematic.Shortcut"); + if(tmpFromDB.containsKey(type.toLowerCase())) + continue; + + SchematicType checktype = null; + if(!config.getStringList("CheckQuestions").isEmpty()) { + checktype = new SchematicType("C" + type, "C" + shortcut, Type.CHECK_TYPE, null); + tmpTypes.add(checktype); + tmpFromDB.put(checktype.toDB(), checktype); + CheckCommand.setCheckQuestions(checktype, config); + } + + SchematicType current = new SchematicType(type, shortcut, config.getKeys().contains("Server") ? Type.FIGHT_TYPE : Type.NORMAL, checktype); + if(checktype != null) + tmpFightType.put(checktype, current); + tmpFromDB.put(type.toLowerCase(), current); + } } fromDB = Collections.unmodifiableMap(tmpFromDB); @@ -74,7 +87,7 @@ public class SchematicType { private final String name; private final String kuerzel; private final Type type; - private SchematicType checkType; + private final SchematicType checkType; private SchematicType(String name, String kuerzel, Type type, SchematicType checkType){ this.name = name; From 2e5f0de710c863b9c5f815ade993c80ca1c2c129 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sun, 14 Nov 2021 12:00:29 +0100 Subject: [PATCH 60/83] Everthings Tested! Signed-off-by: Chaoscaot --- .../bungeecore/sql/CheckedSchematic.java | 2 +- .../bungeecore/sql/SchematicNode.java | 89 +++++++++++-------- 2 files changed, 51 insertions(+), 40 deletions(-) diff --git a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java index 82b7133..baae893 100644 --- a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java +++ b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java @@ -30,7 +30,7 @@ public class CheckedSchematic { private static final Statement checkHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId IN (SELECT NodeId FROM SchematicNode WHERE NodeOwner = ?) AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' AND NodeId is not NULL ORDER BY EndTime DESC"); private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); - private static final Statement insert = new Statement("INSERT INTO CheckedSchematic (NodeId, NodeName, NodeOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?)"); + private static final Statement insert = new Statement("INSERT INTO CheckedSchematic (NodeId, NodeName, NodeOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?, ?)"); private final Integer node; private final int validator; diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java index b111a2d..e16acdd 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicNode.java +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -19,7 +19,6 @@ package de.steamwar.bungeecore.sql; -import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -42,8 +41,16 @@ public class SchematicNode { private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?"); private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?"); private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName"); + private static final Statement getAccessibleByUserByTypeInNode = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ?"); + private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null"); + private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ?"); + private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType is not null"); + private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1"); + private static final Statement getAllParentsOfNode = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? UNION SELECT SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN"); private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?"); + private static final Statement updateDatabase = new Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?"); + private static final Statement selSchemData = new Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?"); private static final Statement deleteNode = new Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); public static SchematicNode createSchematic(int owner, String name, Integer parent) { @@ -166,21 +173,32 @@ public class SchematicNode { if (!rs.next()) return null; return new SchematicNode(rs); - }); + }, id); } - public static List getSchematicsOfType(int owner, String schemType, Integer parent) { - List schems = getAllSchematicsAccessibleByUser(owner); - schems.removeIf(node -> node.isDir() || !node.getType().equals(schemType)); - Map nodesInParent = new LinkedHashMap<>(); - for (SchematicNode schematicNode : schems) { - SchematicNode currentNode = schematicNode; - while (currentNode.getParent() != parent) { - currentNode = currentNode.getParentNode(); + public static List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { + Statement.ResultSetUser> user = rs -> { + List nodes = new ArrayList<>(); + while (rs.next()) { + nodes.add(new SchematicNode(rs)); } - nodesInParent.putIfAbsent(currentNode.getId(), currentNode); + return nodes; + }; + if(parent == null || parent == 0) { + return getAccessibleByUserByTypeInNode_Null.select(user, owner, owner, schemType); + } else { + return getAccessibleByUserByTypeInNode.select(user, owner, owner, parent, schemType); } - return new ArrayList<>(nodesInParent.values()); + } + + public static List getAllAccessibleSchematicsOfType(int user, String schemType) { + return getAccessibleByUserByType.select(rs -> { + List nodes = new ArrayList<>(); + while (rs.next()) { + nodes.add(new SchematicNode(rs)); + } + return nodes; + }, user, user, schemType); } public static List getAllSchematicsOfType(int owner, String schemType) { @@ -192,7 +210,6 @@ public class SchematicNode { }, owner, schemType); } - public static List getAllSchematicsOfType(String schemType) { return getAllSchemsOfType.select(rs -> { List nodes = new ArrayList<>(); @@ -218,18 +235,10 @@ public class SchematicNode { public static List getSchematicsAccessibleByUser(int user, Integer parent) { if (parent != null && parent != 0) { - SchematicNode node = SchematicNode.getSchematicNode(parent); - boolean isAdded = false; - while (node.getId() != 0) { - for (NodeMember member:node.getMembers()) { - if (member.getMember() == user) { - isAdded = true; - break; - } - } - node = SchematicNode.getSchematicNode(node.getParent()); - } - if(isAdded) + if(isSchematicAccessibleForUser.select(rs -> { + rs.next(); + return rs.getInt("Accessible") > 0; + }, parent, user, user)) return getSchematicNodeInNode(parent); } else { return getAccessibleByUser.select(rs -> { @@ -243,20 +252,29 @@ public class SchematicNode { } public static List getAllSchematicsAccessibleByUser(int user) { - return getAccessibleByUser.select(rs -> { + return getAllSchematicsAccessibleByUser.select(rs -> { List nodes = new ArrayList<>(); while(rs.next()) { - SchematicNode node = new SchematicNode(rs); - if(node.isDir()) { - nodes.addAll(deepGet(node.getId(), node1 -> true)); - } else { - nodes.add(node); - } + nodes.add(new SchematicNode(rs)); } return nodes; }, user, user); } + public static List getAllParentsOfNode(SchematicNode node) { + return getAllParentsOfNode(node.getId()); + } + + public static List getAllParentsOfNode(int node) { + return getAllParentsOfNode.select(rs -> { + List nodes = new ArrayList<>(); + while(rs.next()) { + nodes.add(new SchematicNode(rs)); + } + return nodes; + }, node); + } + private final int id; private final int owner; private String name; @@ -408,13 +426,6 @@ public class SchematicNode { this.brCache.clear(); } - public void delete() { - if (isDir()) { - getSchematicNodeInNode(getId()).forEach(SchematicNode::delete); - } - deleteNode.update(id); - } - @Override public boolean equals(Object obj) { if (!(obj instanceof SchematicNode)) From ea8e5831c42bfc54b50ca4107a1a80d449e292c3 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sat, 20 Nov 2021 11:29:04 +0100 Subject: [PATCH 61/83] Update from Spigot Signed-off-by: Chaoscaot --- .../bungeecore/sql/SchematicNode.java | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java index e16acdd..83e9391 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicNode.java +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -19,12 +19,17 @@ package de.steamwar.bungeecore.sql; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.util.*; import java.util.function.Predicate; +import java.util.zip.GZIPInputStream; public class SchematicNode { @@ -33,6 +38,8 @@ public class SchematicNode { private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); private static final Statement getSchematicsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL"); private static final Statement getSchematicsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ?"); + private static final Statement getDirsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL AND NodeType is NULL"); + private static final Statement getDirsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? AND NodeType is NULL"); private static final Statement getSchematicDirectory_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL"); private static final Statement getSchematicDirectory = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?"); private static final Statement getSchematicNodeO_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL"); @@ -40,12 +47,12 @@ public class SchematicNode { private static final Statement getSchematicNodeId = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?"); private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?"); private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?"); - private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND s.ParentNode is NULL GROUP BY s.NodeId ORDER BY s.NodeName"); + private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND ((s.NodeOwner = ? AND s.ParentNode IS NULL) OR NOT s.NodeOwner = ?) GROUP BY s.NodeId ORDER BY s.NodeName"); private static final Statement getAccessibleByUserByTypeInNode = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ?"); private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null"); private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ?"); - private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType is not null"); - private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1"); + private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN"); + private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN LEFT Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1"); private static final Statement getAllParentsOfNode = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? UNION SELECT SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN"); private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?"); @@ -133,6 +140,22 @@ public class SchematicNode { } } + public static List getSchematicDirectoryInNode(Integer parent) { + if(parent != null && parent == 0) + parent = null; + Statement.ResultSetUser> user = rs -> { + List nodes = new ArrayList<>(); + while (rs.next()) + nodes.add(new SchematicNode(rs)); + return nodes; + }; + if(parent == null) { + return getDirsInNode_Null.select(user); + }else { + return getDirsInNode.select(user, parent); + } + } + public static SchematicNode getSchematicDirectory(String name, Integer parent) { if(parent != null && parent == 0) parent = null; @@ -187,7 +210,7 @@ public class SchematicNode { if(parent == null || parent == 0) { return getAccessibleByUserByTypeInNode_Null.select(user, owner, owner, schemType); } else { - return getAccessibleByUserByTypeInNode.select(user, owner, owner, parent, schemType); + return getAccessibleByUserByTypeInNode.select(user, owner, owner, schemType, parent); } } @@ -246,7 +269,7 @@ public class SchematicNode { while(rs.next()) nodes.add(new SchematicNode(rs)); return nodes; - }, user, user); + }, user, user, user, user); } return Collections.emptyList(); } @@ -421,7 +444,7 @@ public class SchematicNode { } private void updateDB() { - updateDB.update(name, owner, parent == 0 ? null : parent, item, type, rank, id); + updateDB.update(name, owner, parent, item, type, rank, id); this.lastUpdate = Timestamp.from(Instant.now()); this.brCache.clear(); } From d31f3a31d13a53ca7462c9c8655bae964e1970bb Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sat, 20 Nov 2021 21:05:34 +0100 Subject: [PATCH 62/83] Fix CheckCommand Signed-off-by: Chaoscaot --- .../steamwar/bungeecore/commands/CheckCommand.java | 2 +- src/de/steamwar/bungeecore/sql/SchematicNode.java | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index 3ae1626..b44da4e 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -239,7 +239,7 @@ public class CheckCommand extends BasicCommand { return; } - ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemtype()); + ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemtype().fightType()); SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getId(), 0); currentCheckers.put(checker.getUniqueId(), this); currentSchems.put(schematic.getId(), this); diff --git a/src/de/steamwar/bungeecore/sql/SchematicNode.java b/src/de/steamwar/bungeecore/sql/SchematicNode.java index 83e9391..cea408c 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicNode.java +++ b/src/de/steamwar/bungeecore/sql/SchematicNode.java @@ -32,7 +32,6 @@ import java.util.function.Predicate; import java.util.zip.GZIPInputStream; public class SchematicNode { - private static final Statement createNode = new Statement("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)"); private static final Statement getSchematicNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); @@ -69,7 +68,7 @@ public class SchematicNode { } public static SchematicNode createSchematicNode(int owner, String name, Integer parent, String type, String item) { - if (parent == 0) + if (parent != null && parent == 0) parent = null; createNode.update(name, owner, parent, type, item); return getSchematicNode(owner, name, parent); @@ -86,6 +85,9 @@ public class SchematicNode { owner = set.getInt("NodeOwner"); name = set.getString("NodeName"); parent = set.getInt("ParentNode"); + if(set.wasNull()) { + parent = null; + } item = set.getString("NodeItem"); type = set.getString("NodeType"); lastUpdate = set.getTimestamp("LastUpdate"); @@ -409,6 +411,7 @@ public class SchematicNode { } public SchematicNode getParentNode() { + if(parent == null) return null; return SchematicNode.getSchematicNode(parent); } @@ -449,6 +452,13 @@ public class SchematicNode { this.brCache.clear(); } + public void delete() { + if (isDir()) { + getSchematicNodeInNode(getId()).forEach(SchematicNode::delete); + } + deleteNode.update(id); + } + @Override public boolean equals(Object obj) { if (!(obj instanceof SchematicNode)) From 866d57f8dc5558145595c19b7988a3a8730dce53 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 23 Nov 2021 19:27:03 +0100 Subject: [PATCH 63/83] WIP GDPR query processor Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 1 + .../bungeecore/commands/GDPRQuery.java | 239 ++++++++++++++++++ src/de/steamwar/bungeecore/sql/Statement.java | 8 +- 3 files changed, 244 insertions(+), 4 deletions(-) create mode 100644 src/de/steamwar/bungeecore/commands/GDPRQuery.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index 65fd3ce..3ed7e12 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -128,6 +128,7 @@ public class BungeeCore extends Plugin { new ListCommand(); new StatCommand(); new VerifyCommand(); + new GDPRQuery(); // Punishment Commands: new PunishmentCommand("ban", Punishment.PunishmentType.Ban); diff --git a/src/de/steamwar/bungeecore/commands/GDPRQuery.java b/src/de/steamwar/bungeecore/commands/GDPRQuery.java new file mode 100644 index 0000000..ec693e5 --- /dev/null +++ b/src/de/steamwar/bungeecore/commands/GDPRQuery.java @@ -0,0 +1,239 @@ +package de.steamwar.bungeecore.commands; + +import de.steamwar.bungeecore.sql.Statement; +import de.steamwar.bungeecore.sql.SteamwarUser; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import java.io.*; +import java.sql.SQLException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class GDPRQuery extends BasicCommand { + + public GDPRQuery() { + super("gdprquery", null); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if(!(sender instanceof ProxiedPlayer)) + return; + ProxiedPlayer player = (ProxiedPlayer) sender; + SteamwarUser user = SteamwarUser.get(player.getUniqueId()); + + try { + createZip(user); + } catch (IOException e) { + throw new SecurityException("Could not create zip", e); + } + } + + private void createZip(SteamwarUser user) throws IOException { + ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip")); //TODO + + //TODO: Bauweltenurheberrecht + //TODO: Erklärung Art, Umfang (& Dauer?) + + copyBauwelt(user, out, "/home/minecraft/userworlds/" + user.getUuid().toString(), "BuildWorld12"); + copyBauwelt(user, out, "/home/minecraft/userworlds15/" + user.getId(), "BuildWorld15"); + copyPlayerdata(user, out, "/home/minecraft/userworlds", "BuildInventories12"); + copyPlayerdata(user, out, "/home/minecraft/userworlds15", "BuildInventories15"); + //TODO: Simulatoren von allen Bauwelten + + sqlCSV(user, out, bannedIPs, "BannedIPs.csv"); + sqlCSV(user, out, bauweltMember, "BuildMember.csv"); + sqlCSV(user, out, bauweltMembers, "BuildMembers.csv"); + sqlCSV(user, out, checkedSchems, "SchematicChecksessions.csv"); + sqlCSV(user, out, elo, "Elo.csv"); + sqlCSV(user, out, fights, "Fights.csv"); + sqlCSV(user, out, ignoredPlayers, "IgnoredPlayers.csv"); + sqlCSV(user, out, ignoringPlayers, "IgnoringPlayers.csv"); + sqlCSV(user, out, schematicMember, "SchematicMember.csv"); + sqlCSV(user, out, schematicMembers, "SchematicMembers.csv"); + sqlCSV(user, out, pollAnswers, "PollAnswers.csv"); + sqlCSV(user, out, punishments, "Punishments.csv"); + sqlCSV(user, out, sessions, "Sessions.csv"); + sqlCSV(user, out, userData, "UserData.csv"); + sqlCSV(user, out, personalKits, "PersonalKits.csv"); + sqlCSV(user, out, schematics, "Schematics.csv"); + + personalKits(user, out); + schematics(user, out); + userConfig(user, out); + + //TODO: Logs: Lobby & Bungeelogpos! + //TODO: Website + + out.close(); + } + + private static final Statement bannedIPs = new Statement("SELECT Timestamp, IP FROM BannedUserIPs WHERE UserID = ?"); + private static final Statement bauweltMember = new Statement("SELECT BauweltID AS Bauwelt, WorldEdit, World FROM BauweltMember WHERE MemberID = ?"); + private static final Statement bauweltMembers = new Statement("SELECT u.UserName AS 'User', m.WorldEdit AS WorldEdit, m.World AS World FROM BauweltMember m INNER JOIN UserData u ON m.MemberID = u.id WHERE m.BauweltID = ?"); + private static final Statement checkedSchems = new Statement("SELECT NodeName AS Schematic, StartTime, EndTime, DeclineReason AS Result FROM CheckedSchematic WHERE NodeOwner = ? ORDER BY StartTime ASC"); + private static final Statement elo = new Statement("SELECT GameMode, Elo FROM Elo WHERE UserID = ?"); + private static final Statement fights = new Statement("SELECT p.Team AS Team, p.Kit AS Kit, p.Kills AS Kills, p.IsOut AS Died, f.GameMode AS GameMode, f.Server AS Server, f.Arena AS Arena, f.StartTime AS StartTime, f.Duration AS Duration, (f.BlueLeader = p.UserID) AS IsBlueLeader, (f.RedLeader = p.UserID) AS IsRedLeader, f.Win AS Winner, f.WinCondition AS WinCondition FROM Fight f INNER JOIN FightPlayer p ON f.FightID = p.FightID WHERE p.UserID = ? ORDER BY StartTime ASC"); + private static final Statement ignoredPlayers = new Statement("SELECT u.UserName AS IgnoredPlayer FROM IgnoredPlayers i INNER JOIN UserData u ON i.Ignored = u.id WHERE Ignorer = ?"); + private static final Statement ignoringPlayers = new Statement("SELECT Ignorer AS IgnoringPlayers FROM IgnoredPlayers WHERE Ignored = ?"); + private static final Statement schematicMember = new Statement("SELECT s.NodeName AS SchematicName, u.UserName AS SchematicOwner FROM NodeMember m INNER JOIN SchematicNode s ON m.NodeId = s.NodeId INNER JOIN UserData u ON s.NodeOwner = u.id WHERE m.UserId = ?"); + private static final Statement schematicMembers = new Statement("SELECT s.NodeName AS SchematicName, u.UserName AS Member FROM NodeMember m INNER JOIN SchematicNode s ON m.NodeId = s.NodeId INNER JOIN UserData u ON m.UserId = u.id WHERE s.NodeOwner = ?"); + private static final Statement pollAnswers = new Statement("SELECT Question, Answer FROM PollAnswer WHERE UserID = ?"); + private static final Statement punishments = new Statement("SELECT Type, StartTime, EndTime, Perma, Reason FROM Punishments WHERE UserId = ?"); + private static final Statement sessions = new Statement("SELECT StartTime, EndTime FROM Session WHERE UserID = ?"); + private static final Statement userData = new Statement("SELECT * FROM UserData WHERE id = ?"); + private static final Statement personalKits = new Statement("SELECT GameMode, Name, InUse FROM PersonalKit WHERE UserID = ?"); + private static final Statement personalKitData = new Statement("SELECT GameMode, Name, Inventory, Armor FROM PersonalKit WHERE UserID = ?"); + private static final Statement schematics = new Statement("SELECT NodeName AS SchematicName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank FROM SchematicNode WHERE NodeOwner = ?"); + private static final Statement schematicData = new Statement("SELECT NodeName, ParentNode, NodeFormat, NodeData FROM SchematicNode WHERE NodeOwner = ?"); + private static final Statement userConfig = new Statement("SELECT * FROM UserConfig WHERE User = ?"); + + private void sqlCSV(SteamwarUser user, ZipOutputStream out, Statement statement, String path) throws IOException { + write(stream -> { + PrintWriter writer = new PrintWriter(stream); + statement.select(rs -> { + int columns = rs.getMetaData().getColumnCount(); + + for(int i = 1; i <= columns; i++) { + writer.write(rs.getMetaData().getColumnName(1)); + writer.write(";"); + } + writer.println(); + + while(rs.next()) { + for(int i = 1; i <= columns; i++) { + try { + writer.write(rs.getString(i)); + } catch (NullPointerException e) { + // ignored + } + writer.write(";"); + } + writer.println(); + } + return null; + }, user.getId()); + }, out, path); + } + + private void personalKits(SteamwarUser user, ZipOutputStream out) { + personalKitData.select(rs -> { + while(rs.next()) { + try { + write(stream -> { + try { + new PrintWriter(stream).print(rs.getString("Inventory")); + } catch (SQLException e) { + throw new SecurityException("Could not export PersonalKits", e); + } + }, out, "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name") + ".Inventory.yml"); + write(stream -> { + try { + new PrintWriter(stream).print(rs.getString("Armor")); + } catch (SQLException e) { + throw new SecurityException("Could not export PersonalKits", e); + } + }, out, "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name") + ".Armor.yml"); + } catch (IOException e) { + throw new SecurityException("Could not export PersonalKits", e); + } + } + return null; + }, user.getId()); + } + + private void schematics(SteamwarUser user, ZipOutputStream out) { + schematicData.select(rs -> { + while(rs.next()) { + String name = (rs.getString("ParentNode") != null ? rs.getString("ParentNode") : "") + ":" + rs.getString("NodeName"); + boolean format = rs.getBoolean("NodeFormat"); + try(InputStream data = rs.getBinaryStream("NodeData")) { + copy(data, out, "Schematics/" + name + (format ? ".schem" : ".schematic")); + } catch (IOException e) { + throw new SecurityException("Could not export Schematic", e); + } + } + return null; + }, user.getId()); + } + + private void userConfig(SteamwarUser user, ZipOutputStream out) { + userConfig.select(rs -> { + while(rs.next()) { + String name = rs.getString("Config"); + try(InputStream data = rs.getBinaryStream("Value")) { + copy(data, out, name + ".yapion"); + } catch (IOException e) { + throw new SecurityException("Could not export UserConfig", e); + } + } + return null; + }, user.getId()); + } + + private void copyBauwelt(SteamwarUser user, ZipOutputStream out, String inDir, String outDir) throws IOException { + //TODO: Überhaupt nötig wegen Urheberrecht? + File world = new File(inDir); + if(!world.exists()) + return; + + copy(new File(world, "level.dat"), out, outDir + "/level.dat"); + + File region = new File(world, "region"); + for(File regionfile : region.listFiles()) { + copy(regionfile, out, outDir + "/region/" + regionfile.getName()); + } + + File poi = new File(world, "poi"); + if(poi.exists()) { + for(File regionfile : poi.listFiles()) { + copy(regionfile, out, outDir + "/poi/" + regionfile.getName()); + } + } + + File playerdata = new File(world, "playerdata/" + user.getUuid().toString() + ".dat"); + if(playerdata.exists()) + copy(playerdata, out, outDir + "/playerdata/" + user.getUuid().toString() + ".dat"); + } + + private void copyPlayerdata(SteamwarUser user, ZipOutputStream out, String inDir, String outDir) throws IOException { + File worlds = new File(inDir); + String path = "playerdata/" + user.getUuid().toString() + ".dat"; + + int i = 0; + for(File world : worlds.listFiles()) { + File playerdata = new File(world, path); + if(!playerdata.exists()) + continue; + + copy(playerdata, out, outDir + "/" + (i++) + "/" + user.getUuid().toString() + ".dat"); + } + } + + private static void copy(File file, ZipOutputStream out, String path) throws IOException { + try(FileInputStream in = new FileInputStream(file)) { + copy(in, out, path); + } + } + + private static void copy(InputStream in, ZipOutputStream out, String path) throws IOException { + write(stream -> { + int bytes; + for(byte[] buf = new byte[8192]; (bytes = in.read(buf)) > 0; ) { + out.write(buf, 0, bytes); + } + }, out, path); + } + + private static void write(Writer writer, ZipOutputStream out, String path) throws IOException { + ZipEntry entry = new ZipEntry(path); + out.putNextEntry(entry); + writer.accept(out); + out.closeEntry(); + } + + private interface Writer { + void accept(OutputStream stream) throws IOException; + } +} diff --git a/src/de/steamwar/bungeecore/sql/Statement.java b/src/de/steamwar/bungeecore/sql/Statement.java index 9b1628c..9889a7a 100644 --- a/src/de/steamwar/bungeecore/sql/Statement.java +++ b/src/de/steamwar/bungeecore/sql/Statement.java @@ -88,7 +88,7 @@ public class Statement { private final String sql; private PreparedStatement st; - Statement(String sql) { + public Statement(String sql) { this.sql = sql; statements.add(this); try { @@ -102,7 +102,7 @@ public class Statement { st = con.prepareStatement(sql); } - T select(ResultSetUser user, Object... objects) { + public T select(ResultSetUser user, Object... objects) { synchronized (statements) { return prepare(() -> { ResultSet rs = st.executeQuery(); @@ -113,7 +113,7 @@ public class Statement { } } - void update(Object... objects) { + public void update(Object... objects) { synchronized (statements) { prepare(st::executeUpdate, objects); } @@ -135,7 +135,7 @@ public class Statement { } } - interface ResultSetUser { + public interface ResultSetUser { T use(ResultSet rs) throws SQLException; } From a6ea418047711d241de7b5c3f6c70f5196922721 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 23 Nov 2021 19:59:50 +0100 Subject: [PATCH 64/83] WIP GDPR query processor Signed-off-by: Lixfel --- .../bungeecore/commands/GDPRQuery.java | 57 +++++++++---------- 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/GDPRQuery.java b/src/de/steamwar/bungeecore/commands/GDPRQuery.java index ec693e5..c7161ca 100644 --- a/src/de/steamwar/bungeecore/commands/GDPRQuery.java +++ b/src/de/steamwar/bungeecore/commands/GDPRQuery.java @@ -6,7 +6,6 @@ import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import java.io.*; -import java.sql.SQLException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -91,26 +90,31 @@ public class GDPRQuery extends BasicCommand { private void sqlCSV(SteamwarUser user, ZipOutputStream out, Statement statement, String path) throws IOException { write(stream -> { - PrintWriter writer = new PrintWriter(stream); + OutputStreamWriter writer = new OutputStreamWriter(stream); statement.select(rs -> { - int columns = rs.getMetaData().getColumnCount(); + try { + int columns = rs.getMetaData().getColumnCount(); - for(int i = 1; i <= columns; i++) { - writer.write(rs.getMetaData().getColumnName(1)); - writer.write(";"); - } - writer.println(); - - while(rs.next()) { for(int i = 1; i <= columns; i++) { - try { - writer.write(rs.getString(i)); - } catch (NullPointerException e) { - // ignored - } + writer.write(rs.getMetaData().getColumnLabel(i)); writer.write(";"); } - writer.println(); + writer.write("\n"); + + while(rs.next()) { + for(int i = 1; i <= columns; i++) { + try { + writer.write(rs.getString(i)); + } catch (NullPointerException e) { + // ignored + } + writer.write(";"); + } + writer.write("\n"); + } + writer.flush(); + } catch (IOException e) { + throw new SecurityException("Could not write file", e); } return null; }, user.getId()); @@ -121,20 +125,13 @@ public class GDPRQuery extends BasicCommand { personalKitData.select(rs -> { while(rs.next()) { try { - write(stream -> { - try { - new PrintWriter(stream).print(rs.getString("Inventory")); - } catch (SQLException e) { - throw new SecurityException("Could not export PersonalKits", e); - } - }, out, "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name") + ".Inventory.yml"); - write(stream -> { - try { - new PrintWriter(stream).print(rs.getString("Armor")); - } catch (SQLException e) { - throw new SecurityException("Could not export PersonalKits", e); - } - }, out, "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name") + ".Armor.yml"); + String path = "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name"); + try(InputStream data = rs.getBinaryStream("Inventory")) { + copy(data, out, path + ".Inventory.yml"); + } + try(InputStream data = rs.getBinaryStream("Armor")) { + copy(data, out, path + ".Armor.yml"); + } } catch (IOException e) { throw new SecurityException("Could not export PersonalKits", e); } From 582924fb7dc3db1190ef0a756092f5c47f22aa04 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 25 Nov 2021 14:47:37 +0100 Subject: [PATCH 65/83] GDPR query processor Signed-off-by: Lixfel --- src/GDPRQueryREADME.md | 29 ++++ .../bungeecore/commands/GDPRQuery.java | 133 +++++++++++------- .../steamwar/messages/BungeeCore.properties | 10 +- 3 files changed, 124 insertions(+), 48 deletions(-) create mode 100644 src/GDPRQueryREADME.md diff --git a/src/GDPRQueryREADME.md b/src/GDPRQueryREADME.md new file mode 100644 index 0000000..bbe4fcb --- /dev/null +++ b/src/GDPRQueryREADME.md @@ -0,0 +1,29 @@ +# SteamWar GDPR report + +## Copyright notice +The provided build worlds contain the world design of SteamWar contributors and is subject to their copyright. +The build worlds are therefore provided for personal use only. + +## Categories of personal data processed +- IP address +- Minecraft account +- E-Mail address (if using a website account) + +## Processing purposes of personal data and person-related data +- Provision of SteamWar user functionality (Minecraft account, IP address, BuildWorlds, BuildInventories, BuildMembers, Elo, IgnoredPlayers, SchematicMembers, SchematicChecksessions, Schematics, PersonalKits, UserData, UserConfigs) +- Manual analysis and punishment of player misbehaviour (BannedIPs, log files, Punishments) +- Statistical analysis (Sessions, Fights, SchematicChecksessions) +- Historical data storage (Fights) +- Technical error analysis (log files) +- Provision of the SteamWar website functionality (IP address, E-Mail address) + +## Data Accessors +- SteamWar software +- SteamWar Administration +- SteamWar Development +- SteamWar Moderation (limited to Punishments and SchematicChecksessions) + +## Storage duration +- Data for provision of functionality is stored until user triggered deletion +- Log file storage duration is targeted at one month, but might differ due to technical reasons +- Historical and statistical data deletion is not intended diff --git a/src/de/steamwar/bungeecore/commands/GDPRQuery.java b/src/de/steamwar/bungeecore/commands/GDPRQuery.java index c7161ca..bb98fca 100644 --- a/src/de/steamwar/bungeecore/commands/GDPRQuery.java +++ b/src/de/steamwar/bungeecore/commands/GDPRQuery.java @@ -1,7 +1,10 @@ package de.steamwar.bungeecore.commands; +import de.steamwar.bungeecore.BungeeCore; +import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.SteamwarUser; +import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -12,35 +15,47 @@ import java.util.zip.ZipOutputStream; public class GDPRQuery extends BasicCommand { public GDPRQuery() { - super("gdprquery", null); + super("gdprquery", "bungeecore.softreload"); } @Override public void execute(CommandSender sender, String[] args) { if(!(sender instanceof ProxiedPlayer)) return; - ProxiedPlayer player = (ProxiedPlayer) sender; - SteamwarUser user = SteamwarUser.get(player.getUniqueId()); - try { - createZip(user); - } catch (IOException e) { - throw new SecurityException("Could not create zip", e); + ProxiedPlayer player = (ProxiedPlayer) sender; + SteamwarUser user = args.length == 0 ? SteamwarUser.get(player.getUniqueId()) : SteamwarUser.get(args[0]); + if(user == null) { + Message.send("UNKNOWN_PLAYER", player); + return; } + + BungeeCord.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { + try { + createZip(player, user); + } catch (IOException e) { + throw new SecurityException("Could not create zip", e); + } + }); } - private void createZip(SteamwarUser user) throws IOException { - ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip")); //TODO + private void createZip(ProxiedPlayer player, SteamwarUser user) throws IOException { + printUpdate(player, "GDPR_STATUS_WEBSITE"); - //TODO: Bauweltenurheberrecht - //TODO: Erklärung Art, Umfang (& Dauer?) + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(user.getUserName() + ".zip")); + copy(getClass().getClassLoader().getResourceAsStream("GDPRQueryREADME.md"), out, "README.md"); + copy(getClass().getClassLoader().getResourceAsStream("GDPRQueryREADME.md"), out, "README.txt"); + + printUpdate(player, "GDPR_STATUS_WORLD"); copyBauwelt(user, out, "/home/minecraft/userworlds/" + user.getUuid().toString(), "BuildWorld12"); copyBauwelt(user, out, "/home/minecraft/userworlds15/" + user.getId(), "BuildWorld15"); + + printUpdate(player, "GDPR_STATUS_INVENTORIES"); copyPlayerdata(user, out, "/home/minecraft/userworlds", "BuildInventories12"); copyPlayerdata(user, out, "/home/minecraft/userworlds15", "BuildInventories15"); - //TODO: Simulatoren von allen Bauwelten + printUpdate(player, "GDPR_STATUS_DATABASE"); sqlCSV(user, out, bannedIPs, "BannedIPs.csv"); sqlCSV(user, out, bauweltMember, "BuildMember.csv"); sqlCSV(user, out, bauweltMembers, "BuildMembers.csv"); @@ -62,10 +77,11 @@ public class GDPRQuery extends BasicCommand { schematics(user, out); userConfig(user, out); - //TODO: Logs: Lobby & Bungeelogpos! - //TODO: Website + printUpdate(player, "GDPR_STATUS_LOGS"); + copyLogs(user, out, new File("/logs"), "logs"); out.close(); + printUpdate(player, "GDPR_STATUS_FINISHED"); } private static final Statement bannedIPs = new Statement("SELECT Timestamp, IP FROM BannedUserIPs WHERE UserID = ?"); @@ -89,36 +105,34 @@ public class GDPRQuery extends BasicCommand { private static final Statement userConfig = new Statement("SELECT * FROM UserConfig WHERE User = ?"); private void sqlCSV(SteamwarUser user, ZipOutputStream out, Statement statement, String path) throws IOException { - write(stream -> { - OutputStreamWriter writer = new OutputStreamWriter(stream); - statement.select(rs -> { - try { - int columns = rs.getMetaData().getColumnCount(); + write(stream -> statement.select(rs -> { + try { + OutputStreamWriter writer = new OutputStreamWriter(stream); + int columns = rs.getMetaData().getColumnCount(); + for(int i = 1; i <= columns; i++) { + writer.write(rs.getMetaData().getColumnLabel(i)); + writer.write(";"); + } + writer.write("\n"); + + while(rs.next()) { for(int i = 1; i <= columns; i++) { - writer.write(rs.getMetaData().getColumnLabel(i)); + try { + writer.write(rs.getString(i)); + } catch (NullPointerException e) { + // ignored + } writer.write(";"); } writer.write("\n"); - - while(rs.next()) { - for(int i = 1; i <= columns; i++) { - try { - writer.write(rs.getString(i)); - } catch (NullPointerException e) { - // ignored - } - writer.write(";"); - } - writer.write("\n"); - } - writer.flush(); - } catch (IOException e) { - throw new SecurityException("Could not write file", e); } - return null; - }, user.getId()); - }, out, path); + writer.flush(); + } catch (IOException e) { + throw new SecurityException("Could not write file", e); + } + return null; + }, user.getId()), out, path); } private void personalKits(SteamwarUser user, ZipOutputStream out) { @@ -169,8 +183,18 @@ public class GDPRQuery extends BasicCommand { }, user.getId()); } + private void copyLogs(SteamwarUser user, ZipOutputStream out, File log, String outFile) throws IOException { + if (log.isDirectory()) { + for(File logfile : log.listFiles()) { + copyLogs(user, out, logfile, outFile + "/" + logfile.getName().replace(".gz", "")); + } + } else { + Process reader = new ProcessBuilder("zgrep", "^.*" + user.getUserName() + "\\( issued server command:\\| moved too quickly!\\| executed command:\\| lost connection:\\||\\|»\\|\\[\\|\\]\\).*$", log.getPath()).start(); + copy(reader.getInputStream(), out, outFile); + } + } + private void copyBauwelt(SteamwarUser user, ZipOutputStream out, String inDir, String outDir) throws IOException { - //TODO: Überhaupt nötig wegen Urheberrecht? File world = new File(inDir); if(!world.exists()) return; @@ -208,22 +232,37 @@ public class GDPRQuery extends BasicCommand { } } - private static void copy(File file, ZipOutputStream out, String path) throws IOException { + private void printUpdate(ProxiedPlayer player, String message) { + if (player.isConnected()) + Message.send(message, player); + } + + private void copy(File file, ZipOutputStream out, String path) throws IOException { try(FileInputStream in = new FileInputStream(file)) { copy(in, out, path); } } - private static void copy(InputStream in, ZipOutputStream out, String path) throws IOException { - write(stream -> { - int bytes; - for(byte[] buf = new byte[8192]; (bytes = in.read(buf)) > 0; ) { - out.write(buf, 0, bytes); + private void copy(InputStream in, ZipOutputStream out, String path) throws IOException { + boolean initialized = false; + + int bytes; + for(byte[] buf = new byte[8192]; (bytes = in.read(buf)) > 0; ) { + if(!initialized) { + ZipEntry entry = new ZipEntry(path); + out.putNextEntry(entry); + initialized = true; } - }, out, path); + + out.write(buf, 0, bytes); + } + + if(initialized) { + out.closeEntry(); + } } - private static void write(Writer writer, ZipOutputStream out, String path) throws IOException { + private void write(Writer writer, ZipOutputStream out, String path) throws IOException { ZipEntry entry = new ZipEntry(path); out.putNextEntry(entry); writer.accept(out); diff --git a/src/de/steamwar/messages/BungeeCore.properties b/src/de/steamwar/messages/BungeeCore.properties index cc7d8af..9e232f9 100644 --- a/src/de/steamwar/messages/BungeeCore.properties +++ b/src/de/steamwar/messages/BungeeCore.properties @@ -549,4 +549,12 @@ VERIFY_SUCCESS=§7Erfolgreich mit dem Discord Account §e{0} §7verknüpft #Discord DISCORD_TICKET_MESSAGE=§7Ticket §e{0}§7» §f§l{1}: §7{2} DISCORD_TICKET_NEW=§7Ticket §e{0}§7» §aTicket wurde geöffnet! -DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket wurde geschlossen! \ No newline at end of file +DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket wurde geschlossen! + +#GDPR Query +GDPR_STATUS_WEBSITE=§7Website kann nicht automatisiert gepackt werden und muss daher manuell hinzugefügt werden. +GDPR_STATUS_WORLD=§7Packe Bauwelten... +GDPR_STATUS_INVENTORIES=§7Suche und packe Inventare... +GDPR_STATUS_DATABASE=§7Packe Datenbankinhalte... +GDPR_STATUS_LOGS=§7Suche und packe logs... +GDPR_STATUS_FINISHED=§7Packen abgeschlossen \ No newline at end of file From 6bb90af3bca011689371ec8177fa96920df26bea Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 2 Dec 2021 08:45:01 +0100 Subject: [PATCH 66/83] Fix loading of non startable gamemodes Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ArenaMode.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/ArenaMode.java b/src/de/steamwar/bungeecore/ArenaMode.java index 5005bdf..81eed30 100644 --- a/src/de/steamwar/bungeecore/ArenaMode.java +++ b/src/de/steamwar/bungeecore/ArenaMode.java @@ -48,7 +48,8 @@ public class ArenaMode { throw new SecurityException("Could not load SchematicTypes", e); } - new ArenaMode(configFile.getName().replace(".yml", ""), config); + if(config.contains("Server")) + new ArenaMode(configFile.getName().replace(".yml", ""), config); } } From 9f7eca9689816d2258a71d426fa6019872c24acb Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 2 Dec 2021 09:41:47 +0100 Subject: [PATCH 67/83] Display sorted Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/ArenaMode.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/ArenaMode.java b/src/de/steamwar/bungeecore/ArenaMode.java index 81eed30..13db3f4 100644 --- a/src/de/steamwar/bungeecore/ArenaMode.java +++ b/src/de/steamwar/bungeecore/ArenaMode.java @@ -28,6 +28,7 @@ import net.md_5.bungee.config.YamlConfiguration; import java.io.File; import java.io.IOException; import java.util.*; +import java.util.stream.Collectors; public class ArenaMode { @@ -40,7 +41,7 @@ public class ArenaMode { static { File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem"); - for(File configFile : folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))) { + for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) { Configuration config; try { config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); From 78874e080084d7563d26470bba4487ec762be8be Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 2 Dec 2021 17:08:00 +0100 Subject: [PATCH 68/83] FAWE 1.12 should now be Java 16/17 compatible Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/Node.java | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/de/steamwar/bungeecore/Node.java b/src/de/steamwar/bungeecore/Node.java index 9c714c6..4359b9c 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -32,7 +32,6 @@ import java.util.logging.Level; public abstract class Node { - private static final List OPENJDK8_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", "-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods"); private static final List OPENJ9_ARGS = Arrays.asList("-Xgc:excessiveGCratio=80", "-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-XX:-HeapDumpOnOutOfMemory", "-XX:+ExitOnOutOfMemoryError", "-Dlog4j.configurationFile=log4j2.xml"); private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB @@ -75,22 +74,14 @@ public abstract class Node { public abstract double getLoad(); protected void constructServerstart(File directory, List cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) { - boolean openjdk8 = !serverJar.contains("1.8.9") && !serverJar.contains("1.15.2"); - if(openjdk8) - cmd.add("java"); - else - cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/java"); + cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/java"); for(String param : dParams){ cmd.add("-D" + param); } cmd.add("-Xmx" + xmx); - if(openjdk8) - cmd.addAll(OPENJDK8_ARGS); - else { - cmd.add("-Xshareclasses:nonfatal,name=" + directory.getName()); - cmd.addAll(OPENJ9_ARGS); - } + cmd.add("-Xshareclasses:nonfatal,name=" + directory.getName()); + cmd.addAll(OPENJ9_ARGS); cmd.add("-jar"); cmd.add("/binarys/" + serverJar); cmd.add("--log-strip-color"); From 2dd8cf3f8bd19717d2288671d8f5655d06c2d615 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 2 Dec 2021 17:46:39 +0100 Subject: [PATCH 69/83] Fix check without rank Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/commands/CheckCommand.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/commands/CheckCommand.java b/src/de/steamwar/bungeecore/commands/CheckCommand.java index 41ccc8d..6334971 100644 --- a/src/de/steamwar/bungeecore/commands/CheckCommand.java +++ b/src/de/steamwar/bungeecore/commands/CheckCommand.java @@ -49,7 +49,8 @@ public class CheckCommand extends BasicCommand { public static void setCheckQuestions(SchematicType checkType, Configuration config) { checkQuestions.put(checkType, config.getStringList("CheckQuestions")); - ranks.put(checkType, config.getStringList("Ranks")); + if(!config.getStringList("Ranks").isEmpty()) + ranks.put(checkType, config.getStringList("Ranks")); } public static boolean isChecking(ProxiedPlayer player){ From 87ccd1a6d89e951c88f064999415dbcda92f132b Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 4 Dec 2021 07:57:06 +0100 Subject: [PATCH 70/83] Fix possible world names for paper Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/SubserverSystem.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index 9e08df5..877dec8 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -96,6 +96,8 @@ public class SubserverSystem { if(mapName == null) mapName = serverName; + mapName = mapName.replace(' ', '_').replace("[", "").replace("]", ""); + String worldDir; if(eventFightID > 0) worldDir = EVENT_PATH; @@ -138,7 +140,7 @@ public class SubserverSystem { 0, 0, serverName, - serverName.replace(' ', '_') + eventFight.getStartTime().toLocalDateTime().format(DateTimeFormatter.ISO_TIME), + serverName + eventFight.getStartTime().toLocalDateTime().format(DateTimeFormatter.ISO_TIME), null, null, false); From d3d48d9514cbc89e991814e56152e4d4212dc596 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Sun, 5 Dec 2021 12:54:39 +0100 Subject: [PATCH 71/83] Fix Poll Commands Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/commands/PollresultCommand.java | 2 +- src/de/steamwar/bungeecore/sql/PollAnswer.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/PollresultCommand.java b/src/de/steamwar/bungeecore/commands/PollresultCommand.java index cfebd66..df77cb8 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, voted.values().stream().reduce(Integer::sum), PollSystem.getQuestion()); + Message.send("POLLRESULT_HEADER", player, voted.values().stream().reduce(Integer::sum).orElse(0), PollSystem.getQuestion()); for (Map.Entry e: voted.entrySet()) { Message.send("POLLRESULT_LIST", sender, e.getKey(), e.getValue()); } diff --git a/src/de/steamwar/bungeecore/sql/PollAnswer.java b/src/de/steamwar/bungeecore/sql/PollAnswer.java index 7d23c38..7a34476 100644 --- a/src/de/steamwar/bungeecore/sql/PollAnswer.java +++ b/src/de/steamwar/bungeecore/sql/PollAnswer.java @@ -58,7 +58,7 @@ public class PollAnswer { return getResults.select(rs -> { Map retMap = new HashMap<>(); while (rs.next()) - retMap.put(PollSystem.getAnswer(rs.getInt("Answer")), rs.getInt("Times")); + retMap.put(PollSystem.getAnswer(rs.getInt("Answer")-1), rs.getInt("Times")); return retMap; }, PollSystem.getQuestion()); } From defc261e5e5e2d7a62ba1f7e0000d601c81873d2 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 10 Dec 2021 09:08:47 +0100 Subject: [PATCH 72/83] Hotfix: No paper baus Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/SubserverSystem.java | 12 ++---------- src/de/steamwar/bungeecore/commands/BauCommand.java | 3 --- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/src/de/steamwar/bungeecore/SubserverSystem.java b/src/de/steamwar/bungeecore/SubserverSystem.java index 9e08df5..1dd8fe1 100644 --- a/src/de/steamwar/bungeecore/SubserverSystem.java +++ b/src/de/steamwar/bungeecore/SubserverSystem.java @@ -167,17 +167,9 @@ public class SubserverSystem { sendToBau(p, owner, BungeeCore.BAUWELT_PROTOTYP, BungeeCore.WORLD_FOLDER, "spigot-1.12.2.jar", "/home/minecraft/userworlds", owner.toString(), "256M", "UserBau"); } - private static void sendToBau15(ProxiedPlayer p, UUID owner, String serverJar){ - SteamwarUser user = SteamwarUser.get(owner); - sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, serverJar, "/home/minecraft/userworlds15", String.valueOf(user.getId()), "768M", "Bau15"); - } - public static void sendToBau15(ProxiedPlayer p, UUID owner){ - sendToBau15(p, owner, "spigot-1.15.2.jar"); - } - - public static void sendToBau15paper(ProxiedPlayer p, UUID owner){ - sendToBau15(p, owner, "paper-1.15.2.jar"); + SteamwarUser user = SteamwarUser.get(owner); + sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, "spigot-1.15.2.jar", "/home/minecraft/userworlds15", String.valueOf(user.getId()), "768M", "Bau15"); } public static void sendDeniedMessage(ProxiedPlayer p, UUID owner){ diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index b555494..27d8d21 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -69,9 +69,6 @@ public class BauCommand extends BasicCommand { case "1.15": SubserverSystem.sendToBau15(p, p.getUniqueId()); break; - case "paper": - SubserverSystem.sendToBau15paper(p, p.getUniqueId()); - break; case "addmember": addmember(p, args); break; From c98e2c381d5e95111ba87307c35c72022130baa3 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 10 Dec 2021 09:19:01 +0100 Subject: [PATCH 73/83] Autopermabann on jndi:ldap Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/listeners/ChatListener.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index 697bd84..52c5fe0 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -36,6 +36,8 @@ import net.md_5.bungee.api.event.TabCompleteResponseEvent; import net.md_5.bungee.api.scheduler.TaskScheduler; import net.md_5.bungee.event.EventHandler; +import java.sql.Timestamp; +import java.time.Instant; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; @@ -47,6 +49,12 @@ public class ChatListener extends BasicListener { @EventHandler public void onChatEvent(ChatEvent e){ + if(e.getMessage().contains("jndi:ldap")) { + e.setCancelled(true); + SteamwarUser.get(((ProxiedPlayer) e.getSender()).getUniqueId()).punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now()), "Versuchte Exploit-Ausnutzung", 0, true); + return; + } + sanitize7(e); if(e.getMessage().startsWith("/")) onCommand(e); From 276cdf1762a06e5ca80b1154345613d7a46c220c Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 11 Dec 2021 16:54:06 +0100 Subject: [PATCH 74/83] Use default java instead of hardcoded java Signed-off-by: Lixfel --- 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 4359b9c..d53d2e8 100644 --- a/src/de/steamwar/bungeecore/Node.java +++ b/src/de/steamwar/bungeecore/Node.java @@ -74,7 +74,7 @@ public abstract class Node { public abstract double getLoad(); protected void constructServerstart(File directory, List cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) { - cmd.add("/usr/lib/jvm/java-16-openj9-amd64/bin/java"); + cmd.add("java"); for(String param : dParams){ cmd.add("-D" + param); From fe80ede6e071f690207795968f2bdb9affaa0510 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Thu, 16 Dec 2021 17:10:27 +0100 Subject: [PATCH 75/83] Fix of 20+ Bans on lndi Signed-off-by: Chaoscaot --- src/de/steamwar/bungeecore/listeners/ChatListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/ChatListener.java b/src/de/steamwar/bungeecore/listeners/ChatListener.java index 52c5fe0..f66e71c 100644 --- a/src/de/steamwar/bungeecore/listeners/ChatListener.java +++ b/src/de/steamwar/bungeecore/listeners/ChatListener.java @@ -51,7 +51,7 @@ public class ChatListener extends BasicListener { public void onChatEvent(ChatEvent e){ if(e.getMessage().contains("jndi:ldap")) { e.setCancelled(true); - SteamwarUser.get(((ProxiedPlayer) e.getSender()).getUniqueId()).punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now()), "Versuchte Exploit-Ausnutzung", 0, true); + SteamwarUser.get(((ProxiedPlayer) e.getSender()).getUniqueId()).punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.ofEpochSecond(946674800)), "Versuchte Exploit-Ausnutzung", 0, true); return; } From 75b823f7801f62046a1639150ccbc09780760db8 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 17 Dec 2021 06:52:08 +0100 Subject: [PATCH 76/83] Fix renaming Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index ccc174e..5e9ddce 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -137,6 +137,11 @@ public class SteamwarUser { return null; } + user = SteamwarUser.get(uuid); + if (user != null) { + return user; + } + return SteamwarUser.createUserInDatabase(uuid, name); } From 1087cdb74cd2b7e7e49ff29cf90703bb1879975f Mon Sep 17 00:00:00 2001 From: yoyosource Date: Sat, 18 Dec 2021 14:20:35 +0100 Subject: [PATCH 77/83] Add better Tablist Slim behaviour --- .../bungeecore/listeners/TablistManager.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 59f44bf..066facb 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -212,7 +212,19 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { subTablists.forEach(tPart -> { if(withHeaders) - viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); + if (slim) { + int slimSize = tPart.slimSize(viewer.player); + int size = tPart.size(); + if (size == slimSize) { + viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); + } else if (slimSize == 0) { + viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7" + size + "§8)", 1000); + } else { + viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7+" + (size - slimSize) + "§8)", 1000); + } + } else { + viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); + } tPart.print(viewer, slim); if(withHeaders) viewer.setSlot(darkGray, "", 1000); From 864c51c3d9c27c4fd02873ada8fab5b81b1a11b2 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 19 Dec 2021 16:50:29 +0100 Subject: [PATCH 78/83] Prevent arena start dos Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/commands/BauCommand.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/de/steamwar/bungeecore/commands/BauCommand.java b/src/de/steamwar/bungeecore/commands/BauCommand.java index 27d8d21..3795518 100644 --- a/src/de/steamwar/bungeecore/commands/BauCommand.java +++ b/src/de/steamwar/bungeecore/commands/BauCommand.java @@ -247,7 +247,6 @@ public class BauCommand extends BasicCommand { } private static void deleteWorld(ProxiedPlayer player, String world) { - Message.send("BAU_DELETE_DELETED", player); ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(player.getUniqueId())) { @@ -256,16 +255,20 @@ public class BauCommand extends BasicCommand { } } SubserverSystem.deleteFolder(Node.local, world); + Message.send("BAU_DELETE_DELETED", player); }); } public static boolean stopBauserver(ProxiedPlayer p){ + for (Subserver subserver : Subserver.getServerList()) { + if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId()) && !subserver.hasStarted()) { + Message.send("BAU_START_ALREADY", p); + return false; + } + } + for (Subserver subserver : Subserver.getServerList()) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId())) { - if(!subserver.hasStarted()){ - Message.send("BAU_START_ALREADY", p); - return false; - } subserver.stop(); try { Thread.sleep(200); // Wait until possible testarena-World has been deleted From 0cc93f433ee36aac43873c12c0749be4d5810da6 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Wed, 22 Dec 2021 10:17:28 +0100 Subject: [PATCH 79/83] Fix TablistManager --- .../bungeecore/listeners/TablistManager.java | 35 +++++++++++++++---- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 066facb..797471d 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -197,9 +197,25 @@ public class TablistManager extends BasicListener { @Override public int slimSize(ProxiedPlayer viewer) { - int size = subTablists.stream().mapToInt(tPart -> viewer == null ? tPart.size() : tPart.slimSize(viewer)).sum(); - if(withHeaders) - size += subTablists.size() * 2; + int size = 0; + for (int i = 0; i < subTablists.size(); i++) { + TablistPart tablistPart = subTablists.get(i); + boolean removeFooter = i == subTablists.size() - 1; + if (viewer == null) { + size += tablistPart.size(); + if (withHeaders) size += 2; // The 2 is for the header and footer + if (removeFooter) size--; // The last one has no footer + } else { + int slimSize = tablistPart.slimSize(viewer); + if (slimSize == 0) { + if (withHeaders) size++; // This increment is just for the header + } else { + size += slimSize; + if (withHeaders) size += 2; // The 2 is for the header and footer + if (removeFooter) size--; // The last one has no footer + } + } + } return size; } @@ -210,8 +226,10 @@ public class TablistManager extends BasicListener { @Override public void print(Tablist viewer, boolean slim) { - subTablists.forEach(tPart -> { - if(withHeaders) + for (int i = 0; i < subTablists.size(); i++) { + TablistPart tPart = subTablists.get(i); + boolean removeFooter = i == subTablists.size() - 1; + if (withHeaders) { if (slim) { int slimSize = tPart.slimSize(viewer.player); int size = tPart.size(); @@ -219,16 +237,19 @@ public class TablistManager extends BasicListener { viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); } else if (slimSize == 0) { viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7" + size + "§8)", 1000); + removeFooter = true; } else { viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7+" + (size - slimSize) + "§8)", 1000); } } else { viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); } + } tPart.print(viewer, slim); - if(withHeaders) + if (withHeaders && !removeFooter) { viewer.setSlot(darkGray, "", 1000); - }); + } + } } } From 02883f2beae6a0b75ad2ad4ef86e55d6f0451569 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Wed, 22 Dec 2021 11:29:43 +0100 Subject: [PATCH 80/83] Update TablistManager --- .../bungeecore/listeners/TablistManager.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 797471d..4ef84d7 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -203,18 +203,13 @@ public class TablistManager extends BasicListener { boolean removeFooter = i == subTablists.size() - 1; if (viewer == null) { size += tablistPart.size(); - if (withHeaders) size += 2; // The 2 is for the header and footer - if (removeFooter) size--; // The last one has no footer } else { int slimSize = tablistPart.slimSize(viewer); - if (slimSize == 0) { - if (withHeaders) size++; // This increment is just for the header - } else { - size += slimSize; - if (withHeaders) size += 2; // The 2 is for the header and footer - if (removeFooter) size--; // The last one has no footer - } + size += slimSize; + if (slimSize == 0) removeFooter = true; } + if (withHeaders) size += 2; // The 2 is for the header and footer + if (removeFooter) size--; // The last one has no footer } return size; } From 6e6cf764790aebce1db9ec16811db3b68bc44ac3 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Wed, 22 Dec 2021 11:38:00 +0100 Subject: [PATCH 81/83] Update TablistManager --- src/de/steamwar/bungeecore/listeners/TablistManager.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 4ef84d7..4cda03a 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -208,8 +208,10 @@ public class TablistManager extends BasicListener { size += slimSize; if (slimSize == 0) removeFooter = true; } - if (withHeaders) size += 2; // The 2 is for the header and footer - if (removeFooter) size--; // The last one has no footer + if (withHeaders) { + size += 2; // The 2 is for the header and footer + if (removeFooter) size--; // The last one has no footer + } } return size; } From 39c72549639d1592f9c3714e4f8b929214323061 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Wed, 22 Dec 2021 17:09:16 +0100 Subject: [PATCH 82/83] Simplify code Signed-off-by: Lixfel --- .../bungeecore/listeners/TablistManager.java | 30 ++++++------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/src/de/steamwar/bungeecore/listeners/TablistManager.java b/src/de/steamwar/bungeecore/listeners/TablistManager.java index 4cda03a..6b5cb34 100644 --- a/src/de/steamwar/bungeecore/listeners/TablistManager.java +++ b/src/de/steamwar/bungeecore/listeners/TablistManager.java @@ -103,7 +103,7 @@ public class TablistManager extends BasicListener { if(bau.size() > 0) tablist.addSubTablist(bau); - size = (int) Math.ceil(tablist.size() / 20.0); + size = (int) Math.ceil((tablist.size() - 1) / 20.0); tablists.values().forEach(Tablist::refresh); seconds++; } @@ -197,23 +197,11 @@ public class TablistManager extends BasicListener { @Override public int slimSize(ProxiedPlayer viewer) { - int size = 0; - for (int i = 0; i < subTablists.size(); i++) { - TablistPart tablistPart = subTablists.get(i); - boolean removeFooter = i == subTablists.size() - 1; - if (viewer == null) { - size += tablistPart.size(); - } else { - int slimSize = tablistPart.slimSize(viewer); - size += slimSize; - if (slimSize == 0) removeFooter = true; - } - if (withHeaders) { - size += 2; // The 2 is for the header and footer - if (removeFooter) size--; // The last one has no footer - } - } - return size; + return subTablists.stream().mapToInt(tPart -> viewer == null ? tPart.size() : tPart.slimSize(viewer)).map(size -> { + size += withHeaders ? 1 : 0; // Space for header + size += withHeaders && size > 1 ? 1 : 0; // Space for footer + return size; + }).sum(); } @Override @@ -225,7 +213,7 @@ public class TablistManager extends BasicListener { public void print(Tablist viewer, boolean slim) { for (int i = 0; i < subTablists.size(); i++) { TablistPart tPart = subTablists.get(i); - boolean removeFooter = i == subTablists.size() - 1; + boolean withoutFooter = i == subTablists.size() - 1; if (withHeaders) { if (slim) { int slimSize = tPart.slimSize(viewer.player); @@ -234,7 +222,7 @@ public class TablistManager extends BasicListener { viewer.setSlot(gray, "§7§l" + tPart.name(), 1000); } else if (slimSize == 0) { viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7" + size + "§8)", 1000); - removeFooter = true; + withoutFooter = true; } else { viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7+" + (size - slimSize) + "§8)", 1000); } @@ -243,7 +231,7 @@ public class TablistManager extends BasicListener { } } tPart.print(viewer, slim); - if (withHeaders && !removeFooter) { + if (withHeaders && !withoutFooter) { viewer.setSlot(darkGray, "", 1000); } } From 5002b07748676fc344a264834ef6d8c24e90d605 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 23 Dec 2021 17:38:08 +0100 Subject: [PATCH 83/83] Fix stack overflow Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/sql/SteamwarUser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 5e9ddce..ea73ffd 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -294,7 +294,7 @@ public class SteamwarUser { player.disconnect(punishmentMessage(punishment, player)); for (BannedUserIPs banned : BannedUserIPs.get(player.getAddress().getAddress().getHostAddress())) { SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID()); - if (isPunished(punishment) && banned.getTimestamp().before(time)) { + if (isPunished(punishment) && bannedUser.getPunishment(punishment).getEndTime().before(time)) { bannedUser.punish(punishment, time, banReason, from, perma); } }