From 9a4e85d7496ef56f7fef2872b8cfb9382a3f5e08 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Thu, 8 Sep 2022 10:42:57 +0200 Subject: [PATCH 01/11] WIP current state --- CommonCore | 2 +- .../steamwar/core/WorldOfColorWrapper12.java | 32 -- SpigotCore_14/build.gradle | 1 + SpigotCore_18/build.gradle | 1 + SpigotCore_8/build.gradle | 1 + .../steamwar/core/WorldOfColorWrapper8.java | 32 -- .../src/de/steamwar/core/Core.java | 26 +- .../src/de/steamwar/core/ErrorHandler.java | 10 +- .../de/steamwar/core/WorldOfColorWrapper.java | 34 -- .../steamwar/inventory/SchematicSelector.java | 6 +- .../src/de/steamwar/sql/BauweltMember.java | 80 ----- .../src/de/steamwar/sql/CheckedSchematic.java | 66 ++-- .../src/de/steamwar/sql/Event.java | 69 ---- .../src/de/steamwar/sql/EventFight.java | 76 ---- .../src/de/steamwar/sql/Fight.java | 40 --- .../src/de/steamwar/sql/FightPlayer.java | 28 -- .../de/steamwar/sql/NoClipboardException.java | 23 -- .../src/de/steamwar/sql/NodeMember.java | 65 ---- .../src/de/steamwar/sql/PersonalKit.java | 122 ++++--- .../src/de/steamwar/sql/Provider.java | 40 +-- .../src/de/steamwar/sql/SQLConfigImpl.java | 37 ++ .../src/de/steamwar/sql/SQLProvider.java | 330 +++--------------- .../src/de/steamwar/sql/SQLWrapperImpl.java | 63 ++++ .../src/de/steamwar/sql/SchematicType.java | 140 -------- .../de/steamwar/sql/StandaloneProvider.java | 120 ------- .../src/de/steamwar/sql/Statement.java | 156 --------- .../src/de/steamwar/sql/SteamwarUser.java | 135 ------- .../src/de/steamwar/sql/UserGroup.java | 72 ---- 28 files changed, 249 insertions(+), 1558 deletions(-) delete mode 100644 SpigotCore_12/src/de/steamwar/core/WorldOfColorWrapper12.java delete mode 100644 SpigotCore_8/src/de/steamwar/core/WorldOfColorWrapper8.java delete mode 100644 SpigotCore_Main/src/de/steamwar/core/WorldOfColorWrapper.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Event.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/EventFight.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Fight.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/NoClipboardException.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/NodeMember.java create mode 100644 SpigotCore_Main/src/de/steamwar/sql/SQLConfigImpl.java create mode 100644 SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SchematicType.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Statement.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/UserGroup.java diff --git a/CommonCore b/CommonCore index 211f625..c1e175c 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit 211f6258b5bd5a50253a21bd82804edb12f34e3e +Subproject commit c1e175c3e84280c160ae5c7f84e44805f159bbf3 diff --git a/SpigotCore_12/src/de/steamwar/core/WorldOfColorWrapper12.java b/SpigotCore_12/src/de/steamwar/core/WorldOfColorWrapper12.java deleted file mode 100644 index 8214a6c..0000000 --- a/SpigotCore_12/src/de/steamwar/core/WorldOfColorWrapper12.java +++ /dev/null @@ -1,32 +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.core; - -import org.bukkit.entity.Player; - -import java.util.Locale; - -public class WorldOfColorWrapper12 implements WorldOfColorWrapper.IWorldOfColorWrapper { - - @Override - public Locale getLocale(Player player){ - return Locale.forLanguageTag(player.getLocale().replace('_', '-')); - } -} diff --git a/SpigotCore_14/build.gradle b/SpigotCore_14/build.gradle index a2b01ba..8aa97f9 100644 --- a/SpigotCore_14/build.gradle +++ b/SpigotCore_14/build.gradle @@ -44,6 +44,7 @@ sourceSets { dependencies { implementation project(":SpigotCore_Main") + implementation project(':CommonCore') compileOnly project(":SpigotCore_8") compileOnly project(":SpigotCore_9") diff --git a/SpigotCore_18/build.gradle b/SpigotCore_18/build.gradle index c557d7f..f95ffc5 100644 --- a/SpigotCore_18/build.gradle +++ b/SpigotCore_18/build.gradle @@ -45,6 +45,7 @@ sourceSets { dependencies { implementation project(":SpigotCore_Main") implementation project(":SpigotCore_14") + implementation project(':CommonCore') compileOnly swdep("WorldEdit-1.15") diff --git a/SpigotCore_8/build.gradle b/SpigotCore_8/build.gradle index 84f62cf..4a72bb4 100644 --- a/SpigotCore_8/build.gradle +++ b/SpigotCore_8/build.gradle @@ -44,6 +44,7 @@ sourceSets { dependencies { implementation project(":SpigotCore_Main") + implementation project(':CommonCore') compileOnly swdep("Spigot-1.8") compileOnly swdep("WorldEdit-1.12") diff --git a/SpigotCore_8/src/de/steamwar/core/WorldOfColorWrapper8.java b/SpigotCore_8/src/de/steamwar/core/WorldOfColorWrapper8.java deleted file mode 100644 index 457dea2..0000000 --- a/SpigotCore_8/src/de/steamwar/core/WorldOfColorWrapper8.java +++ /dev/null @@ -1,32 +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.core; - -import org.bukkit.entity.Player; - -import java.util.Locale; - -public class WorldOfColorWrapper8 implements WorldOfColorWrapper.IWorldOfColorWrapper { - - @Override - public Locale getLocale(Player player){ - return Locale.forLanguageTag(player.spigot().getLocale().replace('_', '-')); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/core/Core.java b/SpigotCore_Main/src/de/steamwar/core/Core.java index 52b5841..5c016a3 100644 --- a/SpigotCore_Main/src/de/steamwar/core/Core.java +++ b/SpigotCore_Main/src/de/steamwar/core/Core.java @@ -31,13 +31,13 @@ import de.steamwar.core.events.PlayerJoinedEvent; import de.steamwar.core.events.WorldLoadEvent; import de.steamwar.message.Message; import de.steamwar.network.NetworkReceiver; -import de.steamwar.sql.Statement; +import de.steamwar.sql.SteamwarUser; +import de.steamwar.sql.internal.Statement; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; @@ -82,16 +82,6 @@ public class Core extends JavaPlugin{ Core.instance = instance; } - private static boolean standalone = true; - public static boolean standalone() { - return standalone; - } - - private static File sqlConfig; - public static File sqlConfig() { - return sqlConfig; - } - private ErrorHandler errorHandler; private CrashDetector crashDetector; @@ -102,7 +92,6 @@ public class Core extends JavaPlugin{ @Override public void onEnable() { - setSqlConfig(); errorHandler = new ErrorHandler(); crashDetector = new CrashDetector(); @@ -131,6 +120,8 @@ public class Core extends JavaPlugin{ if(Core.getVersion() < 17 && Bukkit.getPluginManager().getPlugin("ViaVersion") != null) new PartialChunkFixer(); + Bukkit.getScheduler().runTaskTimer(Core.getInstance(), SteamwarUser::clear, 72000, 72000); + if(Core.getVersion() >= 19) //new ServerDataHandler(); @@ -146,13 +137,6 @@ public class Core extends JavaPlugin{ TinyProtocol.instance.close(); crashDetector.stop(); errorHandler.unregister(); - if(!standalone) { - Statement.close(); - } - } - - private static void setSqlConfig() { - sqlConfig = new File(System.getProperty("user.home"), "MySQL.yml"); - standalone = !sqlConfig.exists(); + Statement.closeAll(); } } diff --git a/SpigotCore_Main/src/de/steamwar/core/ErrorHandler.java b/SpigotCore_Main/src/de/steamwar/core/ErrorHandler.java index 35e4277..9d55e90 100644 --- a/SpigotCore_Main/src/de/steamwar/core/ErrorHandler.java +++ b/SpigotCore_Main/src/de/steamwar/core/ErrorHandler.java @@ -21,7 +21,6 @@ package de.steamwar.core; import com.comphenix.tinyprotocol.Reflection; import de.steamwar.sql.SWException; -import de.steamwar.sql.Statement; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -74,10 +73,11 @@ public class ErrorHandler extends Handler { if(stacktrace.contains("POI data mismatch")) return; - if(!Statement.connectionStable()) - return; - - SWException.log(message, stacktrace); + try { + SWException.log(message, stacktrace); + } catch (SecurityException e) { + Core.getInstance().getLogger().log(Level.INFO, "Could not log error in database", e); + } } @Override diff --git a/SpigotCore_Main/src/de/steamwar/core/WorldOfColorWrapper.java b/SpigotCore_Main/src/de/steamwar/core/WorldOfColorWrapper.java deleted file mode 100644 index 70f7269..0000000 --- a/SpigotCore_Main/src/de/steamwar/core/WorldOfColorWrapper.java +++ /dev/null @@ -1,34 +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.core; - -import org.bukkit.entity.Player; - -import java.util.Locale; - -public class WorldOfColorWrapper { - private WorldOfColorWrapper() {} - - public static final IWorldOfColorWrapper impl = VersionDependent.getVersionImpl(Core.getInstance()); - - public interface IWorldOfColorWrapper { - Locale getLocale(Player player); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/inventory/SchematicSelector.java b/SpigotCore_Main/src/de/steamwar/inventory/SchematicSelector.java index 0f6ba59..c530544 100644 --- a/SpigotCore_Main/src/de/steamwar/inventory/SchematicSelector.java +++ b/SpigotCore_Main/src/de/steamwar/inventory/SchematicSelector.java @@ -323,7 +323,7 @@ public class SchematicSelector { } else { List> types = new ArrayList<>(); SchematicType.values().forEach(schematicType -> { - types.add(new SWListInv.SWListEntry<>(new SWItem(schematicType.getMaterial(), "§e" + schematicType.name(), Collections.emptyList(), schematicType.fightType(), n -> {}), schematicType)); + types.add(new SWListInv.SWListEntry<>(new SWItem(SWItem.getMaterial(schematicType.getMaterial()), "§e" + schematicType.name(), Collections.emptyList(), schematicType.fightType(), n -> {}), schematicType)); }); SWListInv listInv = new SWListInv<>(player, Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_SEL_TYPE", player), types, (clickType1, schematicType) -> { filter.setType(schematicType); @@ -334,9 +334,9 @@ public class SchematicSelector { }; if(filter.getType() == null) { - inv.setItem(2, SchematicType.Normal.getMaterial(), Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE", player), schemTypeCallback); + inv.setItem(2, SWItem.getMaterial(SchematicType.Normal.getMaterial()), Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE", player), schemTypeCallback); } else { - inv.setItem(2, filter.getType().getMaterial(), Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE", player), Collections.singletonList(Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE_SEARCH", player, filter.getType().name())), true, schemTypeCallback); + inv.setItem(2, SWItem.getMaterial(filter.getType().getMaterial()), Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE", player), Collections.singletonList(Core.MESSAGE.parse("SCHEM_SELECTOR_FILTER_TYPE_SEARCH", player, filter.getType().name())), true, schemTypeCallback); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java b/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java deleted file mode 100644 index 564b916..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java +++ /dev/null @@ -1,80 +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.sql; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class BauweltMember { - private static final List memberCache = new ArrayList<>(); - - public static void clear() { - memberCache.clear(); - } - - public static BauweltMember getBauMember(UUID ownerID, UUID memberID){ - return getBauMember(SteamwarUser.get(ownerID).getId(), SteamwarUser.get(memberID).getId()); - } - - public static BauweltMember getBauMember(int ownerID, int memberID){ - for(BauweltMember member : memberCache) - if(member.getMemberID() == memberID) - return member; - return Provider.impl.getBauMember(ownerID, memberID); - } - - public static List getMembers(UUID bauweltID){ - return getMembers(SteamwarUser.get(bauweltID).getId()); - } - - public static List getMembers(int bauweltID){ - return Provider.impl.getMembers(bauweltID); - } - - private final int bauweltID; - private final int memberID; - private final boolean worldEdit; - private final boolean world; - - public BauweltMember(int bauweltID, int memberID, boolean worldEdit, boolean world) { - this.bauweltID = bauweltID; - this.memberID = memberID; - this.worldEdit = worldEdit; - this.world = world; - memberCache.add(this); - } - - public int getBauweltID() { - return bauweltID; - } - - public int getMemberID() { - return memberID; - } - - public boolean isWorldEdit() { - return worldEdit; - } - - public boolean isWorld() { - return world; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java b/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java index 3c19e4e..de3c0e2 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java +++ b/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java @@ -19,67 +19,57 @@ package de.steamwar.sql; +import de.steamwar.sql.internal.Field; +import de.steamwar.sql.internal.SelectStatement; +import de.steamwar.sql.internal.Table; +import lombok.AllArgsConstructor; +import lombok.Getter; + import java.sql.Timestamp; import java.util.List; -import java.util.UUID; +@AllArgsConstructor public class CheckedSchematic { + private static final Table table = new Table<>(CheckedSchematic.class); + private static final SelectStatement statusOfNode = new SelectStatement<>(table, "SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); + public static List getLastDeclinedOfNode(SchematicNode node){ return getLastDeclinedOfNode(node.getId()); } public static List getLastDeclinedOfNode(int node){ - return Provider.impl.getLastDeclinedOfNode(node); + return statusOfNode.listSelect(node); } - public static List getLastDeclined(UUID uuid){ - return getLastDelined(SteamwarUser.get(uuid).getId()); - } - - public static List getLastDelined(int schemOwner){ - return Provider.impl.getLastDelined(schemOwner); - } - - private final Integer node; + @Field(nullable = true) + private final Integer nodeId; + @Field + private final int nodeOwner; + @Field + private final String nodeName; + @Getter + @Field private final int validator; + @Getter + @Field private final Timestamp startTime; + @Getter + @Field private final Timestamp endTime; + @Getter + @Field private final String declineReason; - public CheckedSchematic(Integer node, int validator, Timestamp startTime, Timestamp endTime, String declineReason) { - this.node = node; - this.validator = validator; - this.startTime = startTime; - this.endTime = endTime; - this.declineReason = declineReason; - } - - public int getValidator() { - return validator; - } - - public Timestamp getStartTime() { - return startTime; - } - - public Timestamp getEndTime() { - return endTime; - } - - public String getDeclineReason() { - return declineReason; - } - public int getNode() { - return node; + return nodeId; } public String getSchemName() { - return SchematicNode.getSchematicNode(node).getName(); + return nodeName; } public int getSchemOwner() { - return SchematicNode.getSchematicNode(node).getId(); + return nodeOwner; } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Event.java b/SpigotCore_Main/src/de/steamwar/sql/Event.java deleted file mode 100644 index a08ad8f..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Event.java +++ /dev/null @@ -1,69 +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.sql; - -import java.sql.Timestamp; - -public class Event { - - public static Event get(int eventID){ - return Provider.impl.getEvent(eventID); - } - - private final int eventID; - private final String eventName; - private final Timestamp start; - private final Timestamp end; - private final int maximumTeamMembers; - private final boolean publicSchemsOnly; - private final boolean spectateSystem; - - public Event(int eventID, String eventName, Timestamp start, Timestamp end, int maximumTeamMembers, boolean publicSchemsOnly, boolean spectateSystem) { - this.eventID = eventID; - this.eventName = eventName; - this.start = start; - this.end = end; - this.maximumTeamMembers = maximumTeamMembers; - this.publicSchemsOnly = publicSchemsOnly; - this.spectateSystem = spectateSystem; - } - - public int getEventID() { - return eventID; - } - public String getEventName() { - return eventName; - } - public Timestamp getStart() { - return start; - } - public Timestamp getEnd() { - return end; - } - public int getMaximumTeamMembers() { - return maximumTeamMembers; - } - public boolean publicSchemsOnly() { - return publicSchemsOnly; - } - public boolean spectateSystem(){ - return spectateSystem; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java b/SpigotCore_Main/src/de/steamwar/sql/EventFight.java deleted file mode 100644 index c60e227..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java +++ /dev/null @@ -1,76 +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.sql; - -public class EventFight { - - public static EventFight get(int fightID) { - return Provider.impl.getEventFight(fightID); - } - - private final int eventID; - private final int fightID; - private final int teamBlue; - private final int teamRed; - private final int kampfleiter; - private final int ergebnis; - - public EventFight(int eventID, int fightID, int teamBlue, int teamRed, int kampfleiter, int ergebnis) { - this.eventID = eventID; - this.fightID = fightID; - this.teamBlue = teamBlue; - this.teamRed = teamRed; - this.kampfleiter = kampfleiter; - this.ergebnis = ergebnis; - } - - public void setErgebnis(int winner) { - Provider.impl.setEventFightResult(this, winner); - } - - public void setFight(int fight) { - //Fight.FightID, not EventFight.FightID - Provider.impl.setEventFightFightID(this, fight); - } - - public int getTeamBlue() { - return teamBlue; - } - - public int getTeamRed() { - return teamRed; - } - - public int getEventID() { - return eventID; - } - - public int getFightID() { - return fightID; - } - - public int getKampfleiter() { - return kampfleiter; - } - - public int getErgebnis() { - return ergebnis; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Fight.java b/SpigotCore_Main/src/de/steamwar/sql/Fight.java deleted file mode 100644 index 36586f4..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Fight.java +++ /dev/null @@ -1,40 +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.sql; - -import java.io.InputStream; -import java.sql.Timestamp; -import java.util.function.Consumer; - -public class Fight { - private Fight(){} - - public static int create(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition){ - return Provider.impl.createFight(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition); - } - - public static void getReplay(int fightID, Consumer reader) { - Provider.impl.getReplay(fightID, reader); - } - - public static void setReplay(int fightID, InputStream data) { - Provider.impl.setReplay(fightID, data); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java b/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java deleted file mode 100644 index df65d54..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java +++ /dev/null @@ -1,28 +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.sql; - -public class FightPlayer { - private FightPlayer(){} - - public static void create(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut){ - Provider.impl.createFightPlayer(fightID, userID, blue, kit, kills, isOut); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/NoClipboardException.java b/SpigotCore_Main/src/de/steamwar/sql/NoClipboardException.java deleted file mode 100644 index 9743348..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/NoClipboardException.java +++ /dev/null @@ -1,23 +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.sql; - -public class NoClipboardException extends RuntimeException { -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java b/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java deleted file mode 100644 index e52298a..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java +++ /dev/null @@ -1,65 +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.sql; - -import java.util.Set; -import java.util.function.Consumer; - -public class NodeMember { - - public static NodeMember getNodeMember(int node, int member) { - return Provider.impl.getNodeMember(node, member); - } - - public static Set getNodeMembers(int node) { - return Provider.impl.getNodeMembers(node); - } - - public static Set getSchematics(int member) { - return Provider.impl.getMemberSchematics(member); - } - - public static NodeMember createNodeMember(int node, int member) { - Provider.impl.createNodeMember(node, member); - return getNodeMember(node, member); - } - - private final int node; - private final int member; - private final Consumer delete; - - public NodeMember(int node, int member, Consumer delete) { - this.node = node; - this.member = member; - this.delete = delete; - } - - public int getNode() { - return node; - } - - public int getMember() { - return member; - } - - public void delete() { - delete.accept(this); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java index b267e5c..44fcff9 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java +++ b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java @@ -19,6 +19,12 @@ package de.steamwar.sql; +import de.steamwar.sql.internal.Field; +import de.steamwar.sql.internal.SelectStatement; +import de.steamwar.sql.internal.Statement; +import de.steamwar.sql.internal.Table; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; @@ -26,43 +32,39 @@ import java.io.StringReader; import java.util.List; import java.util.Objects; +@AllArgsConstructor public class PersonalKit { - public static List get(int userID, String gamemode){ - return Provider.impl.getKits(userID, gamemode); - } - - public static PersonalKit get(int userID, String gamemode, String name) { - return Provider.impl.getKit(userID, gamemode, name); - } - - public static PersonalKit create(int userID, String gamemode, String name, ItemStack[] inventory, ItemStack[] armor){ - if(armor == null) { - armor = new ItemStack[]{null, null, null, null}; - } - PersonalKit kit = new PersonalKit(userID, name, gamemode, saveInvConfig("Inventory", inventory), saveInvConfig("Armor", armor), true); - Provider.impl.updateKit(kit); - return kit; - } - - public static PersonalKit getKitInUse(int userID, String gamemode) { - return Provider.impl.getKitInUse(userID, gamemode); - } + private static final Table table = new Table<>(PersonalKit.class); + private static final SelectStatement getKits = table.selectFields("UserID", "GameMode"); + private static final SelectStatement getKit = table.select(Table.PRIMARY); + private static final SelectStatement getKitInUse = table.selectFields("UserID", "GameMode", "InUse"); + private static final Statement update = table.insertAll(); + private static final Statement delete = table.delete(Table.PRIMARY); + @Getter + @Field(keys = {Table.PRIMARY}) private final int userID; - private String name; + @Getter + @Field(keys = {Table.PRIMARY}) private final String gamemode; + @Getter + @Field(keys = {Table.PRIMARY}) + private final String name; + @Field private String inventory; + @Field private String armor; + @Getter + @Field(def = "1") private boolean inUse; - public PersonalKit(int userID, String name, String gamemode, String inventory, String armor, boolean inUse) { - this.userID = userID; - this.name = name; - this.gamemode = gamemode; - this.inventory = inventory; - this.armor = armor; - this.inUse = inUse; + public String getRawInventory() { + return inventory; + } + + public String getRawArmor() { + return armor; } public ItemStack[] getInventory(){ @@ -75,30 +77,6 @@ public class PersonalKit { return Objects.requireNonNull(config.getList("Armor")).toArray(new ItemStack[0]); } - public int getUserID() { - return userID; - } - - public String getName() { - return name; - } - - public String getGamemode() { - return gamemode; - } - - public String getRawInventory() { - return inventory; - } - - public String getRawArmor() { - return armor; - } - - public boolean isInUse() { - return inUse; - } - public void setInUse() { PersonalKit kit = getKitInUse(userID, gamemode); if(kit != null) @@ -108,32 +86,52 @@ public class PersonalKit { private void setUse(boolean inUse) { this.inUse = inUse; - Provider.impl.updateKit(this); - } - - public void setName(String name) { - this.name = name; - Provider.impl.updateKit(this); + update(); } public void setInventory(ItemStack[] inventory) { this.inventory = saveInvConfig("Inventory", inventory); - Provider.impl.updateKit(this); + update(); } public void setArmor(ItemStack[] armor) { this.armor = saveInvConfig("Armor", armor); - Provider.impl.updateKit(this); + update(); } public void setContainer(ItemStack[] inventory, ItemStack[] armor) { this.armor = saveInvConfig("Armor", armor); this.inventory = saveInvConfig("Inventory", inventory); - Provider.impl.updateKit(this); + update(); } public void delete() { - Provider.impl.deleteKit(this); + delete.update(userID, gamemode, name); + } + + private void update() { + update.update(userID, gamemode, name, inventory, armor, inUse); + } + + public static List get(int userID, String gamemode){ + return getKits.listSelect(userID, gamemode); + } + + public static PersonalKit get(int userID, String gamemode, String name) { + return getKit.select(userID, gamemode, name); + } + + public static PersonalKit create(int userID, String gamemode, String name, ItemStack[] inventory, ItemStack[] armor){ + if(armor == null) { + armor = new ItemStack[]{null, null, null, null}; + } + PersonalKit kit = new PersonalKit(userID, gamemode, name, saveInvConfig("Inventory", inventory), saveInvConfig("Armor", armor), true); + kit.update(); + return kit; + } + + public static PersonalKit getKitInUse(int userID, String gamemode) { + return getKitInUse.select(userID, gamemode); } private static String saveInvConfig(String name, ItemStack[] inv) { diff --git a/SpigotCore_Main/src/de/steamwar/sql/Provider.java b/SpigotCore_Main/src/de/steamwar/sql/Provider.java index b511a03..0ece5ae 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Provider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Provider.java @@ -19,62 +19,24 @@ package de.steamwar.sql; -import de.steamwar.core.Core; - import java.io.IOException; import java.io.InputStream; -import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; -import java.util.function.Consumer; public interface Provider { - Provider impl = Core.standalone() ? new StandaloneProvider() : new SQLProvider(); - - BauweltMember getBauMember(int ownerID, int memberID); - List getMembers(int bauweltID); - - List getLastDeclinedOfNode(int node); - List getLastDelined(int schemOwner); - - Event getEvent(int eventID); - EventFight getEventFight(int fightID); - void setEventFightResult(EventFight fight, int winner); - void setEventFightFightID(EventFight fight, int fightID); + Provider impl = new SQLProvider(); boolean hasEventTeam(int teamID, int eventID); Set getEventTeams(int eventID); Set getTeamEvents(int teamID); - int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition); - void getReplay(int fightID, Consumer reader); - void setReplay(int fightID, InputStream data); - - void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut); - void createDownloadLink(int nodeId, String hash); - NodeMember getNodeMember(int node, int member); - Set getNodeMembers(int node); - Set getMemberSchematics(int member); - void createNodeMember(int node, int member); - - List getKits(int userID, String gamemode); - PersonalKit getKit(int userID, String gamemode, String name); - void updateKit(PersonalKit kit); - void deleteKit(PersonalKit kit); - PersonalKit getKitInUse(int userID, String gamemode); - Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type); Map getPunishmentsOfPlayer(int user); - SteamwarUser getUserByName(String userName); - SteamwarUser getUserByUUID(UUID uuid); - SteamwarUser getUserByID(int id); - List getServerTeam(); - void logException(String server, String message, String stacktrace); Team getTeam(int id); diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLConfigImpl.java b/SpigotCore_Main/src/de/steamwar/sql/SQLConfigImpl.java new file mode 100644 index 0000000..dd54f35 --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLConfigImpl.java @@ -0,0 +1,37 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import de.steamwar.core.Core; +import de.steamwar.sql.internal.SQLConfig; + +import java.util.logging.Logger; + +public class SQLConfigImpl implements SQLConfig { + @Override + public Logger getLogger() { + return Core.getInstance().getLogger(); + } + + @Override + public int maxConnections() { + return 1; + } +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java index ce1da9a..d6e4165 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java @@ -19,103 +19,26 @@ package de.steamwar.sql; +import de.steamwar.sql.internal.Statement; + 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.util.*; -import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; public class SQLProvider implements Provider { - private static final Statement getBauMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); - @Override - public BauweltMember getBauMember(int ownerID, int memberID) { - return getBauMember.select(rs -> rs.next() ? newBauweltMember(rs) : null, ownerID, memberID); - } - - private static final Statement getBauMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); - @Override - public List getMembers(int bauweltID) { - return getBauMembers.select(rs -> { - List members = new ArrayList<>(); - while(rs.next()) - members.add(newBauweltMember(rs)); - return members; - }, bauweltID); - } - - private BauweltMember newBauweltMember(ResultSet rs) throws SQLException { - return new BauweltMember(rs.getInt("BauweltID"), rs.getInt("MemberID"), rs.getBoolean("WorldEdit"), rs.getBoolean("World")); - } - - private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); - @Override - public List getLastDeclinedOfNode(int node) { - return nodeHistory.select(rs -> { - List lastDeclined = new ArrayList<>(); - while(rs.next()) - lastDeclined.add(newCheckedSchematic(rs)); - return lastDeclined; - }, node); - } - - 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"); - @Override - public List getLastDelined(int schemOwner) { - return checkHistory.select(rs -> { - List history = new ArrayList<>(); - while(rs.next()) - history.add(newCheckedSchematic(rs)); - return history; - }, schemOwner); - } - - private CheckedSchematic newCheckedSchematic(ResultSet rs) throws SQLException { - return new CheckedSchematic(rs.getInt("NodeId"), rs.getInt("Validator"), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getString("DeclineReason")); - } - - private static final Statement getEvent = new Statement("SELECT * FROM Event WHERE EventID = ?"); - @Override - public Event getEvent(int eventID) { - return getEvent.select(rs -> { - rs.next(); - return new Event(rs.getInt("EventID"), rs.getString("EventName"), rs.getTimestamp("Start"), rs.getTimestamp("End"), rs.getInt("MaximumTeamMembers"), rs.getBoolean("PublicSchemsOnly"), rs.getBoolean("SpectateSystem")); - }, eventID); - } - - private static final Statement getEventFight = new Statement("SELECT * FROM EventFight WHERE FightID = ?"); - @Override - public EventFight getEventFight(int fightID) { - return getEventFight.select(rs -> { - rs.next(); - return new EventFight(rs.getInt("EventID"), rs.getInt("FightID"), rs.getInt("TeamBlue"), rs.getInt("TeamRed"), rs.getInt("Kampfleiter"), rs.getInt("Ergebnis")); - }, fightID); - } - - private static final Statement setEventFightResult = new Statement("UPDATE EventFight SET Ergebnis = ? WHERE FightID = ?"); - @Override - public void setEventFightResult(EventFight fight, int winner) { - setEventFightResult.update(winner, fight.getFightID()); - } - - private static final Statement setEventFightFightID = new Statement("UPDATE EventFight SET Fight = ? WHERE FightID = ?"); - @Override - public void setEventFightFightID(EventFight fight, int fightID) { - setEventFightFightID.update(fightID, fight.getFightID()); - } - - private static final Statement hasEventTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); + private static final de.steamwar.sql.internal.Statement hasEventTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); @Override public boolean hasEventTeam(int teamID, int eventID) { return hasEventTeam.select(ResultSet::next, teamID, eventID); } - private static final Statement eventTeams = new Statement("SELECT * FROM TeamTeilnahme WHERE EventID = ?"); + private static final de.steamwar.sql.internal.Statement eventTeams = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE EventID = ?"); @Override public Set getEventTeams(int eventID) { return eventTeams.select(rs -> { @@ -126,7 +49,7 @@ public class SQLProvider implements Provider { }, eventID); } - private static final Statement eventsTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ?"); + private static final de.steamwar.sql.internal.Statement eventsTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ?"); @Override public Set getTeamEvents(int teamID) { return eventsTeam.select(rs -> { @@ -137,136 +60,13 @@ public class SQLProvider implements Provider { }, teamID); } - private static final Statement createFight = new Statement("INSERT INTO Fight (GameMode, Server, StartTime, Duration, BlueLeader, RedLeader, BlueSchem, RedSchem, Win, WinCondition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - private static final Statement getLastFightID = new Statement("SELECT LAST_INSERT_ID() AS FightID"); - @Override - public int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition) { - createFight.update(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition); - return getLastFightID.select(rs -> { - rs.next(); - return rs.getInt("FightID"); - }); - } - - private static final Statement getReplay = new Statement("SELECT Replay FROM Replay WHERE FightID = ?"); - @Override - public void getReplay(int fightID, Consumer reader) { - getReplay.select(rs -> { - rs.next(); - reader.accept(rs.getBinaryStream("Replay")); - return null; - }, fightID); - } - - private static final Statement setReplay = new Statement("INSERT INTO Replay (FightID, Replay) VALUES (?, ?)"); - @Override - public void setReplay(int fightID, InputStream data) { - setReplay.update(fightID, data); - } - - private static final Statement create = new Statement("INSERT INTO FightPlayer (FightID, UserID, Team, Kit, Kills, IsOut) VALUES (?, ?, ?, ?, ?, ?)"); - @Override - public void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut) { - create.update(fightID, userID, blue ? 1 : 2, kit, kills, isOut); - } - - private static final Statement createLink = new Statement("INSERT INTO NodeDownload (NodeId, Link) VALUES (?, ?) ON DUPLICATE KEY UPDATE Link = VALUES(Link)"); + private static final de.steamwar.sql.internal.Statement createLink = new de.steamwar.sql.internal.Statement("INSERT INTO NodeDownload (NodeId, Link) VALUES (?, ?) ON DUPLICATE KEY UPDATE Link = VALUES(Link)"); @Override public void createDownloadLink(int nodeId, String hash) { createLink.update(nodeId, hash); } - private static final Statement getNodeMember = new Statement("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?"); - @Override - public NodeMember getNodeMember(int node, int member) { - return getNodeMember.select(rs -> { - if(!rs.next()) - return null; - return newNodeMember(rs); - }, node, member); - } - - private static final Statement getNodeMembers = new Statement("SELECT * FROM NodeMember WHERE NodeId = ?"); - @Override - public Set getNodeMembers(int node) { - return getNodeMembers.select(rs -> { - Set members = new HashSet<>(); - while (rs.next()) - members.add(newNodeMember(rs)); - return members; - }, node); - } - - private static final Statement getSchematics = new Statement("SELECT * FROM NodeMember WHERE UserId = ?"); - @Override - public Set getMemberSchematics(int member) { - return getSchematics.select(rs -> { - Set members = new HashSet<>(); - while (rs.next()) - members.add(newNodeMember(rs)); - return members; - }, member); - } - - private static final Statement deleteNodeMember = new Statement("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?"); - private NodeMember newNodeMember(ResultSet rs) throws SQLException { - return new NodeMember(rs.getInt("NodeId"), rs.getInt("UserId"), member -> deleteNodeMember.update(member.getNode(), member.getMember())); - } - - private static final Statement createNodeMember = new Statement("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)"); - @Override - public void createNodeMember(int node, int member) { - createNodeMember.update(node, member); - } - - private static final Statement getKits = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ?"); - @Override - public List getKits(int userID, String gamemode) { - return getKits.select(rs -> { - List list = new ArrayList<>(); - while (rs.next()) - list.add(newPersonalKit(rs)); - return list; - }, userID, gamemode); - } - - private static final Statement getKit = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND Name = ?"); - @Override - public PersonalKit getKit(int userID, String gamemode, String name) { - return getKit.select(rs -> { - if(rs.next()) - return newPersonalKit(rs); - return null; - }, userID, gamemode, name); - } - - private PersonalKit newPersonalKit(ResultSet rs) throws SQLException { - return new PersonalKit(rs.getInt("UserID"), rs.getString("Name"), rs.getString("GameMode"), rs.getString("Inventory"), rs.getString("Armor"), rs.getBoolean("InUse")); - } - - private static final Statement updateKit = new Statement("INSERT INTO PersonalKit (UserID, GameMode, Name, Inventory, Armor, InUse) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE Inventory = VALUES(Inventory), Armor = VALUES(Armor), Name = VALUES(Name), InUse = VALUES(InUse)"); - @Override - public void updateKit(PersonalKit kit) { - updateKit.update(kit.getUserID(), kit.getGamemode(), kit.getName(), kit.getRawInventory(), kit.getRawArmor(), kit.isInUse()); - } - - private static final Statement deleteKit = new Statement("DELETE FROM `PersonalKit` WHERE UserID = ? AND GameMode = ? AND Name = ?"); - @Override - public void deleteKit(PersonalKit kit) { - deleteKit.update(kit.getUserID(), kit.getGamemode(), kit.getName()); - } - - private static final Statement getKitInUse = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND InUse = 1"); - @Override - public PersonalKit getKitInUse(int userID, String gamemode) { - return getKitInUse.select(rs -> { - if(rs.next()) - return newPersonalKit(rs); - return null; - }, userID, gamemode); - } - - private static final Statement getPunishment = new Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); + private static final de.steamwar.sql.internal.Statement getPunishment = new de.steamwar.sql.internal.Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); @Override public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { return getPunishment.select(rs -> { @@ -280,7 +80,7 @@ public class SQLProvider implements Provider { return new Punishment(rs.getInt("UserId"), rs.getInt("Punisher"), Punishment.PunishmentType.valueOf(rs.getString("Type")), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getBoolean("Perma"), rs.getString("Reason")); } - 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 de.steamwar.sql.internal.Statement getPunishments = new de.steamwar.sql.internal.Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); @Override public Map getPunishmentsOfPlayer(int user) { return getPunishments.select(rs -> { @@ -291,57 +91,13 @@ public class SQLProvider implements Provider { }, user); } - private static final Statement getUserName = new Statement("SELECT * FROM UserData WHERE lower(UserName) = ?"); - @Override - public SteamwarUser getUserByName(String userName) { - return getUserName.select(rs -> { - if(rs.next()) - return newSteamwarUser(rs); - return null; - }, userName.toLowerCase()); - } - - private static final Statement getUserUUID = new Statement("SELECT * FROM UserData WHERE UUID = ?"); - @Override - public SteamwarUser getUserByUUID(UUID uuid) { - return getUserUUID.select(rs -> { - rs.next(); - return newSteamwarUser(rs); - }, uuid.toString()); - } - - private static final Statement getUserId = new Statement("SELECT * FROM UserData WHERE id = ?"); - @Override - public SteamwarUser getUserByID(int id) { - return getUserId.select(rs -> { - rs.next(); - return newSteamwarUser(rs); - }, id); - } - - private static final Statement getServerTeam = new Statement("SELECT * FROM UserData WHERE UserGroup != 'Member' AND UserGroup != 'YouTuber'"); - @Override - public List getServerTeam() { - return getServerTeam.select(rs -> { - List users = new ArrayList<>(); - while(rs.next()) - users.add(newSteamwarUser(rs)); - return users; - }); - } - - private SteamwarUser newSteamwarUser(ResultSet rs) throws SQLException { - String dbLocale = rs.getString("Locale"); - return new SteamwarUser(rs.getInt("id"), UUID.fromString(rs.getString("UUID")), rs.getString("UserName"), UserGroup.getUsergroup(rs.getString("UserGroup")), rs.getInt("Team"), rs.getBoolean("Bedrock"), dbLocale != null ? Locale.forLanguageTag(dbLocale) : null); - } - - private static final Statement insert = new Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); + private static final de.steamwar.sql.internal.Statement insert = new de.steamwar.sql.internal.Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); @Override public void logException(String server, String message, String stacktrace) { insert.update(server, message, stacktrace); } - private static final Statement getTeam = new Statement("SELECT * FROM Team WHERE TeamID = ?"); + private static final de.steamwar.sql.internal.Statement getTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM Team WHERE TeamID = ?"); @Override public Team getTeam(int id) { return getTeam.select(rs -> { @@ -350,7 +106,7 @@ public class SQLProvider implements Provider { }, id); } - private static final Statement getTeamMembers = new Statement("SELECT id FROM UserData WHERE Team = ?"); + private static final de.steamwar.sql.internal.Statement getTeamMembers = new de.steamwar.sql.internal.Statement("SELECT id FROM UserData WHERE Team = ?"); @Override public List getTeamMembers(Team team) { return getTeamMembers.select(rs -> { @@ -361,7 +117,7 @@ public class SQLProvider implements Provider { }, team.getTeamId()); } - private static final Statement getConfig = new Statement("SELECT Value FROM UserConfig WHERE User = ? AND Config = ?"); + private static final de.steamwar.sql.internal.Statement getConfig = new de.steamwar.sql.internal.Statement("SELECT Value FROM UserConfig WHERE User = ? AND Config = ?"); @Override public String getConfig(int player, String config) { return getConfig.select(rs -> { @@ -371,13 +127,13 @@ public class SQLProvider implements Provider { }, player, config); } - private static final Statement setConfig = new Statement("INSERT INTO UserConfig (User, Config, Value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Value = VALUES(Value)"); + private static final de.steamwar.sql.internal.Statement setConfig = new de.steamwar.sql.internal.Statement("INSERT INTO UserConfig (User, Config, Value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Value = VALUES(Value)"); @Override public void updatePlayerConfig(int id, String config, String value) { setConfig.update(id, config, value); } - private static final Statement deleteConfig = new Statement("DELETE FROM UserConfig WHERE User = ? AND Config = ?"); + private static final de.steamwar.sql.internal.Statement deleteConfig = new de.steamwar.sql.internal.Statement("DELETE FROM UserConfig WHERE User = ? AND Config = ?"); @Override public void removePlayerConfig(int id, String config) { deleteConfig.update(id, config); @@ -387,42 +143,42 @@ public class SQLProvider implements Provider { private static String nodeSelectCreator(String itemPrefix) { return "SELECT " + Arrays.stream(nodeSelect).map(s -> itemPrefix + s).collect(Collectors.joining(", ")) + " FROM 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(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); - private static final Statement getSchematicNode = new Statement(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); - private static final Statement getSchematicsInNode_Null = new Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL ORDER BY NodeName"); - private static final Statement getSchematicsInNode = new Statement(nodeSelectCreator("") + "WHERE ParentNode = ? ORDER BY NodeName"); - private static final Statement getDirsInNode_Null = new Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL AND NodeType is NULL ORDER BY NodeName"); - private static final Statement getDirsInNode = new Statement(nodeSelectCreator("") + "WHERE ParentNode = ? AND NodeType is NULL ORDER BY NodeName"); - private static final Statement getSchematicDirectory_Null = new Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL ORDER BY NodeName"); - private static final Statement getSchematicDirectory = new Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final Statement getSchematicNodeO_Null = new Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL "); - private static final Statement getSchematicNodeO = new Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final Statement getSchematicNodeId = new Statement(nodeSelectCreator("") + "WHERE NodeId = ?"); - private static final Statement getAllSchemsOfTypeOwner = new Statement( nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeType = ? ORDER BY NodeName"); - private static final Statement getAllSchemsOfType = new Statement(nodeSelectCreator("") + "WHERE NodeType = ? ORDER BY NodeName"); - private static final Statement getAccessibleByUser = new Statement(nodeSelectCreator("s.") + "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 (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ? ORDER BY NodeName"); - private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null ORDER BY NodeName"); - private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? ORDER BY NodeName"); - private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); - private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "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 (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN ORDER BY 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 = ?, ReplaceColor = ?, AllowReplay = ? 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 = ?"); - private static final Statement schemElo = new Statement("SELECT Elo FROM SchemElo WHERE SchemId = ? AND Season = ?"); + private static final de.steamwar.sql.internal.Statement createNode = new de.steamwar.sql.internal.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 de.steamwar.sql.internal.Statement getSchematicNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); + private static final de.steamwar.sql.internal.Statement getSchematicNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); + private static final de.steamwar.sql.internal.Statement getSchematicsInNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getSchematicsInNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getDirsInNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL AND NodeType is NULL ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getDirsInNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode = ? AND NodeType is NULL ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getSchematicDirectory_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getSchematicDirectory = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getSchematicNodeO_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL "); + private static final de.steamwar.sql.internal.Statement getSchematicNodeO = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getSchematicNodeId = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeId = ?"); + private static final de.steamwar.sql.internal.Statement getAllSchemsOfTypeOwner = new de.steamwar.sql.internal.Statement( nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeType = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getAllSchemsOfType = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeType = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getAccessibleByUser = new de.steamwar.sql.internal.Statement(nodeSelectCreator("s.") + "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 de.steamwar.sql.internal.Statement getAccessibleByUserByTypeInNode = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getAccessibleByUserByTypeInNode_Null = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getAccessibleByUserByType = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement getAllSchematicsAccessibleByUser = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement isSchematicAccessibleForUser = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN AS (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "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 de.steamwar.sql.internal.Statement getAllParentsOfNode = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN AS (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); + private static final de.steamwar.sql.internal.Statement countNodes = new de.steamwar.sql.internal.Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); + private static final de.steamwar.sql.internal.Statement updateDB = new de.steamwar.sql.internal.Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ?, ReplaceColor = ?, AllowReplay = ? WHERE NodeId = ?"); + private static final de.steamwar.sql.internal.Statement updateDatabase = new de.steamwar.sql.internal.Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?"); + private static final de.steamwar.sql.internal.Statement selSchemData = new de.steamwar.sql.internal.Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?"); + private static final de.steamwar.sql.internal.Statement deleteNode = new de.steamwar.sql.internal.Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); + private static final de.steamwar.sql.internal.Statement schemElo = new de.steamwar.sql.internal.Statement("SELECT Elo FROM SchemElo WHERE SchemId = ? AND Season = ?"); - private static final Statement.ResultSetUser> toSchematicList = rs -> { + private static final de.steamwar.sql.internal.Statement.ResultSetUser> toSchematicList = rs -> { List nodes = new ArrayList<>(); while (rs.next()) { nodes.add(nodeFromResultSet(rs)); } return nodes; }; - private static final Statement.ResultSetUser toSchematicNode = rs -> { + private static final de.steamwar.sql.internal.Statement.ResultSetUser toSchematicNode = rs -> { if (rs.next()) { return nodeFromResultSet(rs); } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java b/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java new file mode 100644 index 0000000..41bb20a --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java @@ -0,0 +1,63 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import de.steamwar.core.Core; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class SQLWrapperImpl implements SQLWrapper { + + @Override + public void loadSchemTypes(List tmpTypes, Map tmpFromDB) { + File folder = new File(Core.getInstance().getDataFolder().getParentFile(), "FightSystem"); + if(folder.exists()) { + for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if(!config.isConfigurationSection("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; + String material = config.getString("Schematic.Material", "STONE_BUTTON"); + + if(!config.getStringList("CheckQuestions").isEmpty()) { + checktype = new SchematicType("C" + type, "C" + shortcut, SchematicType.Type.CHECK_TYPE, null, material); + tmpTypes.add(checktype); + tmpFromDB.put(checktype.toDB(), checktype); + } + + SchematicType current = new SchematicType(type, shortcut, config.isConfigurationSection("Server") ? SchematicType.Type.FIGHT_TYPE : SchematicType.Type.NORMAL, checktype, material); + tmpTypes.add(current); + tmpFromDB.put(type.toLowerCase(), current); + } + } + } +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicType.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicType.java deleted file mode 100644 index 5b5bd0d..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SchematicType.java +++ /dev/null @@ -1,140 +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.sql; - -import de.steamwar.core.Core; -import de.steamwar.inventory.SWItem; -import org.bukkit.Material; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.util.*; -import java.util.stream.Collectors; - -public class SchematicType { - public static final SchematicType Normal = new SchematicType("Normal", "", Type.NORMAL, null, SWItem.getMaterial("STONE_BUTTON")); //Has to stay publicly availible - - private static final Map fromDB; - private static final List types; - - static { - File folder = new File(Core.getInstance().getDataFolder().getParentFile(), "FightSystem"); - - List tmpTypes = new LinkedList<>(); - Map tmpFromDB = new HashMap<>(); - - tmpTypes.add(Normal); - tmpFromDB.put(Normal.name().toLowerCase(), Normal); - - if(folder.exists()) { - for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) { - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - if(!config.isConfigurationSection("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; - Material material = SWItem.getMaterial(config.getString("Schematic.Material", "STONE_BUTTON")); - - if(!config.getStringList("CheckQuestions").isEmpty()) { - checktype = new SchematicType("C" + type, "C" + shortcut, Type.CHECK_TYPE, null, material); - tmpTypes.add(checktype); - tmpFromDB.put(checktype.toDB(), checktype); - } - - SchematicType current = new SchematicType(type, shortcut, config.isConfigurationSection("Server") ? Type.FIGHT_TYPE : Type.NORMAL, checktype, material); - tmpTypes.add(current); - tmpFromDB.put(type.toLowerCase(), current); - } - } - - fromDB = Collections.unmodifiableMap(tmpFromDB); - types = Collections.unmodifiableList(tmpTypes); - } - - private final String name; - private final String kuerzel; - private final Type type; - private final SchematicType checkType; - private final Material material; - - private SchematicType(String name, String kuerzel, Type type, SchematicType checkType, Material material){ - this.name = name; - this.kuerzel = kuerzel; - this.type = type; - this.checkType = checkType; - this.material = material; - } - - public boolean isAssignable(){ - return type == Type.NORMAL || (type == Type.FIGHT_TYPE && checkType != null); - } - - public SchematicType checkType(){ - return checkType; - } - - public boolean check(){ - return type == Type.CHECK_TYPE; - } - - public boolean fightType(){ - return type == Type.FIGHT_TYPE; - } - - public boolean writeable(){ - return type == Type.NORMAL; - } - - public String name(){ - return name; - } - - public String getKuerzel() { - return kuerzel; - } - - public Material getMaterial() { - return material; - } - - public String toDB(){ - return name.toLowerCase(); - } - - public static SchematicType fromDB(String input){ - return fromDB.getOrDefault(input.toLowerCase(), null); - } - - public static List values(){ - return types; - } - - enum Type{ - NORMAL, - CHECK_TYPE, - FIGHT_TYPE - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 0a9b3f7..ade58d2 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -20,10 +20,6 @@ package de.steamwar.sql; import de.steamwar.core.WorldEditWrapper; -import de.steamwar.core.WorldOfColorWrapper; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; import java.io.File; import java.io.FileOutputStream; @@ -34,7 +30,6 @@ import java.nio.file.Path; import java.sql.Timestamp; import java.time.Instant; import java.util.*; -import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; @@ -44,43 +39,6 @@ public class StandaloneProvider implements Provider { nodesToPath.put(-1, schematicDir.toPath()); } - @Override - public BauweltMember getBauMember(int ownerID, int memberID) { - OfflinePlayer player = Bukkit.getOfflinePlayer(SteamwarUser.get(memberID).getUUID()); - return new BauweltMember(ownerID, memberID, player.isOp(), player.isOp()); - } - - @Override - public List getMembers(int bauweltID) { - return Bukkit.getOnlinePlayers().stream().map(player -> getBauMember(bauweltID, SteamwarUser.get(player.getUniqueId()).getId())).collect(Collectors.toList()); - } - - @Override - public List getLastDeclinedOfNode(int node) { - return new ArrayList<>(); - } - - @Override - public List getLastDelined(int schemOwner) { - return new ArrayList<>(); - } - - @Override - public Event getEvent(int eventID) { - return new Event(eventID, "DummyEvent", Timestamp.from(Instant.now()), Timestamp.from(Instant.now()), 6, false, false); - } - - @Override - public EventFight getEventFight(int fightID) { - return new EventFight(0, fightID, 0, 0, 0, 0); - } - - @Override - public void setEventFightResult(EventFight fight, int winner) {} - - @Override - public void setEventFightFightID(EventFight fight, int fightID) {} - @Override public boolean hasEventTeam(int teamID, int eventID) { return false; @@ -96,62 +54,9 @@ public class StandaloneProvider implements Provider { return Collections.emptySet(); } - @Override - public int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition) { - return 0; - } - - @Override - public void getReplay(int fightID, Consumer reader) {} - - @Override - public void setReplay(int fightID, InputStream data) {} - - @Override - public void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut) {} - @Override public void createDownloadLink(int nodeId, String hash) {} - @Override - public NodeMember getNodeMember(int node, int member) { - return null; - } - - @Override - public Set getNodeMembers(int node) { - return Collections.emptySet(); - } - - @Override - public Set getMemberSchematics(int member) { - return Collections.emptySet(); - } - - @Override - public void createNodeMember(int node, int member) {} - - @Override - public List getKits(int userID, String gamemode) { - return Collections.emptyList(); - } - - @Override - public PersonalKit getKit(int userID, String gamemode, String name) { - return null; - } - - @Override - public void updateKit(PersonalKit kit) {} - - @Override - public void deleteKit(PersonalKit kit) {} - - @Override - public PersonalKit getKitInUse(int userID, String gamemode) { - return null; - } - @Override public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { return null; @@ -162,31 +67,6 @@ public class StandaloneProvider implements Provider { return Collections.emptyMap(); } - private int userId = 1; - private final Map usersByUUID = new HashMap<>(); - @Override - public SteamwarUser getUserByName(String userName) { - Player player = Bukkit.getPlayer(userName); - if(player == null) - return null; - return usersByUUID.computeIfAbsent(player.getUniqueId(), uuid -> new SteamwarUser(userId++, uuid, userName, UserGroup.Member, 0, false, null)); - } - - @Override - public SteamwarUser getUserByUUID(UUID uuid) { - return usersByUUID.computeIfAbsent(uuid, uuid1 -> new SteamwarUser(userId++, uuid1, Objects.requireNonNull(Objects.requireNonNull(Bukkit.getOfflinePlayer(uuid1)).getName()), UserGroup.Member, 0, false, null)); - } - - @Override - public SteamwarUser getUserByID(int id) { - return usersByUUID.values().stream().filter(user -> user.getId() == id).findAny().get(); - } - - @Override - public List getServerTeam() { - return Bukkit.getOperators().stream().map(OfflinePlayer::getUniqueId).map(this::getUserByUUID).collect(Collectors.toList()); - } - @Override public void logException(String server, String message, String stacktrace) {} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Statement.java b/SpigotCore_Main/src/de/steamwar/sql/Statement.java deleted file mode 100644 index 20e37f7..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Statement.java +++ /dev/null @@ -1,156 +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.sql; - -import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException; -import de.steamwar.core.Core; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; - -public class Statement { - - private static final String URL; - private static final String USER; - private static final String PASSWORD; - - private static Connection con; - - private static final List statements = new ArrayList<>(); - - static { - File file = Core.sqlConfig(); - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - - if(!file.exists()) - throw new SecurityException("SQL-ConfigFile not found!"); - - URL = "jdbc:mysql://" + config.getString("HOST") + ":" + config.getString("PORT") + "/" + config.getString("DATABASE"); - USER = config.getString("USER"); - PASSWORD = config.getString("PASSWORD"); - - Statement.connect(); - } - - private static void connect() { - try { - con = DriverManager.getConnection(URL + "?useServerPrepStmts=true", USER, PASSWORD); - } catch (SQLException e) { - throw new SecurityException("Could not start SQL connection", e); - } - } - - public static void close() { - for (Statement statement : statements) { - if (statement.st != null) { - try { - statement.st.close(); - } catch (SQLException e) { - Core.getInstance().getLogger().log(Level.INFO, "Could not close statement", e); - } - statement.st = null; - } - } - - try { - con.close(); - } catch (SQLException e) { - Core.getInstance().getLogger().log(Level.INFO, "Could not close SQL connection", e); - } - } - - private static void reset() { - close(); - connect(); - } - - public static boolean connectionStable() { - try { - return !con.isClosed(); - } catch (SQLException e) { - return false; - } - } - - private final String sql; - private PreparedStatement st; - - public Statement(String sql) { - this.sql = sql; - statements.add(this); - } - - public T select(ResultSetUser user, Object... objects) { - return prepare(() -> { - ResultSet rs = getSt().executeQuery(); - T result = user.use(rs); - rs.close(); - return result; - }, objects); - } - - public void update(Object... objects) { - prepare(getSt()::executeUpdate, objects); - } - - private synchronized T prepare(SQLRunnable runnable, Object... objects) { - try { - try { - setObjects(objects); - return runnable.run(); - } catch (CommunicationsException e) { - reset(); - setObjects(objects); - return runnable.run(); - } - } catch (SQLException e) { - throw new SecurityException("Could not execute SQL statement", e); - } - } - - private PreparedStatement getSt() { - if(st == null) { - try { - st = con.prepareStatement(sql); - } catch (SQLException e) { - throw new SecurityException("Could not prepare statement", e); - } - } - return st; - } - - private void setObjects(Object... objects) throws SQLException { - for (int i = 0; i < objects.length; i++) { - getSt().setObject(i + 1, objects[i]); - } - } - - public interface ResultSetUser { - T use(ResultSet rs) throws SQLException; - } - - private interface SQLRunnable { - T run() throws SQLException; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java b/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java deleted file mode 100644 index ff78332..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java +++ /dev/null @@ -1,135 +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.sql; - -import de.steamwar.core.Core; -import de.steamwar.core.WorldOfColorWrapper; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.*; - -public class SteamwarUser { - - - private static final Map byUUID = new HashMap<>(); - private static final Map byName = new HashMap<>(); - private static final Map byId = new HashMap<>(); - - static{ - Bukkit.getScheduler().runTaskTimer(Core.getInstance(), () -> { - byId.clear(); - byName.clear(); - byUUID.clear(); - }, 72000, 72000); - } - - public static void invalidate(int userId) { - SteamwarUser user = byId.remove(userId); - if (user == null) - return; - byName.remove(user.getUserName()); - byUUID.remove(user.getUUID()); - } - - private final int id; - private final UUID uuid; - private final String userName; - private final UserGroup userGroup; - private final int team; - private final boolean bedrock; - private Locale locale; - - public SteamwarUser(int id, UUID uuid, String userName, UserGroup userGroup, int team, boolean bedrock, Locale locale) { - this.id = id; - this.uuid = uuid; - this.userName = userName; - this.userGroup = userGroup; - this.team = team; - this.bedrock = bedrock; - this.locale = locale; - - byUUID.put(uuid, this); - byName.put(userName.toLowerCase(), this); - byId.put(id, this); - } - - public int getId() { - return id; - } - - public UUID getUUID() { - return uuid; - } - - public String getUserName() { - return userName; - } - - public UserGroup getUserGroup() { - return userGroup; - } - - public int getTeam(){ - return team; - } - - public boolean isBedrock(){ - return bedrock; - } - - public Locale getLocale() { - if(locale != null) - return locale; - Locale locale = WorldOfColorWrapper.impl.getLocale(Bukkit.getPlayer(uuid)); - if (locale != null) - return locale; - return Locale.getDefault(); - } - - public static SteamwarUser get(String userName){ - SteamwarUser user = byName.get(userName.toLowerCase()); - if(user == null) - user = Provider.impl.getUserByName(userName); - return user; - } - - public static SteamwarUser get(UUID uuid){ - SteamwarUser user = byUUID.get(uuid); - if(user == null) - user = Provider.impl.getUserByUUID(uuid); - return user; - } - - public static SteamwarUser get(int id) { - SteamwarUser user = byId.get(id); - if(user == null) - user = Provider.impl.getUserByID(id); - return user; - } - - public static SteamwarUser get(Player player) { - return get(player.getUniqueId()); - } - - public static List getServerTeam() { - return Provider.impl.getServerTeam(); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/UserGroup.java b/SpigotCore_Main/src/de/steamwar/sql/UserGroup.java deleted file mode 100644 index 617f6f8..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/UserGroup.java +++ /dev/null @@ -1,72 +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.sql; - -import java.util.Arrays; -import java.util.stream.Collectors; - -public enum UserGroup { - - Admin("§4", "§e", true, true, true), - Developer("§3", "§f", true, true, true), - Moderator("§c", "§f", true, true, true), - Supporter("§9", "§f", false, true, true), - Builder("§2", "§f", false, true, false), - YouTuber("§5", "§f", false, false, false), - Member("§7", "§7", false, false, false); - - private final String colorCode; - private final String chatColorCode; - private final boolean adminGroup; - private final boolean teamGroup; - private final boolean checkSchematics; - - UserGroup(String colorCode, String chatColorCode, boolean adminGroup, boolean teamGroup, boolean checkSchematics) { - this.colorCode = colorCode; - this.chatColorCode = chatColorCode; - this.adminGroup = adminGroup; - this.teamGroup = teamGroup; - this.checkSchematics = checkSchematics; - } - - public String getColorCode() { - return colorCode; - } - - public boolean isAdminGroup() { - return adminGroup; - } - - public boolean isTeamGroup() { - return teamGroup; - } - - public boolean isCheckSchematics() { - return checkSchematics; - } - - public String getChatColorCode() { - return chatColorCode; - } - - public static UserGroup getUsergroup(String name) { - return Arrays.stream(UserGroup.values()).filter(userGroup -> userGroup.name().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); - } -} \ No newline at end of file From 5b41b2112dbc7118cbc93189ef364ac2510a3cfb Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 20 Sep 2022 16:41:07 +0200 Subject: [PATCH 02/11] Full CommonDB untested --- CommonCore | 2 +- .../src/de/steamwar/core/Core.java | 2 + .../core/events/PlayerJoinedEvent.java | 7 +- .../src/de/steamwar/sql/CheckedSchematic.java | 75 --- .../src/de/steamwar/sql/NodeDownload.java | 48 -- .../src/de/steamwar/sql/Provider.java | 69 --- .../src/de/steamwar/sql/Punishment.java | 128 ----- .../src/de/steamwar/sql/SQLProvider.java | 397 ------------- .../src/de/steamwar/sql/SQLWrapperImpl.java | 16 + .../src/de/steamwar/sql/SWException.java | 47 -- .../src/de/steamwar/sql/SchematicData.java | 99 ++++ .../src/de/steamwar/sql/SchematicNode.java | 528 ------------------ .../src/de/steamwar/sql/Season.java | 54 -- .../de/steamwar/sql/StandaloneProvider.java | 294 ---------- SpigotCore_Main/src/de/steamwar/sql/Team.java | 65 --- .../src/de/steamwar/sql/TeamTeilnahme.java | 39 -- .../src/de/steamwar/sql/UserConfig.java | 54 -- 17 files changed, 124 insertions(+), 1800 deletions(-) delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Provider.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Punishment.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SWException.java create mode 100644 SpigotCore_Main/src/de/steamwar/sql/SchematicData.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Season.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Team.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/UserConfig.java diff --git a/CommonCore b/CommonCore index c1e175c..1758fc4 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit c1e175c3e84280c160ae5c7f84e44805f159bbf3 +Subproject commit 1758fc4297da23f6cae2e69115b510a6fb7d4aeb diff --git a/SpigotCore_Main/src/de/steamwar/core/Core.java b/SpigotCore_Main/src/de/steamwar/core/Core.java index 5c016a3..c1d7d30 100644 --- a/SpigotCore_Main/src/de/steamwar/core/Core.java +++ b/SpigotCore_Main/src/de/steamwar/core/Core.java @@ -31,6 +31,7 @@ import de.steamwar.core.events.PlayerJoinedEvent; import de.steamwar.core.events.WorldLoadEvent; import de.steamwar.message.Message; import de.steamwar.network.NetworkReceiver; +import de.steamwar.sql.SchematicNode; import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.internal.Statement; import org.bukkit.Bukkit; @@ -121,6 +122,7 @@ public class Core extends JavaPlugin{ new PartialChunkFixer(); Bukkit.getScheduler().runTaskTimer(Core.getInstance(), SteamwarUser::clear, 72000, 72000); + Bukkit.getScheduler().runTaskTimer(Core.getInstance(), SchematicNode::clear, 20L * 30, 20L * 30); if(Core.getVersion() >= 19) //new ServerDataHandler(); diff --git a/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java b/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java index 8b78106..aae2000 100644 --- a/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java +++ b/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java @@ -21,8 +21,10 @@ package de.steamwar.core.events; import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.UserGroup; +import de.steamwar.sql.internal.Statement; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; @@ -30,9 +32,12 @@ import org.bukkit.event.player.PlayerQuitEvent; public class PlayerJoinedEvent implements Listener{ - @EventHandler + @EventHandler(priority = EventPriority.LOWEST) private void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); + if(!Statement.productionDatabase()) { + SteamwarUser.createOrUpdateUsername(player.getUniqueId(), player.getName()); + } SteamwarUser user = SteamwarUser.get(player.getUniqueId()); if(user.getUserGroup() != UserGroup.Member) { diff --git a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java b/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java deleted file mode 100644 index de3c0e2..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java +++ /dev/null @@ -1,75 +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.sql; - -import de.steamwar.sql.internal.Field; -import de.steamwar.sql.internal.SelectStatement; -import de.steamwar.sql.internal.Table; -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.sql.Timestamp; -import java.util.List; - -@AllArgsConstructor -public class CheckedSchematic { - - private static final Table table = new Table<>(CheckedSchematic.class); - private static final SelectStatement statusOfNode = new SelectStatement<>(table, "SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); - - public static List getLastDeclinedOfNode(SchematicNode node){ - return getLastDeclinedOfNode(node.getId()); - } - - public static List getLastDeclinedOfNode(int node){ - return statusOfNode.listSelect(node); - } - - @Field(nullable = true) - private final Integer nodeId; - @Field - private final int nodeOwner; - @Field - private final String nodeName; - @Getter - @Field - private final int validator; - @Getter - @Field - private final Timestamp startTime; - @Getter - @Field - private final Timestamp endTime; - @Getter - @Field - private final String declineReason; - - public int getNode() { - return nodeId; - } - - public String getSchemName() { - return nodeName; - } - - public int getSchemOwner() { - return nodeOwner; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java b/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java deleted file mode 100644 index 2ffc7d9..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java +++ /dev/null @@ -1,48 +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.sql; - -import com.google.common.io.BaseEncoding; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; - -public class NodeDownload { - private NodeDownload() {} - - private static final String BASE = "https://steamwar.de/download.php?schem="; - - public static String getLink(SchematicNode schem){ - if(schem.isDir()) - throw new SecurityException("Can not Download Directorys"); - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException e) { - throw new SecurityException(e); - } - digest.reset(); - digest.update((Instant.now().toString() + schem.getOwner() + schem.getId()).getBytes()); - String hash = BaseEncoding.base16().encode(digest.digest()); - Provider.impl.createDownloadLink(schem.getId(), hash); - return BASE + hash; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Provider.java b/SpigotCore_Main/src/de/steamwar/sql/Provider.java deleted file mode 100644 index 0ece5ae..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Provider.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is a part of the SteamWar software. - * - * Copyright (C) 2022 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.sql; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface Provider { - Provider impl = new SQLProvider(); - - boolean hasEventTeam(int teamID, int eventID); - Set getEventTeams(int eventID); - Set getTeamEvents(int teamID); - - void createDownloadLink(int nodeId, String hash); - - Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type); - Map getPunishmentsOfPlayer(int user); - - void logException(String server, String message, String stacktrace); - - Team getTeam(int id); - List getTeamMembers(Team team); - - String getConfig(int player, String config); - void updatePlayerConfig(int id, String config, String value); - void removePlayerConfig(int id, String config); - - void createSchematicNode(int owner, String name, Integer parent, String type, String item); - SchematicNode getSchematicNode(int owner, String name, Integer parent); - List getSchematicNodeInNode(Integer parent); - List getSchematicDirectoryInNode(Integer parent); - SchematicNode getSchematicDirectory(String name, Integer parent); - SchematicNode getSchematicNode(String name, Integer parent); - SchematicNode getSchematicNode(int id); - List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent); - List getAllAccessibleSchematicsOfType(int user, String schemType); - List getAllSchematicsOfType(int owner, String schemType); - List getAllSchematicsOfType(String schemType); - List getSchematicsAccessibleByUser(int user, Integer parent); - List getAllSchematicsAccessibleByUser(int user); - List getAllParentsOfNode(int node); - Integer countNodes(); - void updateSchematicNode(SchematicNode node); - void deleteSchematicNode(SchematicNode node); - InputStream getSchematicData(SchematicNode node) throws IOException; - void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat); - int getSchematicElo(SchematicNode node, int season); -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Punishment.java b/SpigotCore_Main/src/de/steamwar/sql/Punishment.java deleted file mode 100644 index f97285c..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Punishment.java +++ /dev/null @@ -1,128 +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.sql; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.sql.Timestamp; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Map; -import java.util.function.Consumer; - -public class Punishment { - - - public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { - return Provider.impl.getPunishmentOfPlayer(user, type); - } - - public static Map getPunishmentsOfPlayer(int user) { - return Provider.impl.getPunishmentsOfPlayer(user); - } - - public static boolean isPunished(SteamwarUser user, Punishment.PunishmentType type, Consumer callback) { - Punishment punishment = Punishment.getPunishmentOfPlayer(user.getId(), type); - if(punishment == null || !punishment.isCurrent()) { - return false; - } else { - callback.accept(punishment); - return true; - } - } - - - private final int user; - private final int punisher; - private final PunishmentType type; - private final Timestamp startTime; - private final Timestamp endTime; - private final boolean perma; - private final String reason; - - public Punishment(int user, int punisher, PunishmentType type, Timestamp startTime, Timestamp endTime, boolean perma, String reason) { - this.user = user; - this.punisher = punisher; - this.type = type; - this.startTime = startTime; - this.endTime = endTime; - this.perma = perma; - this.reason = reason; - } - - public Timestamp getStartTime() { - return startTime; - } - - public Timestamp getEndTime() { - return endTime; - } - - public PunishmentType getType() { - return type; - } - - public int getUser() { - return user; - } - - public String getReason() { - return reason; - } - - public int getPunisher() { - return punisher; - } - - public boolean isPerma() { - return perma; - } - - public String getBantime(Timestamp endTime, boolean perma) { - if (perma) { - return "permanent"; - } 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(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; - private final String playerMessagePerma; - private final String playerMessageUntil; - private final String usageNotPunished; - private final String unpunishmentMessage; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java deleted file mode 100644 index d6e4165..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * This file is a part of the SteamWar software. - * - * Copyright (C) 2022 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.sql; - -import de.steamwar.sql.internal.Statement; - -import java.io.IOException; -import java.io.InputStream; -import java.sql.Blob; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; -import java.util.stream.Collectors; -import java.util.zip.GZIPInputStream; - -public class SQLProvider implements Provider { - - private static final de.steamwar.sql.internal.Statement hasEventTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); - @Override - public boolean hasEventTeam(int teamID, int eventID) { - return hasEventTeam.select(ResultSet::next, teamID, eventID); - } - - private static final de.steamwar.sql.internal.Statement eventTeams = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE EventID = ?"); - @Override - public Set getEventTeams(int eventID) { - return eventTeams.select(rs -> { - Set teams = new HashSet<>(); - while(rs.next()) - teams.add(Team.get(rs.getInt("TeamID"))); - return teams; - }, eventID); - } - - private static final de.steamwar.sql.internal.Statement eventsTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ?"); - @Override - public Set getTeamEvents(int teamID) { - return eventsTeam.select(rs -> { - Set events = new HashSet<>(); - while(rs.next()) - events.add(Event.get(rs.getInt("EventID"))); - return events; - }, teamID); - } - - private static final de.steamwar.sql.internal.Statement createLink = new de.steamwar.sql.internal.Statement("INSERT INTO NodeDownload (NodeId, Link) VALUES (?, ?) ON DUPLICATE KEY UPDATE Link = VALUES(Link)"); - @Override - public void createDownloadLink(int nodeId, String hash) { - createLink.update(nodeId, hash); - } - - private static final de.steamwar.sql.internal.Statement getPunishment = new de.steamwar.sql.internal.Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); - @Override - public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { - return getPunishment.select(rs -> { - if (rs.next()) - return newPunishment(rs); - return null; - }, user, type.name()); - } - - private Punishment newPunishment(ResultSet rs) throws SQLException { - return new Punishment(rs.getInt("UserId"), rs.getInt("Punisher"), Punishment.PunishmentType.valueOf(rs.getString("Type")), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getBoolean("Perma"), rs.getString("Reason")); - } - - private static final de.steamwar.sql.internal.Statement getPunishments = new de.steamwar.sql.internal.Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); - @Override - public Map getPunishmentsOfPlayer(int user) { - return getPunishments.select(rs -> { - Map punishments = new HashMap<>(); - while (rs.next()) - punishments.put(Punishment.PunishmentType.valueOf(rs.getString("Type")), newPunishment(rs)); - return punishments; - }, user); - } - - private static final de.steamwar.sql.internal.Statement insert = new de.steamwar.sql.internal.Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); - @Override - public void logException(String server, String message, String stacktrace) { - insert.update(server, message, stacktrace); - } - - private static final de.steamwar.sql.internal.Statement getTeam = new de.steamwar.sql.internal.Statement("SELECT * FROM Team WHERE TeamID = ?"); - @Override - public Team getTeam(int id) { - return getTeam.select(rs -> { - rs.next(); - return new Team(rs.getInt("TeamID"), rs.getString("TeamKuerzel"), rs.getString("TeamName"), rs.getString("TeamColor")); - }, id); - } - - private static final de.steamwar.sql.internal.Statement getTeamMembers = new de.steamwar.sql.internal.Statement("SELECT id FROM UserData WHERE Team = ?"); - @Override - public List getTeamMembers(Team team) { - return getTeamMembers.select(rs -> { - List members = new ArrayList<>(); - while(rs.next()) - members.add(rs.getInt("id")); - return members; - }, team.getTeamId()); - } - - private static final de.steamwar.sql.internal.Statement getConfig = new de.steamwar.sql.internal.Statement("SELECT Value FROM UserConfig WHERE User = ? AND Config = ?"); - @Override - public String getConfig(int player, String config) { - return getConfig.select(rs -> { - if(rs.next()) - return rs.getString("Value"); - return null; - }, player, config); - } - - private static final de.steamwar.sql.internal.Statement setConfig = new de.steamwar.sql.internal.Statement("INSERT INTO UserConfig (User, Config, Value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Value = VALUES(Value)"); - @Override - public void updatePlayerConfig(int id, String config, String value) { - setConfig.update(id, config, value); - } - - private static final de.steamwar.sql.internal.Statement deleteConfig = new de.steamwar.sql.internal.Statement("DELETE FROM UserConfig WHERE User = ? AND Config = ?"); - @Override - public void removePlayerConfig(int id, String config) { - deleteConfig.update(id, config); - } - - private static final String[] nodeSelect = {"NodeId", "NodeName", "NodeOwner", "ParentNode", "NodeType", "NodeItem", "NodeRank", "NodeFormat", "LastUpdate", "ReplaceColor", "AllowReplay"}; - private static String nodeSelectCreator(String itemPrefix) { - return "SELECT " + Arrays.stream(nodeSelect).map(s -> itemPrefix + s).collect(Collectors.joining(", ")) + " FROM SchematicNode "; - } - private static final de.steamwar.sql.internal.Statement createNode = new de.steamwar.sql.internal.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 de.steamwar.sql.internal.Statement getSchematicNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); - private static final de.steamwar.sql.internal.Statement getSchematicNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); - private static final de.steamwar.sql.internal.Statement getSchematicsInNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getSchematicsInNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getDirsInNode_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode is NULL AND NodeType is NULL ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getDirsInNode = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE ParentNode = ? AND NodeType is NULL ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getSchematicDirectory_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getSchematicDirectory = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getSchematicNodeO_Null = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode is NULL "); - private static final de.steamwar.sql.internal.Statement getSchematicNodeO = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getSchematicNodeId = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeId = ?"); - private static final de.steamwar.sql.internal.Statement getAllSchemsOfTypeOwner = new de.steamwar.sql.internal.Statement( nodeSelectCreator("") + "WHERE NodeOwner = ? AND NodeType = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getAllSchemsOfType = new de.steamwar.sql.internal.Statement(nodeSelectCreator("") + "WHERE NodeType = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getAccessibleByUser = new de.steamwar.sql.internal.Statement(nodeSelectCreator("s.") + "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 de.steamwar.sql.internal.Statement getAccessibleByUserByTypeInNode = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getAccessibleByUserByTypeInNode_Null = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? UNION " + nodeSelectCreator("SN.") + "AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getAccessibleByUserByType = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement getAllSchematicsAccessibleByUser = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN as (" + nodeSelectCreator("s.") + "s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId UNION " + nodeSelectCreator("SN.") + "AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement isSchematicAccessibleForUser = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN AS (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "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 de.steamwar.sql.internal.Statement getAllParentsOfNode = new de.steamwar.sql.internal.Statement("WITH RECURSIVE RSN AS (" + nodeSelectCreator("") + "WHERE NodeId = ? UNION " + nodeSelectCreator("SN.") + "SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); - private static final de.steamwar.sql.internal.Statement countNodes = new de.steamwar.sql.internal.Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); - private static final de.steamwar.sql.internal.Statement updateDB = new de.steamwar.sql.internal.Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ?, ReplaceColor = ?, AllowReplay = ? WHERE NodeId = ?"); - private static final de.steamwar.sql.internal.Statement updateDatabase = new de.steamwar.sql.internal.Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?"); - private static final de.steamwar.sql.internal.Statement selSchemData = new de.steamwar.sql.internal.Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?"); - private static final de.steamwar.sql.internal.Statement deleteNode = new de.steamwar.sql.internal.Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); - private static final de.steamwar.sql.internal.Statement schemElo = new de.steamwar.sql.internal.Statement("SELECT Elo FROM SchemElo WHERE SchemId = ? AND Season = ?"); - - private static final de.steamwar.sql.internal.Statement.ResultSetUser> toSchematicList = rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) { - nodes.add(nodeFromResultSet(rs)); - } - return nodes; - }; - private static final de.steamwar.sql.internal.Statement.ResultSetUser toSchematicNode = rs -> { - if (rs.next()) { - return nodeFromResultSet(rs); - } - return null; - }; - - private static SchematicNode nodeFromResultSet(ResultSet rs) throws SQLException { - Integer parent = rs.getInt("ParentNode"); - if(rs.wasNull()) { - parent = null; - } - String type = rs.getString("NodeType"); - return new SchematicNode( - rs.getInt("NodeId"), - rs.getInt("NodeOwner"), - rs.getString("NodeName"), - parent, - rs.getString("NodeItem"), - type, - type == null, - rs.getInt("NodeRank"), - rs.getTimestamp("LastUpdate"), - rs.getBoolean("NodeFormat"), - rs.getBoolean("ReplaceColor"), - rs.getBoolean("AllowReplay") - ); - } - - @Override - public void createSchematicNode(int owner, String name, Integer parent, String type, String item) { - createNode.update(name, owner, parent, type, item); - } - - @Override - public SchematicNode getSchematicNode(int owner, String name, Integer parent) { - - if(parent == null) { - return getSchematicNode_Null.select(toSchematicNode, owner, name); - } else { - return getSchematicNode.select(toSchematicNode, owner, name, parent); - } - } - - @Override - public List getSchematicNodeInNode(Integer parent) { - if(parent == null) { - return getSchematicsInNode_Null.select(toSchematicList); - }else { - return getSchematicsInNode.select(toSchematicList, parent); - } - } - - @Override - public List getSchematicDirectoryInNode(Integer parent) { - if(parent == null) { - return getDirsInNode_Null.select(toSchematicList); - }else { - return getDirsInNode.select(toSchematicList, parent); - } - } - - @Override - public SchematicNode getSchematicDirectory(String name, Integer parent) { - Statement.ResultSetUser user = rs -> { - while (rs.next()) { - SchematicNode node = nodeFromResultSet(rs); - if(node.isDir()) - return node; - } - return null; - }; - - if(parent == null) { - return getSchematicDirectory_Null.select(user, name); - }else { - return getSchematicDirectory.select(user, name, parent); - } - } - - @Override - public SchematicNode getSchematicNode(String name, Integer parent) { - if(parent == null) { - return getSchematicNodeO_Null.select(toSchematicNode, name); - }else { - return getSchematicNodeO.select(toSchematicNode, name, parent); - } - } - - @Override - public SchematicNode getSchematicNode(int id) { - return getSchematicNodeId.select(rs -> { - if (!rs.next()) - return null; - return nodeFromResultSet(rs); - }, id); - } - - @Override - public List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { - if(parent == null || parent == 0) { - return getAccessibleByUserByTypeInNode_Null.select(toSchematicList, owner, owner, schemType); - } else { - return getAccessibleByUserByTypeInNode.select(toSchematicList, owner, owner, schemType, parent); - } - } - - @Override - public List getAllAccessibleSchematicsOfType(int user, String schemType) { - return getAccessibleByUserByType.select(toSchematicList, user, user, schemType); - } - - @Override - public List getAllSchematicsOfType(int owner, String schemType) { - return getAllSchemsOfTypeOwner.select(toSchematicList, owner, schemType); - } - - @Override - public List getAllSchematicsOfType(String schemType) { - return getAllSchemsOfType.select(toSchematicList, schemType); - } - - @Override - public List getSchematicsAccessibleByUser(int user, Integer parent) { - if (parent != null && parent != 0) { - if(Boolean.TRUE.equals(isSchematicAccessibleForUser.select(rs -> { - rs.next(); - return rs.getInt("Accessible") > 0; - }, parent, user, user))) { - return getSchematicNodeInNode(parent); - } - } else { - return getAccessibleByUser.select(rs -> { - List nodes = new ArrayList<>(); - while(rs.next()) - nodes.add(nodeFromResultSet(rs)); - return nodes; - }, user, user, user, user); - } - return Collections.emptyList(); - } - - @Override - public List getAllSchematicsAccessibleByUser(int user) { - return getAllSchematicsAccessibleByUser.select(toSchematicList, user, user); - } - - @Override - public List getAllParentsOfNode(int node) { - return getAllParentsOfNode.select(toSchematicList, node); - } - - @Override - public Integer countNodes() { - return countNodes.select(rs -> { - if (rs.next()) { - return rs.getInt("count"); - } - return 0; - }); - } - - @Override - public void updateSchematicNode(SchematicNode node) { - updateDB.update( - node.getName(), - node.getOwner(), - node.getParent(), - node.getItem(), - node.getType(), - node.getRankUnsafe(), - node.replaceColor(), - node.allowReplay(), - node.getId() - ); - } - - @Override - public void deleteSchematicNode(SchematicNode node) { - deleteNode.update(node.getId()); - } - - @Override - public InputStream getSchematicData(SchematicNode node) throws IOException { - try { - return selSchemData.select(rs -> { - rs.next(); - Blob schemData = rs.getBlob("NodeData"); - if(schemData == null) { - throw new SecurityException("SchemData is null"); - } - try { - return new GZIPInputStream(schemData.getBinaryStream()); - } catch (IOException e) { - throw new SecurityException("SchemData is wrong", e); - } - }, node.getId()); - } catch (Exception e) { - throw new IOException(e); - } - } - - @Override - public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) { - updateDatabase.update(blob, newFormat, node.getId()); - } - - @Override - public int getSchematicElo(SchematicNode node, int season) { - return schemElo.select(rs -> { - if(rs.next()) { - return rs.getInt("Elo"); - } - return 0; - }, node.getId(), season); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java b/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java index 41bb20a..c6d833d 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLWrapperImpl.java @@ -20,7 +20,10 @@ package de.steamwar.sql; import de.steamwar.core.Core; +import org.bukkit.Bukkit; +import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; import java.io.File; import java.util.Arrays; @@ -60,4 +63,17 @@ public class SQLWrapperImpl implements SQLWrapper { } } } + + private static final String SERVER_VERSION = Bukkit.getServer().getVersion(); + + @Override + public void additionalExceptionMetadata(StringBuilder builder) { + builder.append("\nPlayers: "); + for(Player player : Bukkit.getOnlinePlayers()) + builder.append(player.getName()).append(" "); + builder.append("\nWorlds: "); + for(World world : Bukkit.getWorlds()) + builder.append(world.getName()).append(" "); + builder.append("\nServer: ").append(SERVER_VERSION); + } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SWException.java b/SpigotCore_Main/src/de/steamwar/sql/SWException.java deleted file mode 100644 index 0622a89..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SWException.java +++ /dev/null @@ -1,47 +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.sql; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import java.io.File; - -public class SWException { - private SWException(){} - - private static final String serverVersion = Bukkit.getServer().getVersion(); - private static final String cwd = System.getProperty("user.dir"); - private static final String server = new File(cwd).getName(); - - public static void log(String message, String stacktrace){ - StringBuilder msgBuilder = new StringBuilder(message).append("\nPlayers: "); - for(Player player : Bukkit.getOnlinePlayers()) - msgBuilder.append(player.getName()).append(" "); - msgBuilder.append("\nWorlds: "); - for(World world : Bukkit.getWorlds()) - msgBuilder.append(world.getName()).append(" "); - msgBuilder.append("\nServer: ").append(serverVersion); - msgBuilder.append("\nCWD: ").append(cwd); - - Provider.impl.logException(server, msgBuilder.toString(), stacktrace); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java new file mode 100644 index 0000000..bb80a77 --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java @@ -0,0 +1,99 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import de.steamwar.core.Core; +import de.steamwar.core.WorldEditWrapper; +import de.steamwar.sql.internal.Statement; +import org.bukkit.entity.Player; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Blob; +import java.util.zip.GZIPInputStream; + +public class SchematicData { + + public static Clipboard clipboardFromStream(InputStream is, boolean schemFormat) { + try { + return WorldEditWrapper.impl.getClipboard(is, schemFormat); + } catch (IOException e) { + throw new SecurityException("Could not read schem", e); + } + } + + 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 final SchematicNode node; + + public SchematicData(SchematicNode node) { + this.node = node; + if(node.isDir()) + throw new SecurityException("Node is Directory"); + } + + public InputStream schemData() throws IOException { + try { + return selSchemData.select(rs -> { + rs.next(); + Blob schemData = rs.getBlob("NodeData"); + if(schemData == null) { + throw new SecurityException("SchemData is null"); + } + try { + return new GZIPInputStream(schemData.getBinaryStream()); + } catch (IOException e) { + throw new SecurityException("SchemData is wrong", e); + } + }, node.getId()); + } catch (Exception e) { + throw new IOException(e); + } + } + + public Clipboard load() throws IOException, NoClipboardException { + return WorldEditWrapper.impl.getClipboard(schemData(), node.getSchemFormat()); + } + + public void loadToPlayer(Player player) throws IOException, NoClipboardException { + WorldEditWrapper.impl.setPlayerClipboard(player, schemData(), node.getSchemFormat()); + } + + public void saveFromPlayer(Player player) throws IOException, NoClipboardException { + saveFromPlayer(player, Core.getVersion() > 12); + } + + public void saveFromPlayer(Player player, boolean newFormat) throws IOException, NoClipboardException { + updateDatabase(WorldEditWrapper.impl.getPlayerClipboard(player, newFormat), newFormat); + } + + @Deprecated + public void saveFromBytes(byte[] bytes, boolean newFormat) { + updateDatabase(new ByteArrayInputStream(bytes), newFormat); + } + + private void updateDatabase(InputStream blob, boolean newFormat) { + updateDatabase.update(blob, newFormat, node.getId()); + node.setNodeFormat(newFormat); + } +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java deleted file mode 100644 index cadf8fd..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java +++ /dev/null @@ -1,528 +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.sql; - -import com.sk89q.worldedit.extent.clipboard.Clipboard; -import de.steamwar.core.Core; -import de.steamwar.core.WorldEditWrapper; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Predicate; - -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 != null && parent == 0) - parent = null; - Provider.impl.createSchematicNode(owner, name, parent, type, item); - return getSchematicNode(owner, name, parent); - } - - public static SchematicNode getSchematicNode(int owner, String name, SchematicNode parent) { - return getSchematicNode(owner, name, parent.getId()); - } - - public SchematicNode( - int id, - int owner, - String name, - Integer parent, - String item, - String type, - boolean isDir, - int rank, - Timestamp lastUpdate, - boolean schemFormat, - boolean replaceColor, - boolean allowReplay - ) { - this.id = id; - this.owner = owner; - this.name = name; - this.parent = parent; - this.item = item; - this.type = type; - this.lastUpdate = lastUpdate; - this.isDir = isDir; - if (!isDir) { - this.schemFormat = schemFormat; - this.rank = rank; - this.replaceColor = replaceColor; - this.allowReplay = allowReplay; - } - } - - 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 getSchematicNode(int owner, String name, Integer parent) { - if (parent != null && parent == 0) { - parent = null; - } - return Provider.impl.getSchematicNode(owner, name, parent); - } - - public static List getSchematicNodeInNode(Integer parent) { - if(parent != null && parent == 0) { - parent = null; - } - return Provider.impl.getSchematicNodeInNode(parent); - } - - public static List getSchematicDirectoryInNode(Integer parent) { - if(parent != null && parent == 0) { - parent = null; - } - return Provider.impl.getSchematicDirectoryInNode(parent); - } - - public static SchematicNode getSchematicDirectory(String name, Integer parent) { - if(parent != null && parent == 0) { - parent = null; - } - return Provider.impl.getSchematicDirectory(name, parent); - } - - public static SchematicNode getSchematicNode(String name, Integer parent) { - if(parent != null && parent == 0) { - parent = null; - } - return Provider.impl.getSchematicNode(name, parent); - } - - public static SchematicNode getSchematicNode(int id) { - return Provider.impl.getSchematicNode(id); - } - - public static List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { - return Provider.impl.getAccessibleSchematicsOfTypeInParent(owner, schemType, parent); - } - - public static List getAllAccessibleSchematicsOfType(int user, String schemType) { - return Provider.impl.getAllAccessibleSchematicsOfType(user, schemType); - } - - public static List getAllSchematicsOfType(int owner, String schemType) { - return Provider.impl.getAllSchematicsOfType(owner, schemType); - } - - @Deprecated - public static List getAllSchematicsOfType(String schemType) { - return Provider.impl.getAllSchematicsOfType(schemType); - } - - public static List getAllSchematicsOfType(SchematicType schemType) { - return Provider.impl.getAllSchematicsOfType(schemType.toDB()); - } - - 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) { - return Provider.impl.getSchematicsAccessibleByUser(user, parent); - } - - public static List getAllSchematicsAccessibleByUser(int user) { - return Provider.impl.getAllSchematicsAccessibleByUser(user); - } - - public static List getAllParentsOfNode(SchematicNode node) { - return getAllParentsOfNode(node.getId()); - } - - public static List getAllParentsOfNode(int node) { - return Provider.impl.getAllParentsOfNode(node); - } - - public static SchematicNode getNodeFromPath(SteamwarUser user, String s) { - if (s.startsWith("/")) { - s = s.substring(1); - } - if (s.isEmpty()) { - return null; - } - if (s.contains("/")) { - String[] layers = s.split("/"); - SchematicNode currentNode = null; - for (int i = 0; i < layers.length; i++) { - int finalI = i; - Optional node; - if (currentNode == null) { - node = SchematicNode.getSchematicsAccessibleByUser(user.getId(), 0).stream().filter(node1 -> node1.getName().equals(layers[finalI])).findAny(); - } else { - node = Optional.ofNullable(SchematicNode.getSchematicNode(layers[i], currentNode.getId())); - } - if (!node.isPresent()) { - return null; - } else { - currentNode = node.get(); - if (!currentNode.isDir() && i != layers.length - 1) { - return null; - } - } - } - return currentNode; - } else { - String finalS = s; - return SchematicNode.getSchematicsAccessibleByUser(user.getId(), 0).stream().filter(node1 -> node1.getName().equals(finalS)).findAny().orElse(null); - } - } - - private final int id; - private final int owner; - private String name; - private Integer parent; - private String item; - private String type; - private boolean replaceColor; - private boolean allowReplay; - private boolean schemFormat; - private int rank; - private Timestamp lastUpdate; - private final boolean isDir; - private Map brCache = new HashMap<>(); - - 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() { - return Provider.impl.countNodes(); - } - - 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 Integer getParent() { - return parent; - } - - public void setParent(Integer parent) { - this.parent = parent; - updateDB(); - } - - public String getItem() { - if (item.isEmpty()) { - return isDir ? "CHEST" : "CAULDRON_ITEM"; - } - return item; - } - - public void setItem(String item) { - this.item = item; - updateDB(); - } - - @Deprecated - public String getType() { - return type; - } - - @Deprecated - 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; - } - - @Deprecated - public int getRankUnsafe() { - 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 SecurityException("Is Directory"); - return SchematicType.fromDB(type); - } - - public void setSchemtype(SchematicType type) { - if(isDir()) - throw new SecurityException("Is Directory"); - this.type = type.toDB(); - updateDB(); - } - - public SchematicNode getParentNode() { - if(parent == null) return null; - return SchematicNode.getSchematicNode(parent); - } - - public boolean accessibleByUser(int user) { - return NodeMember.getNodeMember(id, user) != null; - } - - public Set getMembers() { - return NodeMember.getNodeMembers(id); - } - - public Timestamp getLastUpdate() { - return lastUpdate; - } - - public String generateBreadcrumbs(SteamwarUser user) { - return brCache.computeIfAbsent(user.getId(), integer -> generateBreadcrumbs("/", user)); - } - - public String generateBreadcrumbs(String split, SteamwarUser user) { - StringBuilder builder = new StringBuilder(getName()); - SchematicNode currentNode = this; - if (currentNode.isDir()) builder.append("/"); - final Set nodeMembers = NodeMember.getSchematics(user.getId()); - AtomicInteger i = new AtomicInteger(); - i.set(currentNode.getId()); - while (currentNode.getParentNode() != null && nodeMembers.stream().noneMatch(nodeMember -> nodeMember.getNode() == i.get())) { - currentNode = currentNode.getParentNode(); - i.set(currentNode.getId()); - builder.insert(0, split) - .insert(0, currentNode.getName()); - } - return builder.toString(); - } - - private void updateDB() { - Provider.impl.updateSchematicNode(this); - this.lastUpdate = Timestamp.from(Instant.now()); - this.brCache.clear(); - TAB_CACHE.clear(); - } - - public void delete() { - Provider.impl.deleteSchematicNode(this); - } - - public InputStream schemData() throws IOException { - return Provider.impl.getSchematicData(this); - } - - public Clipboard load() throws IOException, NoClipboardException { - if(isDir) - throw new SecurityException("Node is Directory"); - return WorldEditWrapper.impl.getClipboard(schemData(), schemFormat); - } - - public void loadToPlayer(Player player) throws IOException, NoClipboardException { - if(isDir) - throw new SecurityException("Node is Directory"); - WorldEditWrapper.impl.setPlayerClipboard(player, schemData(), schemFormat); - } - - public void saveFromPlayer(Player player) throws IOException, NoClipboardException { - if(isDir) - throw new SecurityException("Node is Directory"); - saveFromPlayer(player, Core.getVersion() > 12); - } - - public void saveFromBytes(byte[] bytes, boolean newFormat) { - if(isDir) - throw new SecurityException("Node is Directory"); - updateDatabase(new ByteArrayInputStream(bytes), newFormat); - } - - public void saveFromPlayer(Player player, boolean newFormat) throws IOException, NoClipboardException { - if(isDir) - throw new SecurityException("Node is Directory"); - updateDatabase(WorldEditWrapper.impl.getPlayerClipboard(player, newFormat), newFormat); - } - - private void updateDatabase(InputStream blob, boolean newFormat) { - Provider.impl.saveSchematicNode(this, blob, newFormat); - schemFormat = newFormat; - } - - public static Clipboard clipboardFromStream(InputStream is, boolean schemFormat) { - try { - return WorldEditWrapper.impl.getClipboard(is, schemFormat); - } catch (IOException e) { - throw new SecurityException("Could not read schem", e); - } - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SchematicNode)) - return false; - - SchematicNode node = (SchematicNode) obj; - return node.getId() == id; - } - - protected static final Map>> TAB_CACHE = new HashMap<>(); - - static { - Bukkit.getScheduler().runTaskTimer(Core.getInstance(), TAB_CACHE::clear, 20L * 30, 20L * 30); - } - - public static List getNodeTabcomplete(SteamwarUser user, String s) { - boolean sws = s.startsWith("/"); - if (sws) { - s = s.substring(1); - } - int index = s.lastIndexOf("/"); - String cacheKey = index == -1 ? "" : s.substring(0, index); - if(TAB_CACHE.containsKey(user.getId()) && TAB_CACHE.get(user.getId()).containsKey(cacheKey)) { - return new ArrayList<>(TAB_CACHE.get(user.getId()).get(cacheKey)); - } - List list = new ArrayList<>(); - if (s.contains("/")) { - String preTab = s.substring(0, s.lastIndexOf("/") + 1); - SchematicNode pa = SchematicNode.getNodeFromPath(user, preTab); - if (pa == null) return Collections.emptyList(); - List nodes = SchematicNode.getSchematicNodeInNode(pa); - nodes.forEach(node -> list.add((sws ? "/" : "") + node.generateBreadcrumbs(user))); - } else { - List nodes = SchematicNode.getSchematicsAccessibleByUser(user.getId(), 0); - nodes.forEach(node -> list.add((sws ? "/" : "") + node.getName() + (node.isDir() ? "/" : ""))); - } - list.remove("//copy"); - TAB_CACHE.computeIfAbsent(user.getId(), integer -> new HashMap<>()).putIfAbsent(cacheKey, list); - return list; - } - - private static final List FORBIDDEN_NAMES = Collections.unmodifiableList(Arrays.asList("public")); - public static boolean invalidSchemName(String[] layers) { - for (String layer : layers) { - if (layer.isEmpty()) { - return true; - } - if (layer.contains("/") || - layer.contains("\\") || - layer.contains("<") || - layer.contains(">") || - layer.contains("^") || - layer.contains("°") || - layer.contains("'") || - layer.contains("\"") || - layer.contains(" ")) { - return true; - } - if(FORBIDDEN_NAMES.contains(layer.toLowerCase())) { - return true; - } - } - return false; - } - - public boolean replaceColor() { - return replaceColor; - } - - public void setReplaceColor(boolean replaceColor) { - if(isDir()) - throw new SecurityException("Is Directory"); - this.replaceColor = replaceColor; - updateDB(); - } - - public boolean allowReplay() { - return allowReplay; - } - - public void setAllowReplay(boolean allowReplay) { - if(isDir()) - throw new SecurityException("Is Directory"); - this.allowReplay = allowReplay; - updateDB(); - } - - public int getElo(int season) { - return Provider.impl.getSchematicElo(this, season); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Season.java b/SpigotCore_Main/src/de/steamwar/sql/Season.java deleted file mode 100644 index 8768ad8..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Season.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.sql; - -import java.util.Calendar; - -public class Season { - private Season() {} - - public static int getSeason() { - Calendar calendar = Calendar.getInstance(); - int yearIndex = calendar.get(Calendar.MONTH) / 4; - return (calendar.get(Calendar.YEAR) * 3 + yearIndex); - } - - public static String getSeasonStart() { - Calendar calendar = Calendar.getInstance(); - return calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) / 4 * 3 + 1) + "-1"; - } - - public static String convertSeasonToString(int season){ - if (season == -1) return ""; - int yearSeason = season % 3; - int year = (season - yearSeason) / 3; - return String.format("%d-%d", year, yearSeason); - } - - public static int convertSeasonToNumber(String season){ - if (season.isEmpty()) return -1; - String[] split = season.split("-"); - try { - return Integer.parseInt(split[0]) * 3 + Integer.parseInt(split[1]); - } catch (NumberFormatException e) { - return -1; - } - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java deleted file mode 100644 index ade58d2..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * This file is a part of the SteamWar software. - * - * Copyright (C) 2022 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.sql; - -import de.steamwar.core.WorldEditWrapper; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.zip.GZIPInputStream; - -public class StandaloneProvider implements Provider { - public StandaloneProvider() { - nodesToPath.put(-1, schematicDir.toPath()); - } - - @Override - public boolean hasEventTeam(int teamID, int eventID) { - return false; - } - - @Override - public Set getEventTeams(int eventID) { - return Collections.emptySet(); - } - - @Override - public Set getTeamEvents(int teamID) { - return Collections.emptySet(); - } - - @Override - public void createDownloadLink(int nodeId, String hash) {} - - @Override - public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { - return null; - } - - @Override - public Map getPunishmentsOfPlayer(int user) { - return Collections.emptyMap(); - } - - @Override - public void logException(String server, String message, String stacktrace) {} - - @Override - public Team getTeam(int id) { - return new Team(0, "TEST", "TestAlliancePleaseIgnore", "c"); - } - - @Override - public List getTeamMembers(Team team) { - return Collections.emptyList(); - } - - private final Map> configs = new HashMap<>(); - @Override - public String getConfig(int player, String config) { - return configs.computeIfAbsent(player, player1 -> new HashMap<>()).get(config); - } - - @Override - public void updatePlayerConfig(int id, String config, String value) { - configs.computeIfAbsent(id, player -> new HashMap<>()).put(config, value); - } - - @Override - public void removePlayerConfig(int id, String config) { - configs.computeIfAbsent(id, player -> new HashMap<>()).remove(config); - } - - private int nodeId = 1; - private final File schematicDir = WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); - private final Map nodeById = new HashMap<>(); - private final Map> nodesByParent = new HashMap<>(); - private final Map nodesToPath = new HashMap<>(); - - private List mapDir(Integer id) { - try (Stream stream = Files.list(id==null?schematicDir.toPath():nodesToPath.get(id))) { - List list = stream.map(path -> { - File file = path.toFile(); - SchematicNode node = new SchematicNode( - nodeId++, - 0, - file.isDirectory()?file.getName():file.getName().substring(file.getName().lastIndexOf(".")), - null, - "", - "normal", - file.isDirectory(), - 0, - Timestamp.from(Instant.now()), - file.getName().endsWith(".schem"), - false, - false - ); - nodesToPath.put(node.getId(), path); - nodeById.put(node.getId(), node); - return node; - }).collect(Collectors.toList()); - nodesByParent.putIfAbsent(id == null?-1:id, list); - return list; - } catch (IOException e) { - throw new SecurityException(e); - } - } - - @Override - public void createSchematicNode(int owner, String name, Integer parent, String type, String item) { - boolean isDir = type == null; - Path p = null; - try { - if(isDir) { - p = Files.createDirectory(new File(nodesToPath.get(parent == null?-1:parent).toFile(), name).toPath()); - } else { - p = Files.createFile(new File(nodesToPath.get(parent == null?-1:parent).toFile(), name + ".schem").toPath()); - } - } catch (IOException e) { - throw new SecurityException(e); - } - - File file = p.toFile(); - int id = nodeId++; - nodesToPath.put(id, p); - SchematicNode node = new SchematicNode( - nodeId++, - 0, - file.isDirectory()?file.getName():file.getName().substring(file.getName().lastIndexOf(".")), - null, - "", - "normal", - file.isDirectory(), - 0, - Timestamp.from(Instant.now()), - file.getName().endsWith(".schem"), - true, - true - ); - nodeById.put(id, node); - nodesByParent.get(parent == null?-1:parent).add(node); - } - - @Override - public SchematicNode getSchematicNode(int owner, String name, Integer parent) { - return nodesByParent.get(parent).stream().filter(node -> node.getName().equals(name)).findAny().orElse(null); - } - - @Override - public List getSchematicNodeInNode(Integer parent) { - return nodesByParent.computeIfAbsent(parent==null?-1:parent, integer -> mapDir(parent)); - } - - @Override - public List getSchematicDirectoryInNode(Integer parent) { - return getSchematicNodeInNode(parent).stream().filter(SchematicNode::isDir).collect(Collectors.toList()); - } - - @Override - public SchematicNode getSchematicDirectory(String name, Integer parent) { - return getSchematicDirectoryInNode(parent).stream().filter(node -> node.getName().equals(name)).findFirst().orElse(null); - } - - @Override - public SchematicNode getSchematicNode(String name, Integer parent) { - return getSchematicNodeInNode(parent).stream().filter(node -> name.equals(node.getName())).findFirst().orElse(null); - } - - @Override - public SchematicNode getSchematicNode(int id) { - return nodeById.getOrDefault(id, null); - } - - @Override - public List getAccessibleSchematicsOfTypeInParent(int ignored, String schemType, Integer parent) { - return getSchematicDirectoryInNode(parent).stream().filter(node -> node.getType().equals(schemType)).collect(Collectors.toList()); - } - - @Override - public List getAllAccessibleSchematicsOfType(int ignored, String schemType) { - return getAllSchematicsAccessibleByUser(ignored).stream().filter(node -> schemType.equals(node.getType())).collect(Collectors.toList()); - } - - @Override - public List getAllSchematicsOfType(int ignored, String schemType) { - return getAllAccessibleSchematicsOfType(ignored, schemType); - } - - @Override - public List getAllSchematicsOfType(String schemType) { - return getAllAccessibleSchematicsOfType(-1, schemType); - } - - @Override - public List getSchematicsAccessibleByUser(int ignored, Integer parent) { - return getSchematicNodeInNode(parent); - } - - @Override - public List getAllSchematicsAccessibleByUser(int user) { - return nodesByParent.values().stream().reduce((schematicNodes, schematicNodes2) -> { - schematicNodes.addAll(schematicNodes2); - return schematicNodes; - }).orElse(new ArrayList<>()); - } - - @Override - public List getAllParentsOfNode(int node) { - List allSchematicsAccessibleByUser = getAllSchematicsAccessibleByUser(node); - allSchematicsAccessibleByUser.remove(getSchematicNode(node)); - return allSchematicsAccessibleByUser; - } - - @Override - public Integer countNodes() { - return nodesByParent.values().stream().map(List::size).reduce((Integer::sum)).orElse(0); - } - - @Override - public void updateSchematicNode(SchematicNode node) { - try { - Path newPath = new File(nodesToPath.get(node.getParent() == null?-1:node.getParent()).toFile(), node.getName() + (node.getSchemFormat()?".schem":".schematic")).toPath(); - Files.move(nodesToPath.get(node.getId()), newPath); - nodesToPath.put(node.getId(), newPath); - } catch (IOException e) { - throw new SecurityException(e); - } - } - - @Override - public void deleteSchematicNode(SchematicNode node) { - try { - Files.deleteIfExists(nodesToPath.get(node.getId())); - nodeById.remove(node.getId()); - nodesByParent.get(node.getParent() == null?-1:node.getId()).remove(node); - nodesToPath.remove(node.getId()); - } catch (IOException e) { - throw new SecurityException(e); - } - } - - @Override - public InputStream getSchematicData(SchematicNode node) throws IOException { - return new GZIPInputStream(Files.newInputStream(nodesToPath.get(node.getId()))); - } - - @Override - public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) { - try (FileOutputStream stream = new FileOutputStream(nodesToPath.get(node.getId()).toFile())) { - byte[] bucket = new byte[1024]; - int nReadBytes; - - while((nReadBytes = blob.read(bucket, 0, bucket.length)) !=-1){ - stream.write(bucket, 0, nReadBytes); - } - - if(newFormat != node.getSchemFormat()) { - nodesToPath.get(node.getId()).toFile().renameTo(new File(nodesToPath.get(node.getId()).toFile().getParentFile(), node.getName() + "." + (newFormat?".schem":"schematic"))); - } - } catch (IOException e) { - throw new SecurityException(e); - } - } - - @Override - public int getSchematicElo(SchematicNode node, int season) { - return 0; - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Team.java b/SpigotCore_Main/src/de/steamwar/sql/Team.java deleted file mode 100644 index a432ba8..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Team.java +++ /dev/null @@ -1,65 +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.sql; - -import java.util.List; - -public class Team { - - private final int teamId; - private final String teamKuerzel; - private final String teamName; - private final String teamColor; - - private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); - - public Team(int teamId, String teamKuerzel, String teamName, String teamColor) { - this.teamId = teamId; - this.teamKuerzel = teamKuerzel; - this.teamName = teamName; - this.teamColor = teamColor; - } - - public static Team get(int id){ - if(id == 0) - return pub; - return Provider.impl.getTeam(id); - } - - public int getTeamId() { - return teamId; - } - - public String getTeamKuerzel() { - return teamKuerzel; - } - - public String getTeamName() { - return teamName; - } - - public String getTeamColor() { - return teamColor; - } - - public List getMembers(){ - return Provider.impl.getTeamMembers(this); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java b/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java deleted file mode 100644 index d10320a..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java +++ /dev/null @@ -1,39 +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.sql; - -import java.util.Set; - -public class TeamTeilnahme { - private TeamTeilnahme(){} - - - public static boolean nimmtTeil(int teamID, int eventID){ - return Provider.impl.hasEventTeam(teamID, eventID); - } - - public static Set getTeams(int eventID){ - return Provider.impl.getEventTeams(eventID); - } - - public static Set getEvents(int teamID){ - return Provider.impl.getTeamEvents(teamID); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java b/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java deleted file mode 100644 index 8547b3b..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/UserConfig.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.sql; - -import java.util.UUID; - -public class UserConfig { - private UserConfig() {} - - public static String getConfig(UUID player, String config) { - return getConfig(SteamwarUser.get(player).getId(), config); - } - - public static String getConfig(int player, String config) { - return Provider.impl.getConfig(player, config); - } - - public static void updatePlayerConfig(UUID uuid, String config, String value) { - updatePlayerConfig(SteamwarUser.get(uuid).getId(), config, value); - } - - public static void updatePlayerConfig(int id, String config, String value) { - if (value == null) { - removePlayerConfig(id, config); - return; - } - Provider.impl.updatePlayerConfig(id, config, value); - } - - public static void removePlayerConfig(UUID uuid, String config) { - removePlayerConfig(SteamwarUser.get(uuid).getId(), config); - } - - public static void removePlayerConfig(int id, String config) { - Provider.impl.removePlayerConfig(id, config); - } -} From 6b59e06fea9cad2882a89982c2a38efd01f3a864 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 20 Sep 2022 16:42:03 +0200 Subject: [PATCH 03/11] Full CommonDB untested --- CommonCore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CommonCore b/CommonCore index 1758fc4..9043ab9 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit 1758fc4297da23f6cae2e69115b510a6fb7d4aeb +Subproject commit 9043ab9dc59bb08c238f050f05046f2bc983d03f From f4fcec5d1143cb5e80343ed3d2f21021407d6af9 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 24 Sep 2022 20:00:30 +0200 Subject: [PATCH 04/11] Update CommonCore --- CommonCore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CommonCore b/CommonCore index 9043ab9..c9b4dad 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit 9043ab9dc59bb08c238f050f05046f2bc983d03f +Subproject commit c9b4dad9b9a730eb70e1a843d78e03e5b0441c7c From e06b7e27f5839768e38f33411d78cefa0dcee46d Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 24 Sep 2022 20:03:40 +0200 Subject: [PATCH 05/11] Fix Message --- SpigotCore_Main/src/de/steamwar/message/Message.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SpigotCore_Main/src/de/steamwar/message/Message.java b/SpigotCore_Main/src/de/steamwar/message/Message.java index f78fa78..eca895f 100644 --- a/SpigotCore_Main/src/de/steamwar/message/Message.java +++ b/SpigotCore_Main/src/de/steamwar/message/Message.java @@ -82,7 +82,7 @@ public class Message { } private Locale getLocale(Player player){ - return SteamwarUser.get(player).getLocale(); + return SteamwarUser.get(player.getUniqueId()).getLocale(); } /* Send a message to one player */ From 64dc2089c3333a0eed10069521bedd7c58e44110 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 24 Sep 2022 20:20:57 +0200 Subject: [PATCH 06/11] Fix Build and missing SchematicData function --- SpigotCore_10/build.gradle | 2 +- SpigotCore_12/build.gradle | 2 +- SpigotCore_14/build.gradle | 4 ++-- SpigotCore_15/build.gradle | 2 +- SpigotCore_18/build.gradle | 6 +++--- SpigotCore_19/build.gradle | 4 ++-- SpigotCore_8/build.gradle | 4 ++-- SpigotCore_9/build.gradle | 2 +- SpigotCore_Main/build.gradle | 2 +- SpigotCore_Main/src/de/steamwar/sql/SchematicData.java | 6 +++--- 10 files changed, 17 insertions(+), 17 deletions(-) diff --git a/SpigotCore_10/build.gradle b/SpigotCore_10/build.gradle index 2157455..21565c9 100644 --- a/SpigotCore_10/build.gradle +++ b/SpigotCore_10/build.gradle @@ -43,7 +43,7 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") + compileOnly project(":SpigotCore_Main") compileOnly swdep("Spigot-1.10") } diff --git a/SpigotCore_12/build.gradle b/SpigotCore_12/build.gradle index 6b6e5df..571fa60 100644 --- a/SpigotCore_12/build.gradle +++ b/SpigotCore_12/build.gradle @@ -43,7 +43,7 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") + compileOnly project(":SpigotCore_Main") compileOnly swdep("Spigot-1.12") } diff --git a/SpigotCore_14/build.gradle b/SpigotCore_14/build.gradle index 8aa97f9..1effd11 100644 --- a/SpigotCore_14/build.gradle +++ b/SpigotCore_14/build.gradle @@ -43,8 +43,8 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") - implementation project(':CommonCore') + compileOnly project(":SpigotCore_Main") + compileOnly project(':CommonCore') compileOnly project(":SpigotCore_8") compileOnly project(":SpigotCore_9") diff --git a/SpigotCore_15/build.gradle b/SpigotCore_15/build.gradle index d5adbc4..5d6bf1e 100644 --- a/SpigotCore_15/build.gradle +++ b/SpigotCore_15/build.gradle @@ -43,7 +43,7 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") + compileOnly project(":SpigotCore_Main") compileOnly swdep("Spigot-1.15") } diff --git a/SpigotCore_18/build.gradle b/SpigotCore_18/build.gradle index f95ffc5..ea1260c 100644 --- a/SpigotCore_18/build.gradle +++ b/SpigotCore_18/build.gradle @@ -43,9 +43,9 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") - implementation project(":SpigotCore_14") - implementation project(':CommonCore') + compileOnly project(":SpigotCore_Main") + compileOnly project(":SpigotCore_14") + compileOnly project(':CommonCore') compileOnly swdep("WorldEdit-1.15") diff --git a/SpigotCore_19/build.gradle b/SpigotCore_19/build.gradle index 05103f3..6f8f9d6 100644 --- a/SpigotCore_19/build.gradle +++ b/SpigotCore_19/build.gradle @@ -43,8 +43,8 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") - implementation project(":SpigotCore_14") + compileOnly project(":SpigotCore_Main") + compileOnly project(":SpigotCore_14") compileOnly project(":SpigotCore_18") compileOnly swdep("WorldEdit-1.15") diff --git a/SpigotCore_8/build.gradle b/SpigotCore_8/build.gradle index 4a72bb4..58ea10e 100644 --- a/SpigotCore_8/build.gradle +++ b/SpigotCore_8/build.gradle @@ -43,8 +43,8 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") - implementation project(':CommonCore') + compileOnly project(":SpigotCore_Main") + compileOnly project(':CommonCore') compileOnly swdep("Spigot-1.8") compileOnly swdep("WorldEdit-1.12") diff --git a/SpigotCore_9/build.gradle b/SpigotCore_9/build.gradle index b3f804a..4585a01 100644 --- a/SpigotCore_9/build.gradle +++ b/SpigotCore_9/build.gradle @@ -43,7 +43,7 @@ sourceSets { } dependencies { - implementation project(":SpigotCore_Main") + compileOnly project(":SpigotCore_Main") compileOnly project(":SpigotCore_8") compileOnly swdep("Spigot-1.9") diff --git a/SpigotCore_Main/build.gradle b/SpigotCore_Main/build.gradle index 6cd4051..a8b5675 100644 --- a/SpigotCore_Main/build.gradle +++ b/SpigotCore_Main/build.gradle @@ -64,7 +64,7 @@ dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'org.hamcrest:hamcrest:2.2' - implementation project(':CommonCore') + compileOnly project(':CommonCore') } processResources { diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java index bb80a77..2c259ab 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java @@ -84,15 +84,15 @@ public class SchematicData { } public void saveFromPlayer(Player player, boolean newFormat) throws IOException, NoClipboardException { - updateDatabase(WorldEditWrapper.impl.getPlayerClipboard(player, newFormat), newFormat); + saveFromStream(WorldEditWrapper.impl.getPlayerClipboard(player, newFormat), newFormat); } @Deprecated public void saveFromBytes(byte[] bytes, boolean newFormat) { - updateDatabase(new ByteArrayInputStream(bytes), newFormat); + saveFromStream(new ByteArrayInputStream(bytes), newFormat); } - private void updateDatabase(InputStream blob, boolean newFormat) { + public void saveFromStream(InputStream blob, boolean newFormat) { updateDatabase.update(blob, newFormat, node.getId()); node.setNodeFormat(newFormat); } From 74823ba86f95d04449d63a358e39796a7f996f5c Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 29 Oct 2022 12:42:41 +0200 Subject: [PATCH 07/11] Fix merge issues --- .../src/de/steamwar/core/Core.java | 5 -- .../src/de/steamwar/core/CrashDetector.java | 4 +- .../src/de/steamwar/sql/Replay.java | 65 ------------------- .../src/de/steamwar/sql/SWException.java | 51 --------------- 4 files changed, 2 insertions(+), 123 deletions(-) delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/Replay.java delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/SWException.java diff --git a/SpigotCore_Main/src/de/steamwar/core/Core.java b/SpigotCore_Main/src/de/steamwar/core/Core.java index bbd8644..957605f 100644 --- a/SpigotCore_Main/src/de/steamwar/core/Core.java +++ b/SpigotCore_Main/src/de/steamwar/core/Core.java @@ -139,9 +139,4 @@ public class Core extends JavaPlugin{ if(crashDetector.onMainThread()) Statement.closeAll(); } - - private static void setSqlConfig() { - sqlConfig = new File(System.getProperty("user.home"), "MySQL.yml"); - standalone = !sqlConfig.exists(); - } } diff --git a/SpigotCore_Main/src/de/steamwar/core/CrashDetector.java b/SpigotCore_Main/src/de/steamwar/core/CrashDetector.java index b4f612e..a0bb826 100644 --- a/SpigotCore_Main/src/de/steamwar/core/CrashDetector.java +++ b/SpigotCore_Main/src/de/steamwar/core/CrashDetector.java @@ -20,7 +20,7 @@ package de.steamwar.core; import de.steamwar.sql.SWException; -import de.steamwar.sql.Statement; +import de.steamwar.sql.internal.Statement; import org.bukkit.Bukkit; import java.util.Arrays; @@ -64,7 +64,7 @@ public class CrashDetector { if(Core.getInstance().isEnabled()) { Core.getInstance().onDisable(); } - Statement.close(); + Statement.closeAll(); //System.exit(0); Does freeze, potential freezing issues: ConsoleRestoreHook, ApplicationShutdownHooks or DeleteOnExitHook Runtime.getRuntime().halt(0); } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Replay.java b/SpigotCore_Main/src/de/steamwar/sql/Replay.java deleted file mode 100644 index c3bc96f..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/Replay.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is a part of the SteamWar software. - * - * Copyright (C) 2022 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.sql; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.file.Files; -import java.sql.SQLException; - -@AllArgsConstructor -public class Replay { - - private static final Statement get = new Statement("SELECT Replay FROM Replay WHERE FightID = ?"); - private static final Statement insert = new Statement("INSERT INTO Replay (FightID, Replay) VALUES (?, ?)"); - - public static Replay get(int fightID) { - return get.select(rs -> { - rs.next(); - - File file; - try { - file = File.createTempFile("replay", "replay"); - file.deleteOnExit(); - Files.copy(rs.getBinaryStream("Replay"), file.toPath()); - } catch (IOException e) { - throw new SQLException(e); - } - return new Replay(fightID, file); - }, fightID); - } - - public static void save(int fightID, File file) { - try { - insert.update(fightID, new FileInputStream(file)); - } catch (FileNotFoundException e) { - throw new SecurityException("Could not save replay", e); - } - } - - private final int fightID; - @Getter - private final File replay; -} \ No newline at end of file diff --git a/SpigotCore_Main/src/de/steamwar/sql/SWException.java b/SpigotCore_Main/src/de/steamwar/sql/SWException.java deleted file mode 100644 index c370744..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/SWException.java +++ /dev/null @@ -1,51 +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.sql; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import java.io.File; - -public class SWException { - private SWException(){} - - private static final String serverVersion = Bukkit.getServer().getVersion(); - private static final String cwd = System.getProperty("user.dir"); - private static final String server = new File(cwd).getName(); - - public static void init() { - //force class loading - } - - public static void log(String message, String stacktrace){ - StringBuilder msgBuilder = new StringBuilder(message).append("\nPlayers: "); - for(Player player : Bukkit.getOnlinePlayers()) - msgBuilder.append(player.getName()).append(" "); - msgBuilder.append("\nWorlds: "); - for(World world : Bukkit.getWorlds()) - msgBuilder.append(world.getName()).append(" "); - msgBuilder.append("\nServer: ").append(serverVersion); - msgBuilder.append("\nCWD: ").append(cwd); - - Provider.impl.logException(server, msgBuilder.toString(), stacktrace); - } -} From 5c05a4a7db42577549bc5bf819e12dc12cf36612 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sat, 29 Oct 2022 13:19:36 +0200 Subject: [PATCH 08/11] Fixes --- CommonCore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CommonCore b/CommonCore index 3da8d04..92bea62 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit 3da8d04f3565cb99a417405284bca0efaaf9c5a3 +Subproject commit 92bea6255f6cae312674c7badffb7a8a44c4daee From 18525814d8b3b469d6e077ce6bd5e435704f10e7 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Wed, 2 Nov 2022 22:38:21 +0100 Subject: [PATCH 09/11] Current state --- CommonCore | 2 +- .../src/de/steamwar/core/events/PlayerJoinedEvent.java | 10 ++++++++++ SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/CommonCore b/CommonCore index 92bea62..bd626bb 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit 92bea6255f6cae312674c7badffb7a8a44c4daee +Subproject commit bd626bb4e6366f1e5e7e64765a6e47fefe05b16a diff --git a/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java b/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java index aae2000..4d0f776 100644 --- a/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java +++ b/SpigotCore_Main/src/de/steamwar/core/events/PlayerJoinedEvent.java @@ -27,8 +27,11 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerLocaleChangeEvent; import org.bukkit.event.player.PlayerQuitEvent; +import java.util.Locale; + public class PlayerJoinedEvent implements Listener{ @@ -48,6 +51,13 @@ public class PlayerJoinedEvent implements Listener{ event.setJoinMessage("§a§l» §r" + player.getDisplayName()); } + + @EventHandler + private void onLocale(PlayerLocaleChangeEvent event) { + if(!Statement.productionDatabase()) { + SteamwarUser.get(event.getPlayer().getUniqueId()).setLocale(Locale.forLanguageTag(event.getLocale()), false); + } + } @EventHandler private void onQuit(PlayerQuitEvent event) { diff --git a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java index 44fcff9..fcc5a09 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java +++ b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java @@ -131,7 +131,7 @@ public class PersonalKit { } public static PersonalKit getKitInUse(int userID, String gamemode) { - return getKitInUse.select(userID, gamemode); + return getKitInUse.select(userID, gamemode, true); } private static String saveInvConfig(String name, ItemStack[] inv) { From 37c01fece7ab44d8307e4e186315efa36a4c4e2d Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 15 Nov 2022 18:40:48 +0100 Subject: [PATCH 10/11] Current state --- CommonCore | 2 +- SpigotCore_Main/src/de/steamwar/sql/SchematicData.java | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CommonCore b/CommonCore index bd626bb..e9a39d0 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit bd626bb4e6366f1e5e7e64765a6e47fefe05b16a +Subproject commit e9a39d007d83a93e7dc50ab2706c9f16213bc900 diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java index 2c259ab..635aa6c 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SchematicData.java @@ -22,17 +22,24 @@ package de.steamwar.sql; import com.sk89q.worldedit.extent.clipboard.Clipboard; import de.steamwar.core.Core; import de.steamwar.core.WorldEditWrapper; +import de.steamwar.sql.internal.SqlTypeMapper; import de.steamwar.sql.internal.Statement; import org.bukkit.entity.Player; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.PipedInputStream; import java.sql.Blob; +import java.sql.PreparedStatement; import java.util.zip.GZIPInputStream; public class SchematicData { + static { + new SqlTypeMapper<>(PipedInputStream.class, "BLOB", (rs, identifier) -> { throw new SecurityException("PipedInputStream is write only datatype"); }, PreparedStatement::setBinaryStream); + } + public static Clipboard clipboardFromStream(InputStream is, boolean schemFormat) { try { return WorldEditWrapper.impl.getClipboard(is, schemFormat); From e8d4dd6319a094490c6e24034032705490b1195c Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 22 Nov 2022 11:34:57 +0100 Subject: [PATCH 11/11] Update to CommonCore master --- CommonCore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CommonCore b/CommonCore index e9a39d0..68bb3f3 160000 --- a/CommonCore +++ b/CommonCore @@ -1 +1 @@ -Subproject commit e9a39d007d83a93e7dc50ab2706c9f16213bc900 +Subproject commit 68bb3f3b8b54486153ab2a91d505bd802ec861ea