SteamWar/BungeeCore
Archiviert
13
2

Merge branch 'master' into replaying
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful

# Conflicts:
#	src/de/steamwar/bungeecore/BungeeCore.java
#	src/de/steamwar/bungeecore/SubserverSystem.java
#	src/de/steamwar/bungeecore/sql/Statement.java
Dieser Commit ist enthalten in:
Lixfel 2021-12-27 13:14:14 +01:00
Commit d6e01e6bae
61 geänderte Dateien mit 2435 neuen und 1349 gelöschten Zeilen

29
src/GDPRQueryREADME.md Normale Datei
Datei anzeigen

@ -0,0 +1,29 @@
# SteamWar GDPR report
## Copyright notice
The provided build worlds contain the world design of SteamWar contributors and is subject to their copyright.
The build worlds are therefore provided for personal use only.
## Categories of personal data processed
- IP address
- Minecraft account
- E-Mail address (if using a website account)
## Processing purposes of personal data and person-related data
- Provision of SteamWar user functionality (Minecraft account, IP address, BuildWorlds, BuildInventories, BuildMembers, Elo, IgnoredPlayers, SchematicMembers, SchematicChecksessions, Schematics, PersonalKits, UserData, UserConfigs)
- Manual analysis and punishment of player misbehaviour (BannedIPs, log files, Punishments)
- Statistical analysis (Sessions, Fights, SchematicChecksessions)
- Historical data storage (Fights)
- Technical error analysis (log files)
- Provision of the SteamWar website functionality (IP address, E-Mail address)
## Data Accessors
- SteamWar software
- SteamWar Administration
- SteamWar Development
- SteamWar Moderation (limited to Punishments and SchematicChecksessions)
## Storage duration
- Data for provision of functionality is stored until user triggered deletion
- Log file storage duration is targeted at one month, but might differ due to technical reasons
- Historical and statistical data deletion is not intended

Datei anzeigen

@ -20,9 +20,15 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SchematicType;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
public class ArenaMode { public class ArenaMode {
@ -32,9 +38,19 @@ public class ArenaMode {
private static final List<ArenaMode> allModes = new LinkedList<>(); private static final List<ArenaMode> allModes = new LinkedList<>();
private static final Random random = new Random(); private static final Random random = new Random();
static void init(Configuration config){ static {
for(String internalName : config.getKeys()){ File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem");
new ArenaMode(internalName, config.getSection(internalName));
for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) {
Configuration config;
try {
config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
} catch (IOException e) {
throw new SecurityException("Could not load SchematicTypes", e);
}
if(config.contains("Server"))
new ArenaMode(configFile.getName().replace(".yml", ""), config);
} }
} }
@ -84,19 +100,16 @@ public class ArenaMode {
private final String schemType; private final String schemType;
private ArenaMode(String internalName, Configuration config){ private ArenaMode(String internalName, Configuration config){
this.folder = config.getString("folder"); this.folder = config.getString("Server.Folder");
this.serverJar = config.getString("serverJar"); this.serverJar = config.getString("Server.ServerJar");
this.config = config.getString("config"); this.config = internalName + ".yml";
this.maps = config.getStringList("maps"); this.maps = config.getStringList("Server.Maps");
this.displayName = config.getString("displayName", internalName); this.displayName = config.getString("GameName", internalName);
if(config.contains("chatNames")) this.chatNames = config.getStringList("Server.ChatNames");
this.chatNames = config.getStringList("chatNames"); this.schemType = config.getString("Schematic.Type", "").toLowerCase();
else
this.chatNames = Collections.emptyList();
this.historic = config.getBoolean("historic", false);
this.schemType = config.getString("schemType", "").toLowerCase();
this.ranked = config.getBoolean("ranked", false); this.ranked = config.getBoolean("Server.Ranked", false);
this.historic = config.getBoolean("Server.Historic", false);
allModes.add(this); allModes.add(this);
byInternal.put(internalName, this); byInternal.put(internalName, this);

Datei anzeigen

@ -28,10 +28,10 @@ import de.steamwar.bungeecore.listeners.mods.Forge;
import de.steamwar.bungeecore.listeners.mods.LabyMod; import de.steamwar.bungeecore.listeners.mods.LabyMod;
import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker;
import de.steamwar.bungeecore.listeners.mods.WorldDownloader; import de.steamwar.bungeecore.listeners.mods.WorldDownloader;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.Statement;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import de.steamwar.bungeecore.sql.Team; import de.steamwar.bungeecore.sql.Team;
import net.dv8tion.jda.api.JDA;
import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
@ -71,6 +71,8 @@ public class BungeeCore extends Plugin {
public static final Map<String, String> serverPermissions = new HashMap<>(); public static final Map<String, String> serverPermissions = new HashMap<>();
public static final Map<String, String> commands = new HashMap<>(); public static final Map<String, String> commands = new HashMap<>();
private ErrorLogger errorLogger;
@Override @Override
public void onEnable(){ public void onEnable(){
getProxy().registerChannel("sw:bridge"); getProxy().registerChannel("sw:bridge");
@ -78,7 +80,7 @@ public class BungeeCore extends Plugin {
setInstance(this); setInstance(this);
loadConfig(); loadConfig();
new ErrorLogger(); errorLogger = new ErrorLogger();
new ConnectionListener(); new ConnectionListener();
new Forge(); new Forge();
new LabyMod(); new LabyMod();
@ -89,9 +91,10 @@ public class BungeeCore extends Plugin {
new WorldDownloader(); new WorldDownloader();
new BrandListener(); new BrandListener();
commands.put("/b", null); new Node.LocalNode();
commands.put("/gs", null); //new Node.RemoteNode("lx");
commands.put("/bau", null); //new Node.RemoteNode("az");
commands.put("/tp", null); commands.put("/tp", null);
commands.put("/bc", null); commands.put("/bc", null);
commands.put("/bauchat", null); commands.put("/bauchat", null);
@ -106,8 +109,6 @@ public class BungeeCore extends Plugin {
new JoinmeCommand(); new JoinmeCommand();
new TpCommand(); new TpCommand();
new HelpCommand(); new HelpCommand();
new BanCommand();
new UnbanCommand();
new DenyCommand("watchcat", "wc"); new DenyCommand("watchcat", "wc");
new TeamCommand(); new TeamCommand();
new ServerTeamchatCommand(); new ServerTeamchatCommand();
@ -116,7 +117,6 @@ public class BungeeCore extends Plugin {
new EventreloadCommand(); new EventreloadCommand();
new EventRescheduleCommand(); new EventRescheduleCommand();
new PollCommand(); new PollCommand();
new MuteCommand();
new BugCommand(); new BugCommand();
new WhoisCommand(); new WhoisCommand();
new RegelnCommand(); new RegelnCommand();
@ -129,6 +129,15 @@ public class BungeeCore extends Plugin {
new StatCommand(); new StatCommand();
new VerifyCommand(); new VerifyCommand();
new ReplayCommand(); new ReplayCommand();
new GDPRQuery();
// Punishment Commands:
new PunishmentCommand("ban", Punishment.PunishmentType.Ban);
new PunishmentCommand("mute", Punishment.PunishmentType.Mute);
new PunishmentCommand("noschemreceiving", Punishment.PunishmentType.NoSchemReceiving);
new PunishmentCommand("noschemsharing", Punishment.PunishmentType.NoSchemSharing);
new PunishmentCommand("noschemsubmitting", Punishment.PunishmentType.NoSchemSubmitting);
new PunishmentCommand("nodev", Punishment.PunishmentType.NoDevServer);
if(!EVENT_MODE){ if(!EVENT_MODE){
new BauCommand(); new BauCommand();
@ -154,19 +163,25 @@ public class BungeeCore extends Plugin {
Team.clearCache(); Team.clearCache();
}, 1, 1, TimeUnit.HOURS); }, 1, 1, TimeUnit.HOURS);
if (SteamwarDiscordBotConfig.loaded) {
try {
new SteamwarDiscordBot(); new SteamwarDiscordBot();
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Could not initialize discord bot", e);
}
}
} }
@Override @Override
public void onDisable(){ public void onDisable(){
ErrorLogger.stop();
Statement.closeAll();
try { try {
SteamwarDiscordBot.instance().getJda().shutdownNow(); SteamwarDiscordBot.instance().getJda().shutdown();
SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); } catch (Throwable e) {
} catch (Exception e) { getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e);
// Ignored
} }
errorLogger.unregister();
Statement.closeAll();
} }
public static BungeeCore get() { public static BungeeCore get() {
@ -256,8 +271,6 @@ public class BungeeCore extends Plugin {
EVENT_MODE = config.getBoolean("eventmode"); EVENT_MODE = config.getBoolean("eventmode");
Broadcaster.setBroadCastMsgs(config.getStringList("broadcasts").toArray(new String[1])); Broadcaster.setBroadCastMsgs(config.getStringList("broadcasts").toArray(new String[1]));
PollSystem.init(config.getString("poll.question"), config.getStringList("poll.answers")); PollSystem.init(config.getString("poll.question"), config.getStringList("poll.answers"));
CheckCommand.loadCheckQuestions(config.getSection("checkquestions"));
CheckCommand.loadRanks(config.getSection("checkranks"));
Persistent.setChatPrefix(CHAT_PREFIX); Persistent.setChatPrefix(CHAT_PREFIX);
Persistent.setLobbyServer(LOBBY_SERVER); Persistent.setLobbyServer(LOBBY_SERVER);
@ -267,8 +280,9 @@ public class BungeeCore extends Plugin {
config.getString("db.password") config.getString("db.password")
); );
ArenaMode.init(config.getSection("games")); if (config.getSection("discord") != null) {
SteamwarDiscordBotConfig.loadConfig(config.getSection("discord")); SteamwarDiscordBotConfig.loadConfig(config.getSection("discord"));
}
final Configuration servers = config.getSection("servers"); final Configuration servers = config.getSection("servers");
for(final String serverName : servers.getKeys()){ for(final String serverName : servers.getKeys()){

Datei anzeigen

@ -20,83 +20,55 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import de.steamwar.bungeecore.sql.SWException; import de.steamwar.bungeecore.sql.SWException;
import net.md_5.bungee.api.ProxyServer; import de.steamwar.bungeecore.sql.Statement;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.logging.Filter; import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class ErrorLogger extends Handler implements Filter { public class ErrorLogger extends Handler {
private static ErrorLogger instance;
private int ddosRate = 0; private int ddosRate = 0;
ErrorLogger(){ ErrorLogger(){
ProxyServer.getInstance().getLogger().addHandler(this); Logger.getLogger("").addHandler(this);
ProxyServer.getInstance().getLogger().setFilter(this);
instance = this;
} }
static void stop(){ void unregister(){
ProxyServer.getInstance().getLogger().removeHandler(instance); Logger.getLogger("").removeHandler(this);
} }
@Override @Override
public boolean isLoggable(LogRecord record) { public void publish(LogRecord logRecord) {
if(record.getLevel() != Level.SEVERE) if(logRecord.getLevel().intValue() < Level.WARNING.intValue())
return true; return;
StringBuilder stacktrace = new StringBuilder(record.getSourceClassName() + "\n" + record.getSourceMethodName()); String message = MessageFormat.format(logRecord.getMessage(), logRecord.getParameters());
Throwable thrown = record.getThrown(); for(String reason : ignoreContains)
while(thrown != null){ if(message.contains(reason))
stacktrace.append("\nCaused by ").append(thrown.getMessage()); return;
for(StackTraceElement ste : thrown.getStackTrace()) ByteArrayOutputStream stacktraceOutput = new ByteArrayOutputStream();
stacktrace.append("\n").append(ste.toString()); if(logRecord.getThrown() != null)
logRecord.getThrown().printStackTrace(new PrintStream(stacktraceOutput));
thrown = thrown.getCause(); String stacktrace = stacktraceOutput.toString();
} if(stacktrace.contains("Cannot request protocol")) {
if(++ddosRate % 1000 == 0) {
String stacktraceString = stacktrace.toString();
if(stacktraceString.contains("Cannot request protocol")){
ddosRate++;
if(ddosRate % 1000 == 0){
SWException.log("Bungee", "DDOS", ddosRate + ""); SWException.log("Bungee", "DDOS", ddosRate + "");
} }
return false;
}
return true;
}
@Override
public void publish(LogRecord record) {
if(record.getLevel() != Level.SEVERE && record.getLevel() != Level.WARNING)
return; return;
} else if (!Statement.connectionStable()) {
StringBuilder stacktrace = new StringBuilder(record.getSourceClassName() + "\n" + record.getSourceMethodName()); return;
Throwable thrown = record.getThrown();
while(thrown != null){
stacktrace.append("\nCaused by ").append(thrown.getMessage());
for(StackTraceElement ste : thrown.getStackTrace())
stacktrace.append("\n").append(ste.toString());
thrown = thrown.getCause();
} }
String stacktraceString = stacktrace.toString();
String message = MessageFormat.format(record.getMessage(), record.getParameters());
if(message.contains("ServerConnector") SWException.log("Bungee", message, stacktrace);
|| message.contains("InitialHandler")
|| message.contains("UpstreamBridge")
|| message.contains("DownstreamBridge")
|| message.contains(" took ")
|| message.contains("No client connected for pending server!"))
return;
SWException.log("Bungee", message, stacktraceString);
} }
@Override @Override
@ -108,4 +80,17 @@ public class ErrorLogger extends Handler implements Filter {
public void close() { public void close() {
//ignored //ignored
} }
private static final List<String> ignoreContains;
static {
List<String> contains = new ArrayList<>();
contains.add("ServerConnector");
contains.add("InitialHandler");
contains.add("UpstreamBridge");
contains.add("DownstreamBridge");
contains.add(" took ");
contains.add("No client connected for pending server!");
ignoreContains = Collections.unmodifiableList(contains);
}
} }

Datei anzeigen

@ -1,96 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore;
import java.io.*;
public class LoadEvaluation {
private LoadEvaluation(){}
private static final File meminfo = new File("/proc/meminfo");
public static double getRamPercentage() {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(meminfo)))) {
String memTotal = bufferedReader.readLine().replaceAll(" +", " ");
bufferedReader.readLine();
String memAvailable = bufferedReader.readLine().replaceAll(" +", " ");
long memTotalLong = getNumber(memTotal);
long memAvailableLong = getNumber(memAvailable);
return (memTotalLong - memAvailableLong) / (double) memTotalLong;
} catch (IOException e) {
return 1D;
}
}
public static double getRemoteRamPercentage(String remote) {
try {
// Attention:
// memInfo.sh needs to contain: cat /proc/meminfo
Process process = new ProcessBuilder("ssh", remote, "\"./memInfo.sh\"").start();
process.waitFor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String memTotal = bufferedReader.readLine().replaceAll(" +", " ");
bufferedReader.readLine();
String memAvailable = bufferedReader.readLine().replaceAll(" +", " ");
long memTotalLong = getNumber(memTotal);
long memAvailableLong = getNumber(memAvailable);
return (memTotalLong - memAvailableLong) / (double) memTotalLong;
} catch (IOException e) {
return 1D;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return 1D;
}
}
public static double getCPULoad() {
try {
Process process = new ProcessBuilder("bash", "-c", "cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS=\"\" '{printf \"%.2f\\n\", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'").start();
process.waitFor();
return Double.parseDouble(new BufferedReader(new InputStreamReader(process.getInputStream())).readLine()) / 100.0;
} catch (IOException e) {
return 1D;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return 1D;
}
}
public static double getRemoteCPULoad(String remote) {
try {
// Attention:
// cpuLoad.sh needs to contain: cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%.2f\n", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'
Process process = new ProcessBuilder("ssh", remote, "\"./cpuLoad.sh\"").start();
process.waitFor();
return Double.parseDouble(new BufferedReader(new InputStreamReader(process.getInputStream())).readLine()) / 100.0;
} catch (IOException e) {
return 1D;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return 1D;
}
}
private static long getNumber(String s) {
return Long.parseLong(s.split(" ")[1]);
}
}

Datei anzeigen

@ -0,0 +1,254 @@
/*
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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore;
import net.md_5.bungee.api.ProxyServer;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
public abstract class Node {
private static final List<String> OPENJ9_ARGS = Arrays.asList("-Xgc:excessiveGCratio=80", "-Xsyslog:none", "-Xtrace:none", "-Xdisableexplicitgc", "-XX:+AlwaysPreTouch", "-XX:+CompactStrings", "-XX:-HeapDumpOnOutOfMemory", "-XX:+ExitOnOutOfMemoryError", "-Dlog4j.configurationFile=log4j2.xml");
private static final double MIN_FREE_MEM = 4.0 * 1024 * 1024; // 4 GiB
private static final List<Node> nodes = new ArrayList<>();
public static Node local = null;
public static Node getNode() {
Node node = local;
double minLoad = local.getLoad();
if(minLoad < 0.5)
return local;
synchronized (nodes) {
Iterator<Node> it = nodes.iterator();
while(it.hasNext()) {
Node n = it.next();
double load = n.getLoad();
if (load < minLoad) {
minLoad = load;
node = n;
} else if (load == Double.POSITIVE_INFINITY) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Removing " + n.getName() + " due to infinite load!");
it.remove();
}
}
}
return node;
}
public static void forEach(Consumer<Node> consumer) {
consumer.accept(local);
synchronized (nodes) {
nodes.forEach(consumer);
}
}
public abstract ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams);
public abstract void execute(String... command);
public abstract String getName();
public abstract double getLoad();
protected void constructServerstart(File directory, List<String> cmd, String serverJar, String worldDir, String levelName, int port, String xmx, String... dParams) {
cmd.add("java");
for(String param : dParams){
cmd.add("-D" + param);
}
cmd.add("-Xmx" + xmx);
cmd.add("-Xshareclasses:nonfatal,name=" + directory.getName());
cmd.addAll(OPENJ9_ARGS);
cmd.add("-jar");
cmd.add("/binarys/" + serverJar);
cmd.add("--log-strip-color");
cmd.add("--world-dir");
cmd.add(worldDir);
cmd.add("--level-name");
cmd.add(levelName);
cmd.add("--port");
cmd.add(String.valueOf(port));
cmd.add("nogui");
}
protected void execute(ProcessBuilder builder) {
try {
builder.start().waitFor();
} catch (IOException e) {
throw new SecurityException("Could not execute command", e);
} catch (InterruptedException e) {
ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted during execution", e);
Thread.currentThread().interrupt();
}
}
public static class LocalNode extends Node {
private static final File meminfo = new File("/proc/meminfo");
private static final File loadavg = new File("/proc/loadavg");
private final int cores;
public LocalNode() {
this.cores = Runtime.getRuntime().availableProcessors();
local = this;
}
@Override
public ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams) {
List<String> cmd = new ArrayList<>();
constructServerstart(directory, cmd, serverJar, worldDir, levelName, port, xmx, dParams);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(directory);
return builder;
}
@Override
public void execute(String... command) {
execute(new ProcessBuilder(command));
}
@Override
public String getName() {
return "local";
}
@Override
public double getLoad() {
double totalMem;
double freeMem;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(meminfo)))) {
totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]);
bufferedReader.readLine();
freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]);
} catch (IOException e) {
throw new SecurityException("Could not read local memory", e);
}
double cpuLoad;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(loadavg)))) {
cpuLoad = Double.parseDouble(bufferedReader.readLine().split(" ")[0]);
} catch (IOException e) {
throw new SecurityException("Could not read local cpu", e);
}
return cpuLoad / cores + (freeMem > MIN_FREE_MEM ? 0 : ((totalMem - freeMem) / totalMem));
}
}
public static class RemoteNode extends Node {
private final int cores;
private final String remote;
public RemoteNode(String remote) {
this.remote = remote;
//Determine core count
Process process;
try {
process = new ProcessBuilder("ssh", remote, "nproc").start();
if(!process.waitFor(5, TimeUnit.SECONDS))
throw new IOException("Timeout of " + remote + " on init");
} catch (IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not initialize " + remote);
cores = 1;
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
cores = 1;
return;
}
int c;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
c = Integer.parseInt(bufferedReader.readLine());
} catch (IOException | NumberFormatException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read cores of" + remote, e);
c = 1;
}
cores = c;
BungeeCore.get().getLogger().log(Level.INFO, "Adding node " + remote + " with " + cores + " cores.");
synchronized (nodes) {
nodes.add(this);
}
}
@Override
public ProcessBuilder startServer(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams) {
List<String> cmd = new ArrayList<>();
cmd.add("ssh");
cmd.add("-L");
cmd.add(port + ":localhost:" + port);
cmd.add(remote);
cmd.add("cd");
cmd.add(directory.getPath());
cmd.add(";");
constructServerstart(directory, cmd, serverJar, worldDir, levelName, port, xmx, dParams);
return new ProcessBuilder(cmd);
}
@Override
public void execute(String... command) {
List<String> cmd = new ArrayList<>();
cmd.add("ssh");
cmd.add(remote);
cmd.addAll(Arrays.asList(command));
execute(new ProcessBuilder(cmd));
}
@Override
public String getName() {
return remote;
}
@Override
public double getLoad() {
Process process;
try {
process = new ProcessBuilder("ssh", remote, "cat /proc/loadavg;cat /proc/meminfo").start();
if(!process.waitFor(1, TimeUnit.SECONDS))
return Double.POSITIVE_INFINITY;
} catch (IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could starting process to read load", e);
return Double.POSITIVE_INFINITY;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Double.POSITIVE_INFINITY;
}
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
double cpuLoad = Double.parseDouble(bufferedReader.readLine().split(" ")[0]);
double totalMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]);
bufferedReader.readLine();
double freeMem = Double.parseDouble(bufferedReader.readLine().replaceAll(" +", " ").split(" ")[1]);
return cpuLoad / cores + (freeMem > MIN_FREE_MEM ? 0 : ((totalMem - freeMem) / totalMem));
} catch (IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could read load", e);
return Double.POSITIVE_INFINITY;
}
}
}
}

Datei anzeigen

@ -27,30 +27,23 @@ import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.Set;
import java.util.logging.Level; import java.util.UUID;
import java.util.stream.Collectors;
public class SubserverSystem { public class SubserverSystem {
private SubserverSystem(){} private SubserverSystem(){}
private static final String BACKBONE = "/home/minecraft/backbone/"; private static final String BACKBONE = "/home/minecraft/";
private static final List<String> JVM_ARGS = Arrays.asList("-Dlog4j.configurationFile=log4j2.xml", "-server", "-Xms128M", "-XX:+UseCompressedOops", "-XX:+TieredCompilation", "-XX:TargetSurvivorRatio=90", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=15", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseBiasedLocking", "-XX:UseSSE=3", "-XX:+UseCodeCacheFlushing", "-XX:+UseThreadPriorities", "-XX:+AggressiveOpts", "-XX:+ReduceSignalUsage", "-XX:+UseInterpreter", "-XX:+UseSharedSpaces", "-XX:AllocatePrefetchStyle=1", "-XX:+AlwaysCompileLoopMethods", "-XX:+UseConcMarkSweepGC", "-XX:+RewriteFrequentPairs", "-XX:+OptimizeStringConcat", "-XX:+CMSCleanOnEnter", "-XX:+UseInlineCaches");
private static final List<String> JVM8_ARGS = Arrays.asList("-XX:ThreadPriorityPolicy=42", "-XX:SharedReadOnlySize=30m", "-XX:+UseFastEmptyMethods", "-XX:+UseFastAccessorMethods");
private static final String ARENA_PATH = BACKBONE + "arenaserver/"; private static final String ARENA_PATH = BACKBONE + "arenaserver/";
private static final String SERVER_PATH = BACKBONE + "server/"; private static final String SERVER_PATH = BACKBONE + "server/";
private static final String EVENT_PATH = BACKBONE + "event/"; private static final String EVENT_PATH = BACKBONE + "event/";
private static final int FIRST_ARENA_PORT; private static final boolean MAIN_SERVER = ProxyServer.getInstance().getConfig().getListeners().stream().anyMatch(info -> ((InetSocketAddress) info.getSocketAddress()).getPort() == 25565);
private static final Portrange bauPorts = MAIN_SERVER ? new Portrange(10100, 20000) : new Portrange(2100, 2200);
static { private static final Portrange arenaPorts = MAIN_SERVER ? new Portrange(3000, 3100) : (BungeeCore.EVENT_MODE ? new Portrange(4000, 5000) : bauPorts);
if(BungeeCore.EVENT_MODE)
FIRST_ARENA_PORT = 6000;
else
FIRST_ARENA_PORT = 2500;
}
/** /**
* This function starts every arena (even test- and eventarenas). * This function starts every arena (even test- and eventarenas).
@ -92,17 +85,20 @@ public class SubserverSystem {
*/ */
public static synchronized Subserver startArena(ArenaMode modus, String map, int eventFightID, int checkSchemID, int prepareSchemID, int replayID, String serverName, String mapName, UUID player1, UUID player2, boolean ranked){ public static synchronized Subserver startArena(ArenaMode modus, String map, int eventFightID, int checkSchemID, int prepareSchemID, int replayID, String serverName, String mapName, UUID player1, UUID player2, boolean ranked){
//Generate missing parameters //Generate missing parameters
int port = freePort(FIRST_ARENA_PORT); Node node = eventFightID > 0 ? Node.local : Node.getNode();
int port = arenaPorts.freePort();
if(serverName == null){ if(serverName == null){
if(ranked) if(ranked)
serverName = "Ranked" + (port - FIRST_ARENA_PORT); serverName = "Ranked" + (port - arenaPorts.start);
else else
serverName = modus.getDisplayName() + (port - FIRST_ARENA_PORT); serverName = modus.getDisplayName() + (port - arenaPorts.start);
} }
if(mapName == null) if(mapName == null)
mapName = serverName; mapName = serverName;
mapName = mapName.replace(' ', '_').replace("[", "").replace("]", "");
String worldDir; String worldDir;
if(eventFightID > 0) if(eventFightID > 0)
worldDir = EVENT_PATH; worldDir = EVENT_PATH;
@ -110,57 +106,32 @@ public class SubserverSystem {
worldDir = ARENA_PATH; worldDir = ARENA_PATH;
//Copy world //Copy world
try { node.execute("cp", "-r", SERVER_PATH + modus.getFolder() + "/arenas/" + map, worldDir + mapName);
new ProcessBuilder("cp", "-r", SERVER_PATH + modus.getFolder() + "/arenas/" + map, worldDir + mapName).start().waitFor();
} catch (IOException e) {
throw new SecurityException("Could not copy folder", e);
} catch (InterruptedException e) {
ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted while copying folder", e);
Thread.currentThread().interrupt();
}
File directory = new File(SERVER_PATH, modus.getFolder()); File directory = new File(SERVER_PATH, modus.getFolder());
List<String> cmd = serverStartCommand( ProcessBuilder builder = node.startServer(
modus.serverJar(), modus.serverJar(), directory, worldDir, mapName, port, "768M",
directory, "logPath=" + mapName, "config=" + modus.getConfig(),
worldDir, "fightID=" + eventFightID, "ranked=" + ranked,
mapName, "checkSchemID=" + checkSchemID, "prepareSchemID=" + prepareSchemID,
port,
"2G",
"logPath=" + mapName,
"config="+modus.getConfig(),
"fightID=" + eventFightID,
"ranked=" + ranked,
"checkSchemID=" + checkSchemID,
"prepareSchemID=" + prepareSchemID,
"replay=" + replayID, "replay=" + replayID,
player1 != null && eventFightID != -1 ? "blueLeader=" + player1 : null, player1 != null && eventFightID != -1 ? "blueLeader=" + player1 : null,
player2 != null ? "redLeader=" + player2 : null); player2 != null ? "redLeader=" + player2 : null
);
//Start server
ProcessBuilder process = new ProcessBuilder(cmd);
process.directory(directory);
String finalMapName = mapName; String finalMapName = mapName;
if(eventFightID == -1) if(eventFightID == -1)
return new Bauserver(serverName, player1, port, process, () -> deleteFolder(ARENA_PATH + finalMapName)); return new Bauserver(serverName, player1, port, builder, () -> deleteFolder(node, ARENA_PATH + finalMapName));
else else
return new Subserver(Servertype.ARENA, serverName, port, process, () -> { return new Subserver(Servertype.ARENA, serverName, port, builder, () -> {
if(eventFightID > 0) if(eventFightID > 0)
return; return;
deleteFolder(ARENA_PATH + finalMapName); deleteFolder(node, ARENA_PATH + finalMapName);
}); });
} }
public static void deleteFolder(String worldName){ public static void deleteFolder(Node node, String worldName){
try { node.execute("rm", "-r", worldName);
new ProcessBuilder("rm", "-r", worldName).start().waitFor();
} catch (IOException e) {
throw new SecurityException("Could not clean up folder", e);
} catch (InterruptedException e) {
ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted while deleting folder", e);
Thread.currentThread().interrupt();
}
} }
public static Subserver startEventArena(EventFight eventFight, String serverName){ public static Subserver startEventArena(EventFight eventFight, String serverName){
@ -171,7 +142,7 @@ public class SubserverSystem {
0, 0,
0, 0,
0, serverName, 0, serverName,
serverName.replace(' ', '_') + eventFight.getStartTime().toLocalDateTime().format(DateTimeFormatter.ISO_TIME), serverName + eventFight.getStartTime().toLocalDateTime().format(DateTimeFormatter.ISO_TIME),
null, null,
null, null,
false); false);
@ -185,42 +156,24 @@ public class SubserverSystem {
if(bauRunning(p, owner)) if(bauRunning(p, owner))
return; return;
copyBauweltIfRequired(prototype, worldFolder + worldName);
SteamwarUser user = SteamwarUser.get(owner); SteamwarUser user = SteamwarUser.get(owner);
copyBauweltIfRequired(p, prototype, worldFolder + worldName);
int port = freePort(4000);
File directory = new File(SERVER_PATH, serverName); File directory = new File(SERVER_PATH, serverName);
List<String> cmd = serverStartCommand( Node node = Node.getNode();
serverJar, int port = bauPorts.freePort();
directory,
worldDir,
worldName,
port,
xmx,
"logPath=" + worldName);
//Start server new Bauserver(user.getUserName() + "s Bau", owner, port, node.startServer(
ProcessBuilder process = new ProcessBuilder(cmd); serverJar, directory, worldDir, worldName, port, xmx, "logPath=" + worldName
process.directory(directory); ), () -> {}).sendPlayer(p);
new Bauserver(user.getUserName() + "s Bau", owner, port, process, () -> {}).sendPlayer(p);
} }
public static void sendToBauServer(ProxiedPlayer p, UUID owner){ public static void sendToBauServer(ProxiedPlayer p, UUID owner){
sendToBau(p, owner, BungeeCore.BAUWELT_PROTOTYP, BungeeCore.WORLD_FOLDER, "spigot-1.12.2.jar", "/home/minecraft/userworlds", owner.toString(), "256M", "UserBau"); sendToBau(p, owner, BungeeCore.BAUWELT_PROTOTYP, BungeeCore.WORLD_FOLDER, "spigot-1.12.2.jar", "/home/minecraft/userworlds", owner.toString(), "256M", "UserBau");
} }
private static void sendToBau15(ProxiedPlayer p, UUID owner, String serverJar){
SteamwarUser user = SteamwarUser.get(owner);
sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, serverJar, "/home/minecraft/userworlds15", String.valueOf(user.getId()), "512M", "Bau15");
}
public static void sendToBau15(ProxiedPlayer p, UUID owner){ public static void sendToBau15(ProxiedPlayer p, UUID owner){
sendToBau15(p, owner, "spigot-1.15.2.jar"); SteamwarUser user = SteamwarUser.get(owner);
} sendToBau(p, owner, BungeeCore.BAUWELT15, BungeeCore.USERWORLDS15, "spigot-1.15.2.jar", "/home/minecraft/userworlds15", String.valueOf(user.getId()), "768M", "Bau15");
public static void sendToBau15paper(ProxiedPlayer p, UUID owner){
sendToBau15(p, owner, "paper-1.15.2.jar");
} }
public static void sendDeniedMessage(ProxiedPlayer p, UUID owner){ public static void sendDeniedMessage(ProxiedPlayer p, UUID owner){
@ -237,63 +190,6 @@ public class SubserverSystem {
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.getName())); new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.getName()));
} }
private static List<String> serverStartCommand(String serverJar, File directory, String worldDir, String levelName, int port, String xmx, String... dParams){
List<String> cmd = new ArrayList<>();
boolean jdk11 = serverJar.contains("1.15.2");
boolean fallback = false;
if (!steamwarStartAvailable()) {
cmd.add("ssh");
cmd.add("-L");
cmd.add(port + ":localhost:" + port);
if (remoteStartAvailable("lx")) {
cmd.add("lx");
} else if (remoteStartAvailable("az")) {
cmd.add("az");
} else {
fallback = true;
}
cmd.add("cd");
cmd.add(directory.getPath());
cmd.add(";");
}
if (fallback) {
cmd.clear();
}
if(jdk11)
cmd.add("/usr/lib/jvm/java-11-openjdk-amd64/bin/java");
else
cmd.add("java");
for(String param : dParams){
cmd.add("-D" + param);
}
cmd.add("-Xmx" + xmx);
cmd.addAll(JVM_ARGS);
if(!jdk11)
cmd.addAll(JVM8_ARGS);
cmd.add("-jar");
cmd.add("/binarys/" + serverJar);
cmd.add("--log-strip-color");
cmd.add("--world-dir");
cmd.add(worldDir);
cmd.add("--level-name");
cmd.add(levelName);
cmd.add("--port");
cmd.add(String.valueOf(port));
return cmd;
}
private static boolean steamwarStartAvailable(){
return LoadEvaluation.getCPULoad() < 0.7 && LoadEvaluation.getRamPercentage() < 0.8;
}
private static boolean remoteStartAvailable(String remote) {
return LoadEvaluation.getRemoteCPULoad(remote) < 0.7 && LoadEvaluation.getRemoteRamPercentage(remote) < 0.8;
}
private static boolean bauRunning(ProxiedPlayer p, UUID owner){ private static boolean bauRunning(ProxiedPlayer p, UUID owner){
for(Subserver subserver : Subserver.getServerList()){ for(Subserver subserver : Subserver.getServerList()){
if(subserver.getType() == Servertype.BAUSERVER && ((Bauserver)subserver).getOwner().equals(owner)){ if(subserver.getType() == Servertype.BAUSERVER && ((Bauserver)subserver).getOwner().equals(owner)){
@ -304,37 +200,46 @@ public class SubserverSystem {
return false; return false;
} }
private static void copyBauweltIfRequired(ProxiedPlayer p, String sourcePath, String targetPath){ private static void copyBauweltIfRequired(String sourcePath, String targetPath){
File w = new File(targetPath); File w = new File(targetPath);
if (!w.exists() || !w.isDirectory()){ if (!w.exists() || !w.isDirectory())
try { Node.local.execute("cp", "-r", sourcePath, targetPath);
new ProcessBuilder("cp", "-r", sourcePath, targetPath).start().waitFor();
} catch (IOException e) {
Message.send("SERVER_WORLD_ERROR", p);
throw new SecurityException("Could not create Bauwelt", e);
} catch (InterruptedException e){
BungeeCore.log("Could not create Bauwelt", e);
Message.send("SERVER_WORLD_ERROR", p);
Thread.currentThread().interrupt();
}
}
} }
private static int freePort(int start){
private static class Portrange {
private final int start;
private final int end;
private int current;
private Portrange(int start, int end) {
this.start = start;
this.end = end;
current = start;
}
private void increment() {
current++;
if(current == end)
current = start;
}
private synchronized int freePort() {
Set<Integer> usedPorts;
synchronized (Subserver.getServerList()) { synchronized (Subserver.getServerList()) {
int port = start; usedPorts = Subserver.getServerList().stream().map(server -> ((InetSocketAddress) server.getServer().getSocketAddress()).getPort()).collect(Collectors.toSet());
boolean isFree = false; }
while(!isFree){
port++; while(usedPorts.contains(current)) {
isFree = true; increment();
for(Subserver server : Subserver.getServerList()){ }
if(((InetSocketAddress)server.getServer().getSocketAddress()).getPort() == port){
isFree = false; int result = current;
break; increment();
} return result;
}
}
return port;
} }
} }
} }

Datei anzeigen

@ -27,7 +27,6 @@ import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button; import net.dv8tion.jda.api.interactions.components.Button;
import net.md_5.bungee.api.scheduler.ScheduledTask;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -56,7 +55,7 @@ public class AuthManager {
if (TOKENS.containsKey(code)) { if (TOKENS.containsKey(code)) {
Member member = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).retrieveMemberById(TOKENS.get(code).longValue()).complete(); Member member = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).retrieveMemberById(TOKENS.get(code).longValue()).complete();
if(member == null) return null; if(member == null) return null;
user.setDiscordId(member.getId()); user.setDiscordId(member.getIdLong());
MessageBuilder builder = new MessageBuilder(); MessageBuilder builder = new MessageBuilder();
builder.setContent(":white_check_mark: Dein Discord Konto wurde mit **" + user.getUserName() + "** verknüpft"); builder.setContent(":white_check_mark: Dein Discord Konto wurde mit **" + user.getUserName() + "** verknüpft");
builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")), Button.danger("invalid", "Ich war das nicht"))); builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")), Button.danger("invalid", "Ich war das nicht")));

Datei anzeigen

@ -44,6 +44,7 @@ import javax.security.auth.login.LoginException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class SteamwarDiscordBot { public class SteamwarDiscordBot {
@ -54,13 +55,13 @@ public class SteamwarDiscordBot {
} }
@Getter @Getter
private AnnouncementListener announcementListener; private volatile AnnouncementListener announcementListener;
@Getter @Getter
private IngameChatListener ingameChatListener; private volatile IngameChatListener ingameChatListener;
@Getter @Getter
private ServerTeamChatListener serverTeamChatListener; private volatile ServerTeamChatListener serverTeamChatListener;
@Getter @Getter
private final JDA jda; private final JDA jda;
@ -84,7 +85,11 @@ public class SteamwarDiscordBot {
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
try {
activity(); activity();
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not set initial activity to discord", e);
}
EventManager.update(); EventManager.update();
SchematicsManager.update(); SchematicsManager.update();
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
@ -95,7 +100,6 @@ public class SteamwarDiscordBot {
DiscordRolesMessage.sendMessage(); DiscordRolesMessage.sendMessage();
DiscordRulesMessage.sendMessage(); DiscordRulesMessage.sendMessage();
DiscordTicketMessage.sendMessage(); DiscordTicketMessage.sendMessage();
new RolesInteractionButtonListener(); new RolesInteractionButtonListener();
new DiscordTicketListener(); new DiscordTicketListener();
new DiscordAuthListener(); new DiscordAuthListener();
@ -104,7 +108,6 @@ public class SteamwarDiscordBot {
ingameChatListener = new IngameChatListener(); ingameChatListener = new IngameChatListener();
serverTeamChatListener = new ServerTeamChatListener(); serverTeamChatListener = new ServerTeamChatListener();
new SlashCommandListener(); new SlashCommandListener();
jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue()); jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue());
Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD); Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD);

Datei anzeigen

@ -20,6 +20,8 @@
package de.steamwar.bungeecore.bot.commands; package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
@ -49,7 +51,7 @@ public class BanCommand extends BasicDiscordCommand {
return; return;
} }
Timestamp time = de.steamwar.bungeecore.commands.BanCommand.parseTime(null, event.getOption("time").getAsString()); Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString());
if (time == null) { if (time == null) {
event.reply("Angegebene Zeit invalide").setEphemeral(true).queue(); event.reply("Angegebene Zeit invalide").setEphemeral(true).queue();
return; return;
@ -58,8 +60,8 @@ public class BanCommand extends BasicDiscordCommand {
String msg = event.getOption("reason").getAsString(); String msg = event.getOption("reason").getAsString();
boolean isPerma = event.getOption("time").getAsString().equals("perma"); boolean isPerma = event.getOption("time").getAsString().equals("perma");
target.ban(time, msg, sender.getId(), isPerma); target.punish(Punishment.PunishmentType.Ban, time, msg, sender.getId(), isPerma);
Message.team("BAN_TEAM_BANNED", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg); Message.team("BAN_TEAM", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg);
event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gebannt").setEphemeral(true).queue(); event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gebannt").setEphemeral(true).queue();
} }
} }

Datei anzeigen

@ -20,7 +20,8 @@
package de.steamwar.bungeecore.bot.commands; package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.BanCommand; import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
@ -50,7 +51,7 @@ public class MuteCommand extends BasicDiscordCommand {
return; return;
} }
Timestamp time = BanCommand.parseTime(null, event.getOption("time").getAsString()); Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString());
if (time == null) { if (time == null) {
event.reply("Angegebene Zeit invalide").setEphemeral(true).complete(); event.reply("Angegebene Zeit invalide").setEphemeral(true).complete();
return; return;
@ -59,8 +60,8 @@ public class MuteCommand extends BasicDiscordCommand {
String msg = event.getOption("reason").getAsString(); String msg = event.getOption("reason").getAsString();
boolean isPerma = event.getOption("time").getAsString().equals("perma"); boolean isPerma = event.getOption("time").getAsString().equals("perma");
target.mute(time, msg, sender.getId(), isPerma); target.punish(Punishment.PunishmentType.Mute, time, msg, sender.getId(), isPerma);
Message.team("MUTE_TEAM_MUTED", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg); Message.team("MUTE_TEAM", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg);
event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gemutet").setEphemeral(true).queue(); event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gemutet").setEphemeral(true).queue();
} }
} }

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore.bot.commands; package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
@ -47,12 +48,12 @@ public class UnbanCommand extends BasicDiscordCommand {
return; return;
} }
if (!target.isBanned()) { if (!target.isPunished(Punishment.PunishmentType.Ban)) {
event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).queue(); event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).queue();
return; return;
} }
target.ban(Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false); target.punish(Punishment.PunishmentType.Ban, Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false);
event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).queue(); event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).queue();
} }
} }

Datei anzeigen

@ -29,6 +29,7 @@ import java.util.Map;
public class SteamwarDiscordBotConfig { public class SteamwarDiscordBotConfig {
public static boolean loaded = false;
public static String TOKEN; public static String TOKEN;
public static String GUILD; public static String GUILD;
public static String ANNOUNCEMENTS_CHANNEL; public static String ANNOUNCEMENTS_CHANNEL;
@ -110,5 +111,6 @@ public class SteamwarDiscordBotConfig {
for (String type : ranksSections.getKeys()) { for (String type : ranksSections.getKeys()) {
RANKS.put(UserGroup.getUsergroup(type), ranksSections.getString(type)); RANKS.put(UserGroup.getUsergroup(type), ranksSections.getString(type));
} }
loaded = true;
} }
} }

Datei anzeigen

@ -93,7 +93,7 @@ public class EventManager {
MessageBuilder messageBuilder = new MessageBuilder(); MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(embedBuilder.build()); messageBuilder.setEmbeds(embedBuilder.build());
if(!events.isEmpty()) { if(events.stream().anyMatch(event -> event.getDeadline().after(Timestamp.from(Instant.now())))) {
messageBuilder.setActionRows(ActionRow.of(menuBuilder.build())); messageBuilder.setActionRows(ActionRow.of(menuBuilder.build()));
} }
if (message == null) { if (message == null) {

Datei anzeigen

@ -53,13 +53,13 @@ public class SchematicsManager {
CheckCommand.getSchemsToCheck().forEach(schematic -> { CheckCommand.getSchemsToCheck().forEach(schematic -> {
StringBuilder st = new StringBuilder(); StringBuilder st = new StringBuilder();
st.append("Typ: ").append(schematic.getSchemType().getKuerzel()); st.append("Typ: ").append(schematic.getSchemtype().getKuerzel());
st.append("\nVon: ").append(SteamwarUser.get(schematic.getSchemOwner()).getUserName()); st.append("\nVon: ").append(SteamwarUser.get(schematic.getOwner()).getUserName());
String checker = CheckCommand.getChecker(schematic); String checker = CheckCommand.getChecker(schematic);
if (checker != null) { if (checker != null) {
st.append("\nWird Geprüft von: ").append(checker); st.append("\nWird Geprüft von: ").append(checker);
} }
embedBuilder.addField(schematic.getSchemName(), st.toString(), true); embedBuilder.addField(schematic.getName(), st.toString(), true);
}); });
MessageBuilder messageBuilder = new MessageBuilder(); MessageBuilder messageBuilder = new MessageBuilder();

Datei anzeigen

@ -22,6 +22,7 @@ package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.listeners.ChatListener; import de.steamwar.bungeecore.listeners.ChatListener;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import de.steamwar.bungeecore.sql.UserGroup; import de.steamwar.bungeecore.sql.UserGroup;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
@ -50,7 +51,7 @@ public class IngameChatListener extends BasicDiscordListener {
event.getMessage().delete().queue(); event.getMessage().delete().queue();
return; return;
} }
if (steamwarUser.isMuted() || steamwarUser.isBanned()) { if (steamwarUser.isPunished(Punishment.PunishmentType.Mute) || steamwarUser.isPunished(Punishment.PunishmentType.Ban)) {
event.getMessage().delete().queue(); event.getMessage().delete().queue();
return; return;
} }

Datei anzeigen

@ -20,7 +20,7 @@
package de.steamwar.bungeecore.bot.util; package de.steamwar.bungeecore.bot.util;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.sql.Schematic; import de.steamwar.bungeecore.sql.SchematicNode;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
@ -36,14 +36,14 @@ import java.time.Instant;
@UtilityClass @UtilityClass
public class DiscordSchemAlert { public class DiscordSchemAlert {
public void sendDecline(Schematic schematic, SteamwarUser user, String reason) { public void sendDecline(SchematicNode schematic, SteamwarUser user, String reason) {
if(user.getDiscordId() != null) { if(user.getDiscordId() != null) {
User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete(); User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete();
EmbedBuilder builder = new EmbedBuilder(); EmbedBuilder builder = new EmbedBuilder();
builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png"); builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png");
builder.setColor(Color.RED); builder.setColor(Color.RED);
builder.setTitle("SteamWar-Schematic Info"); builder.setTitle("SteamWar-Schematic Info");
builder.setDescription("Deine Schematic **" + schematic.getSchemName() + "** wurde abgelehnt. **Grund:** \n" + reason); builder.setDescription("Deine Schematic **" + schematic.getName() + "** wurde abgelehnt. **Grund:** \n" + reason);
builder.setTimestamp(Instant.now()); builder.setTimestamp(Instant.now());
MessageBuilder messageBuilder = new MessageBuilder(); MessageBuilder messageBuilder = new MessageBuilder();
@ -56,14 +56,14 @@ public class DiscordSchemAlert {
} }
} }
public void sendAccept(Schematic schematic, SteamwarUser user) { public void sendAccept(SchematicNode schematic, SteamwarUser user) {
if(user.getDiscordId() != null) { if(user.getDiscordId() != null) {
User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete(); User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(user.getDiscordId()).complete();
EmbedBuilder builder = new EmbedBuilder(); EmbedBuilder builder = new EmbedBuilder();
builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png"); builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png");
builder.setColor(Color.GREEN); builder.setColor(Color.GREEN);
builder.setTitle("SteamWar-Schematic Info"); builder.setTitle("SteamWar-Schematic Info");
builder.setDescription("Deine Schematic **" + schematic.getSchemName() + "** wurde angenommen."); builder.setDescription("Deine Schematic **" + schematic.getName() + "** wurde angenommen.");
builder.setTimestamp(Instant.now()); builder.setTimestamp(Instant.now());
MessageBuilder messageBuilder = new MessageBuilder(); MessageBuilder messageBuilder = new MessageBuilder();

Datei anzeigen

@ -1,85 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
public class BanCommand extends BasicCommand {
public BanCommand() {
super("ban", "bungeecore.ban");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(args.length < 3){
Message.send("USAGE_BAN", sender);
return;
}
SteamwarUser target = unsafeUser(sender, args[0]);
if(target == null)
return;
Timestamp banTime = parseTime(sender, args[1]);
if(banTime == null)
return;
StringBuilder banReason = new StringBuilder();
for (int i = 2; i < args.length; i++){
banReason.append(args[i]).append(" ");
}
boolean isPerma = args[1].equalsIgnoreCase("perma");
String msg = banReason.toString();
target.ban(banTime, msg, SteamwarUser.get(sender.getName()).getId(), isPerma);
Message.team("BAN_TEAM_BANNED", new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((isPerma?"BAN_PERMA":"BAN_UNTIL"), banTime), msg);
}
public static Timestamp parseTime(CommandSender sender, String arg){
if(arg.equalsIgnoreCase("perma")) {
return Timestamp.from(Instant.ofEpochSecond(946674800));
}else{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy_HH:mm");
try{
Date parsedDate = dateFormat.parse(arg);
return new java.sql.Timestamp(parsedDate.getTime());
}catch(ParseException e){
dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try{
Date parsedDate = dateFormat.parse(arg.split("_")[0]);
return new java.sql.Timestamp(parsedDate.getTime());
}catch(ParseException exception){
if (sender != null) {
Message.send("INVALID_TIME", sender);
}
return null;
}
}
}
}
}

Datei anzeigen

@ -38,8 +38,9 @@ public class BauCommand extends BasicCommand {
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if(!(sender instanceof ProxiedPlayer)) if(!(sender instanceof ProxiedPlayer)) {
return; return;
}
ProxiedPlayer p = (ProxiedPlayer) sender; ProxiedPlayer p = (ProxiedPlayer) sender;
@ -68,9 +69,6 @@ public class BauCommand extends BasicCommand {
case "1.15": case "1.15":
SubserverSystem.sendToBau15(p, p.getUniqueId()); SubserverSystem.sendToBau15(p, p.getUniqueId());
break; break;
case "paper":
SubserverSystem.sendToBau15paper(p, p.getUniqueId());
break;
case "addmember": case "addmember":
addmember(p, args); addmember(p, args);
break; break;
@ -249,7 +247,6 @@ public class BauCommand extends BasicCommand {
} }
private static void deleteWorld(ProxiedPlayer player, String world) { private static void deleteWorld(ProxiedPlayer player, String world) {
Message.send("BAU_DELETE_DELETED", player);
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> {
for (Subserver subserver : Subserver.getServerList()) { for (Subserver subserver : Subserver.getServerList()) {
if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(player.getUniqueId())) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(player.getUniqueId())) {
@ -257,17 +254,21 @@ public class BauCommand extends BasicCommand {
break; break;
} }
} }
SubserverSystem.deleteFolder(world); SubserverSystem.deleteFolder(Node.local, world);
Message.send("BAU_DELETE_DELETED", player);
}); });
} }
public static boolean stopBauserver(ProxiedPlayer p){ public static boolean stopBauserver(ProxiedPlayer p){
for (Subserver subserver : Subserver.getServerList()) { for (Subserver subserver : Subserver.getServerList()) {
if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId())) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId()) && !subserver.hasStarted()) {
if(!subserver.hasStarted()){
Message.send("BAU_START_ALREADY", p); Message.send("BAU_START_ALREADY", p);
return false; return false;
} }
}
for (Subserver subserver : Subserver.getServerList()) {
if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(p.getUniqueId())) {
subserver.stop(); subserver.stop();
try { try {
Thread.sleep(200); // Wait until possible testarena-World has been deleted Thread.sleep(200); // Wait until possible testarena-World has been deleted

Datei anzeigen

@ -27,7 +27,8 @@ import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.*; import java.util.ArrayList;
import java.util.LinkedList;
import static de.steamwar.bungeecore.Storage.challenges; import static de.steamwar.bungeecore.Storage.challenges;

Datei anzeigen

@ -23,7 +23,7 @@ import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.bot.util.DiscordSchemAlert; import de.steamwar.bungeecore.bot.util.DiscordSchemAlert;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.bungeecore.sql.CheckedSchematic; import de.steamwar.bungeecore.sql.CheckedSchematic;
import de.steamwar.bungeecore.sql.Schematic; import de.steamwar.bungeecore.sql.SchematicNode;
import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SchematicType;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
@ -47,16 +47,10 @@ public class CheckCommand extends BasicCommand {
private static Map<UUID, CheckSession> currentCheckers = new HashMap<>(); private static Map<UUID, CheckSession> currentCheckers = new HashMap<>();
private static Map<Integer, CheckSession> currentSchems = new HashMap<>(); private static Map<Integer, CheckSession> currentSchems = new HashMap<>();
public static void loadCheckQuestions(Configuration config){ public static void setCheckQuestions(SchematicType checkType, Configuration config) {
for(String schemType : config.getKeys()){ checkQuestions.put(checkType, config.getStringList("CheckQuestions"));
checkQuestions.put(SchematicType.fromDB(schemType), config.getStringList(schemType)); if(!config.getStringList("Ranks").isEmpty())
} ranks.put(checkType, config.getStringList("Ranks"));
}
public static void loadRanks(Configuration config){
for(String schemType : config.getKeys()){
ranks.put(SchematicType.fromDB(schemType), config.getStringList(schemType));
}
} }
public static boolean isChecking(ProxiedPlayer player){ public static boolean isChecking(ProxiedPlayer player){
@ -67,13 +61,13 @@ public class CheckCommand extends BasicCommand {
super("check", ConnectionListener.CHECK_PERMISSION); super("check", ConnectionListener.CHECK_PERMISSION);
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
List<Schematic> schematics = getSchemsToCheck(); List<SchematicNode> schematics = getSchemsToCheck();
if(schematics.size() != currentCheckers.size()) if(schematics.size() != currentCheckers.size())
Message.team("CHECK_REMINDER", "CHECK_REMINDER_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size()); Message.team("CHECK_REMINDER", "CHECK_REMINDER_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size());
}, 10, 10, TimeUnit.MINUTES); }, 10, 10, TimeUnit.MINUTES);
} }
public static void sendReminder(ProxiedPlayer player) { public static void sendReminder(ProxiedPlayer player) {
List<Schematic> schematics = getSchemsToCheck(); List<SchematicNode> schematics = getSchemsToCheck();
if(schematics.size() != currentCheckers.size()) if(schematics.size() != currentCheckers.size())
Message.send("CHECK_REMINDER", player, "CHECK_REMINDER_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size()); Message.send("CHECK_REMINDER", player, "CHECK_REMINDER_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size());
} }
@ -111,38 +105,38 @@ public class CheckCommand extends BasicCommand {
} }
} }
public static List<Schematic> getSchemsToCheck(){ public static List<SchematicNode> getSchemsToCheck(){
List<Schematic> schematicList = new LinkedList<>(); List<SchematicNode> schematicList = new LinkedList<>();
for (SchematicType type : SchematicType.values()) { for (SchematicType type : SchematicType.values()) {
if (type.check()) if (type.check())
schematicList.addAll(Schematic.getAllSchemsOfType(type)); schematicList.addAll(SchematicNode.getAllSchematicsOfType(type.toDB()));
} }
return schematicList; return schematicList;
} }
public static String getChecker(Schematic schematic) { public static String getChecker(SchematicNode schematic) {
if (currentSchems.get(schematic.getSchemID()) == null) return null; if (currentSchems.get(schematic.getId()) == null) return null;
return currentSchems.get(schematic.getSchemID()).checker.getName(); return currentSchems.get(schematic.getId()).checker.getName();
} }
private void list(ProxiedPlayer player) { private void list(ProxiedPlayer player) {
List<Schematic> schematicList = getSchemsToCheck(); List<SchematicNode> schematicList = getSchemsToCheck();
Message.sendPrefixless("CHECK_LIST_HEADER", player, schematicList.size()); Message.sendPrefixless("CHECK_LIST_HEADER", player, schematicList.size());
for (Schematic schematic : schematicList) { for (SchematicNode schematic : schematicList) {
CheckSession current = currentSchems.get(schematic.getSchemID()); CheckSession current = currentSchems.get(schematic.getId());
if (current == null) { if (current == null) {
Message.sendPrefixless("CHECK_LIST_TO_CHECK", player, Message.sendPrefixless("CHECK_LIST_TO_CHECK", player,
Message.parse("CHECK_LIST_TO_CHECK_HOVER", player), Message.parse("CHECK_LIST_TO_CHECK_HOVER", player),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check schematic " + schematic.getSchemID()), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check schematic " + schematic.getId()),
schematic.getSchemType().getKuerzel(), SteamwarUser.get(schematic.getSchemOwner()).getUserName(), schematic.getSchemName()); schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName());
} else { } else {
Message.sendPrefixless("CHECK_LIST_CHECKING", player, Message.sendPrefixless("CHECK_LIST_CHECKING", player,
Message.parse("CHECK_LIST_CHECKING_HOVER", player), Message.parse("CHECK_LIST_CHECKING_HOVER", player),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + current.checker.getName()), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + current.checker.getName()),
schematic.getSchemType().getKuerzel(), SteamwarUser.get(schematic.getSchemOwner()).getUserName(), schematic.getSchemName(), current.checker.getName()); schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName(), current.checker.getName());
} }
} }
} }
@ -153,11 +147,11 @@ public class CheckCommand extends BasicCommand {
return; return;
} }
Schematic schem = Schematic.getSchemFromDB(Integer.parseInt(schemID)); SchematicNode schem = SchematicNode.getSchematicNode(Integer.parseInt(schemID));
if(!schem.getSchemType().check()){ if(!schem.getSchemtype().check()){
ProxyServer.getInstance().getLogger().log(Level.SEVERE, player.getName() + " tried to check an uncheckable schematic!"); ProxyServer.getInstance().getLogger().log(Level.SEVERE, player.getName() + " tried to check an uncheckable schematic!");
return; return;
}else if(schem.getSchemOwner() == SteamwarUser.get(player.getUniqueId()).getId()) { }else if(schem.getOwner() == SteamwarUser.get(player.getUniqueId()).getId()) {
Message.send("CHECK_SCHEMATIC_OWN", player); Message.send("CHECK_SCHEMATIC_OWN", player);
return; return;
} }
@ -223,15 +217,15 @@ public class CheckCommand extends BasicCommand {
private static class CheckSession{ private static class CheckSession{
private final ProxiedPlayer checker; private final ProxiedPlayer checker;
private final Schematic schematic; private final SchematicNode schematic;
private final Timestamp startTime; private final Timestamp startTime;
private final ListIterator<String> checkList; private final ListIterator<String> checkList;
private CheckSession(ProxiedPlayer checker, Schematic schematic){ private CheckSession(ProxiedPlayer checker, SchematicNode schematic){
this.checker = checker; this.checker = checker;
this.schematic = schematic; this.schematic = schematic;
this.startTime = Timestamp.from(Instant.now()); this.startTime = Timestamp.from(Instant.now());
this.checkList = checkQuestions.get(schematic.getSchemType()).listIterator(); this.checkList = checkQuestions.get(schematic.getSchemtype()).listIterator();
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> {
if(!BauCommand.stopBauserver(checker)){ if(!BauCommand.stopBauserver(checker)){
@ -239,12 +233,12 @@ public class CheckCommand extends BasicCommand {
return; return;
} }
ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemType().fightType()); ArenaMode mode = ArenaMode.getBySchemType(schematic.getSchemtype().fightType());
SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getSchemID(), 0); SubserverSystem.startTestServer(checker, mode, FightCommand.getMap(checker, mode, "Random"), schematic.getId(), 0);
currentCheckers.put(checker.getUniqueId(), this); currentCheckers.put(checker.getUniqueId(), this);
currentSchems.put(schematic.getSchemID(), this); currentSchems.put(schematic.getId(), this);
for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic.getSchemName(), schematic.getSchemOwner())) for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic))
Message.sendPrefixless("CHECK_SCHEMATIC_PREVIOUS", checker, previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getReason()); Message.sendPrefixless("CHECK_SCHEMATIC_PREVIOUS", checker, previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getDeclineReason());
next(0); next(0);
}); });
} }
@ -262,8 +256,8 @@ public class CheckCommand extends BasicCommand {
if(checkList.hasNext()){ if(checkList.hasNext()){
next.setText(Message.parse("CHECK_NEXT", checker)); next.setText(Message.parse("CHECK_NEXT", checker));
next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check next")); next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check next"));
}else if(ranks.containsKey(schematic.getSchemType())){ }else if(ranks.containsKey(schematic.getSchemtype())){
List<String> r = ranks.get(schematic.getSchemType()); List<String> r = ranks.get(schematic.getSchemtype());
for(int i = 0; i < r.size(); i++){ for(int i = 0; i < r.size(); i++){
Message.sendPrefixless("CHECK_RANK", checker, Message.sendPrefixless("CHECK_RANK", checker,
Message.parse("CHECK_RANK_HOVER", checker), Message.parse("CHECK_RANK_HOVER", checker),
@ -285,48 +279,49 @@ public class CheckCommand extends BasicCommand {
} }
private void accept(int rank){ private void accept(int rank){
if(ranks.containsKey(schematic.getSchemType())){ if(ranks.containsKey(schematic.getSchemtype())){
if(rank <= 0 || ranks.get(schematic.getSchemType()).size() < rank){ if(rank <= 0 || ranks.get(schematic.getSchemtype()).size() < rank){
Message.send("CHECK_INVALID_RANK", checker); Message.send("CHECK_INVALID_RANK", checker);
return; return;
} }
schematic.setRank(rank); schematic.setRank(rank);
} }
schematic.setSchemType(schematic.getSchemType().fightType()); schematic.setType(schematic.getSchemtype().fightType().toDB());
CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben"); CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "freigegeben");
SteamwarUser user = SteamwarUser.get(schematic.getSchemOwner()); SteamwarUser user = SteamwarUser.get(schematic.getOwner());
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid());
if(player != null) { if(player != null) {
Message.send("CHECK_ACCEPTED", player, schematic.getSchemType().name(), schematic.getSchemName()); Message.send("CHECK_ACCEPTED", player, schematic.getSchemtype().name(), schematic.getName());
} else { } else {
DiscordSchemAlert.sendAccept(schematic, user); DiscordSchemAlert.sendAccept(schematic, user);
} }
Message.team("CHECK_ACCEPTED_TEAM", schematic.getSchemName(), user.getUserName()); Message.team("CHECK_ACCEPTED_TEAM", schematic.getName(), user.getUserName());
stop(); stop();
} }
private void decline(String reason){ private void decline(String reason){
schematic.setSchemType(SchematicType.Normal); schematic.setType(SchematicType.Normal.toDB());
CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason); CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), reason);
SteamwarUser user = SteamwarUser.get(schematic.getSchemOwner()); SteamwarUser user = SteamwarUser.get(schematic.getOwner());
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUuid());
if(player != null) { if(player != null) {
Message.send("CHECK_DECLINED", player, schematic.getSchemType().name(), schematic.getSchemName(), reason); Message.send("CHECK_DECLINED", player, schematic.getSchemtype().name(), schematic.getName(), reason);
} else { } else {
DiscordSchemAlert.sendDecline(schematic, user, reason); DiscordSchemAlert.sendDecline(schematic, user, reason);
} }
Message.team("CHECK_DECLINED_TEAM", schematic.getSchemName(), user.getUserName(), reason); Message.team("CHECK_DECLINED_TEAM", schematic.getName(), user.getUserName(), reason);
stop(); stop();
} }
private void abort(){ private void abort(){
CheckedSchematic.create(schematic.getSchemName(), schematic.getSchemOwner(), SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen"); CheckedSchematic.create(schematic, SteamwarUser.get(checker.getUniqueId()).getId(), startTime, Timestamp.from(Instant.now()), "Prüfvorgang abgebrochen");
stop(); stop();
} }
private void stop(){ private void stop(){
remove(); currentCheckers.remove(checker.getUniqueId());
currentSchems.remove(schematic.getId());
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> {
for (Subserver subserver : Subserver.getServerList()) { for (Subserver subserver : Subserver.getServerList()) {
if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(checker.getUniqueId())) { if (subserver.getType() == Servertype.BAUSERVER && ((Bauserver) subserver).getOwner().equals(checker.getUniqueId())) {
@ -339,7 +334,7 @@ public class CheckCommand extends BasicCommand {
private void remove() { private void remove() {
currentCheckers.remove(checker.getUniqueId()); currentCheckers.remove(checker.getUniqueId());
currentSchems.remove(schematic.getSchemID()); currentSchems.remove(schematic.getId());
} }
} }
} }

Datei anzeigen

@ -20,6 +20,8 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.config.ServerInfo;
@ -27,14 +29,15 @@ import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.File; import java.io.File;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.function.Predicate; import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DevCommand extends BasicCommand { public class DevCommand extends BasicCommand {
private final File DevServerDir = new File("/configs/DevServer"); private final File devServerDir = new File("/configs/DevServer");
private final Map<String, ServerInfo> devServers = new HashMap<>();
public DevCommand() { public DevCommand() {
super("dev", ""); super("dev", "");
@ -42,56 +45,79 @@ public class DevCommand extends BasicCommand {
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) { if (!(sender instanceof ProxiedPlayer))
return;
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser steamwarUser = SteamwarUser.get(player);
if (steamwarUser.isPunishedWithMessage(player, Punishment.PunishmentType.NoDevServer)) {
return; return;
} }
String[] devServer = DevServerDir.list();
if (devServer == null || devServer.length == 0) { updateDevServers();
if(devServers.isEmpty()) {
Message.send("DEV_NO_SERVER", sender); Message.send("DEV_NO_SERVER", sender);
} else if (devServer.length == 1) { } else if (devServers.size() == 1) {
String[] server = devServer[0].split("\\."); player.connect(devServers.values().stream().findAny().get());
sendToServer((ProxiedPlayer) sender, server[0], Integer.parseInt(server[1])); } else if (args.length == 0) {
} else { ServerInfo info = devServers.get(player.getName().toLowerCase());
if (args.length == 0) { if (info == null) {
send(devServer, (ProxiedPlayer) sender, s -> s.equalsIgnoreCase(sender.getName()), () -> Message.send("DEV_UNKNOWN_SERVER", sender)); Message.send("DEV_UNKNOWN_SERVER", player);
} else { return;
send(devServer, (ProxiedPlayer) sender, args[0]::equalsIgnoreCase, () -> Message.send("DEV_NO_SERVER", sender));
}
}
} }
private void send(String[] devServer, ProxiedPlayer sender, Predicate<String> test, Runnable error) { player.connect(info);
for (String s : devServer) { } else {
String[] server = s.split("\\."); ServerInfo info = devServers.get(args[0].toLowerCase());
if (test.test(server[0])) { if (info == null) {
sendToServer(sender, server[0], Integer.parseInt(server[1])); Message.send("DEV_NO_SERVER", player);
break; return;
}
}
error.run();
} }
private void sendToServer(ProxiedPlayer proxiedPlayer, String name, int port) { player.connect(info);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", port); }
ServerInfo serverInfo = ProxyServer.getInstance().constructServerInfo("Dev-" + name, address, "SteamWar.de - Subserver", false);
proxiedPlayer.connect(serverInfo);
} }
@Override @Override
public Iterable<String> onTabComplete(CommandSender sender, String[] args) { public Iterable<String> onTabComplete(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) { if (!(sender instanceof ProxiedPlayer) || args.length > 1) {
return Collections.emptyList(); return Collections.emptyList();
} }
String[] devSever = DevServerDir.list();
if (devSever == null) { updateDevServers();
return Collections.emptyList(); return devServers.keySet().stream().filter(s -> {
}
if (args.length > 1) {
return Collections.emptyList();
}
return Arrays.stream(devSever).map(s -> s.split("\\.")).map(s -> s[0]).filter(s -> {
if (args.length == 0) return true; if (args.length == 0) return true;
return s.startsWith(args[0]); return s.startsWith(args[0].toLowerCase());
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
private void updateDevServers() {
String[] serverFiles = devServerDir.list();
Map<String, Integer> devServerFiles = new HashMap<>();
if(serverFiles != null) {
for(String serverFile : serverFiles) {
String[] server = serverFile.split("\\.");
devServerFiles.put(server[0], Integer.parseInt(server[1]));
}
}
devServers.entrySet().removeIf(entry -> {
if(!devServerFiles.containsKey(entry.getKey())) {
ProxyServer.getInstance().getServers().remove(entry.getValue().getName());
return true;
}
return false;
});
devServerFiles.forEach((key, value) -> {
if (devServers.containsKey(key))
return;
SteamwarUser user = SteamwarUser.get(key);
ServerInfo info = ProxyServer.getInstance().constructServerInfo("Dev " + user.getUserName(), new InetSocketAddress("127.0.0.1", value), "SteamWar.de - Subserver", false);
ProxyServer.getInstance().getServers().put(info.getName(), info);
devServers.put(user.getUserName().toLowerCase(), info);
});
}
} }

Datei anzeigen

@ -0,0 +1,275 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.Statement;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class GDPRQuery extends BasicCommand {
public GDPRQuery() {
super("gdprquery", "bungeecore.softreload");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!(sender instanceof ProxiedPlayer))
return;
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser user = args.length == 0 ? SteamwarUser.get(player.getUniqueId()) : SteamwarUser.get(args[0]);
if(user == null) {
Message.send("UNKNOWN_PLAYER", player);
return;
}
BungeeCord.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> {
try {
createZip(player, user);
} catch (IOException e) {
throw new SecurityException("Could not create zip", e);
}
});
}
private void createZip(ProxiedPlayer player, SteamwarUser user) throws IOException {
printUpdate(player, "GDPR_STATUS_WEBSITE");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(user.getUserName() + ".zip"));
copy(getClass().getClassLoader().getResourceAsStream("GDPRQueryREADME.md"), out, "README.md");
copy(getClass().getClassLoader().getResourceAsStream("GDPRQueryREADME.md"), out, "README.txt");
printUpdate(player, "GDPR_STATUS_WORLD");
copyBauwelt(user, out, "/home/minecraft/userworlds/" + user.getUuid().toString(), "BuildWorld12");
copyBauwelt(user, out, "/home/minecraft/userworlds15/" + user.getId(), "BuildWorld15");
printUpdate(player, "GDPR_STATUS_INVENTORIES");
copyPlayerdata(user, out, "/home/minecraft/userworlds", "BuildInventories12");
copyPlayerdata(user, out, "/home/minecraft/userworlds15", "BuildInventories15");
printUpdate(player, "GDPR_STATUS_DATABASE");
sqlCSV(user, out, bannedIPs, "BannedIPs.csv");
sqlCSV(user, out, bauweltMember, "BuildMember.csv");
sqlCSV(user, out, bauweltMembers, "BuildMembers.csv");
sqlCSV(user, out, checkedSchems, "SchematicChecksessions.csv");
sqlCSV(user, out, elo, "Elo.csv");
sqlCSV(user, out, fights, "Fights.csv");
sqlCSV(user, out, ignoredPlayers, "IgnoredPlayers.csv");
sqlCSV(user, out, ignoringPlayers, "IgnoringPlayers.csv");
sqlCSV(user, out, schematicMember, "SchematicMember.csv");
sqlCSV(user, out, schematicMembers, "SchematicMembers.csv");
sqlCSV(user, out, pollAnswers, "PollAnswers.csv");
sqlCSV(user, out, punishments, "Punishments.csv");
sqlCSV(user, out, sessions, "Sessions.csv");
sqlCSV(user, out, userData, "UserData.csv");
sqlCSV(user, out, personalKits, "PersonalKits.csv");
sqlCSV(user, out, schematics, "Schematics.csv");
personalKits(user, out);
schematics(user, out);
userConfig(user, out);
printUpdate(player, "GDPR_STATUS_LOGS");
copyLogs(user, out, new File("/logs"), "logs");
out.close();
printUpdate(player, "GDPR_STATUS_FINISHED");
}
private static final Statement bannedIPs = new Statement("SELECT Timestamp, IP FROM BannedUserIPs WHERE UserID = ?");
private static final Statement bauweltMember = new Statement("SELECT BauweltID AS Bauwelt, WorldEdit, World FROM BauweltMember WHERE MemberID = ?");
private static final Statement bauweltMembers = new Statement("SELECT u.UserName AS 'User', m.WorldEdit AS WorldEdit, m.World AS World FROM BauweltMember m INNER JOIN UserData u ON m.MemberID = u.id WHERE m.BauweltID = ?");
private static final Statement checkedSchems = new Statement("SELECT NodeName AS Schematic, StartTime, EndTime, DeclineReason AS Result FROM CheckedSchematic WHERE NodeOwner = ? ORDER BY StartTime ASC");
private static final Statement elo = new Statement("SELECT GameMode, Elo FROM Elo WHERE UserID = ?");
private static final Statement fights = new Statement("SELECT p.Team AS Team, p.Kit AS Kit, p.Kills AS Kills, p.IsOut AS Died, f.GameMode AS GameMode, f.Server AS Server, f.Arena AS Arena, f.StartTime AS StartTime, f.Duration AS Duration, (f.BlueLeader = p.UserID) AS IsBlueLeader, (f.RedLeader = p.UserID) AS IsRedLeader, f.Win AS Winner, f.WinCondition AS WinCondition FROM Fight f INNER JOIN FightPlayer p ON f.FightID = p.FightID WHERE p.UserID = ? ORDER BY StartTime ASC");
private static final Statement ignoredPlayers = new Statement("SELECT u.UserName AS IgnoredPlayer FROM IgnoredPlayers i INNER JOIN UserData u ON i.Ignored = u.id WHERE Ignorer = ?");
private static final Statement ignoringPlayers = new Statement("SELECT Ignorer AS IgnoringPlayers FROM IgnoredPlayers WHERE Ignored = ?");
private static final Statement schematicMember = new Statement("SELECT s.NodeName AS SchematicName, u.UserName AS SchematicOwner FROM NodeMember m INNER JOIN SchematicNode s ON m.NodeId = s.NodeId INNER JOIN UserData u ON s.NodeOwner = u.id WHERE m.UserId = ?");
private static final Statement schematicMembers = new Statement("SELECT s.NodeName AS SchematicName, u.UserName AS Member FROM NodeMember m INNER JOIN SchematicNode s ON m.NodeId = s.NodeId INNER JOIN UserData u ON m.UserId = u.id WHERE s.NodeOwner = ?");
private static final Statement pollAnswers = new Statement("SELECT Question, Answer FROM PollAnswer WHERE UserID = ?");
private static final Statement punishments = new Statement("SELECT Type, StartTime, EndTime, Perma, Reason FROM Punishments WHERE UserId = ?");
private static final Statement sessions = new Statement("SELECT StartTime, EndTime FROM Session WHERE UserID = ?");
private static final Statement userData = new Statement("SELECT * FROM UserData WHERE id = ?");
private static final Statement personalKits = new Statement("SELECT GameMode, Name, InUse FROM PersonalKit WHERE UserID = ?");
private static final Statement personalKitData = new Statement("SELECT GameMode, Name, Inventory, Armor FROM PersonalKit WHERE UserID = ?");
private static final Statement schematics = new Statement("SELECT NodeName AS SchematicName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank FROM SchematicNode WHERE NodeOwner = ?");
private static final Statement schematicData = new Statement("SELECT NodeName, ParentNode, NodeFormat, NodeData FROM SchematicNode WHERE NodeOwner = ?");
private static final Statement userConfig = new Statement("SELECT * FROM UserConfig WHERE User = ?");
private void sqlCSV(SteamwarUser user, ZipOutputStream out, Statement statement, String path) throws IOException {
write(stream -> statement.select(rs -> {
try {
OutputStreamWriter writer = new OutputStreamWriter(stream);
int columns = rs.getMetaData().getColumnCount();
for(int i = 1; i <= columns; i++) {
writer.write(rs.getMetaData().getColumnLabel(i));
writer.write(";");
}
writer.write("\n");
while(rs.next()) {
for(int i = 1; i <= columns; i++) {
try {
writer.write(rs.getString(i));
} catch (NullPointerException e) {
// ignored
}
writer.write(";");
}
writer.write("\n");
}
writer.flush();
} catch (IOException e) {
throw new SecurityException("Could not write file", e);
}
return null;
}, user.getId()), out, path);
}
private void personalKits(SteamwarUser user, ZipOutputStream out) {
personalKitData.select(rs -> {
while(rs.next()) {
try {
String path = "PersonalKit/" + rs.getString("GameMode") + "/" + rs.getString("Name");
try(InputStream data = rs.getBinaryStream("Inventory")) {
copy(data, out, path + ".Inventory.yml");
}
try(InputStream data = rs.getBinaryStream("Armor")) {
copy(data, out, path + ".Armor.yml");
}
} catch (IOException e) {
throw new SecurityException("Could not export PersonalKits", e);
}
}
return null;
}, user.getId());
}
private void schematics(SteamwarUser user, ZipOutputStream out) {
schematicData.select(rs -> {
while(rs.next()) {
String name = (rs.getString("ParentNode") != null ? rs.getString("ParentNode") : "") + ":" + rs.getString("NodeName");
boolean format = rs.getBoolean("NodeFormat");
try(InputStream data = rs.getBinaryStream("NodeData")) {
copy(data, out, "Schematics/" + name + (format ? ".schem" : ".schematic"));
} catch (IOException e) {
throw new SecurityException("Could not export Schematic", e);
}
}
return null;
}, user.getId());
}
private void userConfig(SteamwarUser user, ZipOutputStream out) {
userConfig.select(rs -> {
while(rs.next()) {
String name = rs.getString("Config");
try(InputStream data = rs.getBinaryStream("Value")) {
copy(data, out, name + ".yapion");
} catch (IOException e) {
throw new SecurityException("Could not export UserConfig", e);
}
}
return null;
}, user.getId());
}
private void copyLogs(SteamwarUser user, ZipOutputStream out, File log, String outFile) throws IOException {
if (log.isDirectory()) {
for(File logfile : log.listFiles()) {
copyLogs(user, out, logfile, outFile + "/" + logfile.getName().replace(".gz", ""));
}
} else {
Process reader = new ProcessBuilder("zgrep", "^.*" + user.getUserName() + "\\( issued server command:\\| moved too quickly!\\| executed command:\\| lost connection:\\||\\\\|\\[\\|\\]\\).*$", log.getPath()).start();
copy(reader.getInputStream(), out, outFile);
}
}
private void copyBauwelt(SteamwarUser user, ZipOutputStream out, String inDir, String outDir) throws IOException {
File world = new File(inDir);
if(!world.exists())
return;
copy(new File(world, "level.dat"), out, outDir + "/level.dat");
File region = new File(world, "region");
for(File regionfile : region.listFiles()) {
copy(regionfile, out, outDir + "/region/" + regionfile.getName());
}
File poi = new File(world, "poi");
if(poi.exists()) {
for(File regionfile : poi.listFiles()) {
copy(regionfile, out, outDir + "/poi/" + regionfile.getName());
}
}
File playerdata = new File(world, "playerdata/" + user.getUuid().toString() + ".dat");
if(playerdata.exists())
copy(playerdata, out, outDir + "/playerdata/" + user.getUuid().toString() + ".dat");
}
private void copyPlayerdata(SteamwarUser user, ZipOutputStream out, String inDir, String outDir) throws IOException {
File worlds = new File(inDir);
String path = "playerdata/" + user.getUuid().toString() + ".dat";
int i = 0;
for(File world : worlds.listFiles()) {
File playerdata = new File(world, path);
if(!playerdata.exists())
continue;
copy(playerdata, out, outDir + "/" + (i++) + "/" + user.getUuid().toString() + ".dat");
}
}
private void printUpdate(ProxiedPlayer player, String message) {
if (player.isConnected())
Message.send(message, player);
}
private void copy(File file, ZipOutputStream out, String path) throws IOException {
try(FileInputStream in = new FileInputStream(file)) {
copy(in, out, path);
}
}
private void copy(InputStream in, ZipOutputStream out, String path) throws IOException {
boolean initialized = false;
int bytes;
for(byte[] buf = new byte[8192]; (bytes = in.read(buf)) > 0; ) {
if(!initialized) {
ZipEntry entry = new ZipEntry(path);
out.putNextEntry(entry);
initialized = true;
}
out.write(buf, 0, bytes);
}
if(initialized) {
out.closeEntry();
}
}
private void write(Writer writer, ZipOutputStream out, String path) throws IOException {
ZipEntry entry = new ZipEntry(path);
out.putNextEntry(entry);
writer.accept(out);
out.closeEntry();
}
private interface Writer {
void accept(OutputStream stream) throws IOException;
}
}

Datei anzeigen

@ -19,7 +19,10 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.SubserverSystem;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;

Datei anzeigen

@ -22,6 +22,7 @@ package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.IgnoreSystem; import de.steamwar.bungeecore.sql.IgnoreSystem;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
@ -48,8 +49,7 @@ public class MsgCommand extends BasicCommand {
} }
SteamwarUser user = SteamwarUser.get(player); SteamwarUser user = SteamwarUser.get(player);
if(user.isMuted()){ if (user.isPunishedWithMessage(player, Punishment.PunishmentType.Mute)) {
sender.sendMessage(user.muteMessage(player));
return; return;
} }

Datei anzeigen

@ -1,57 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender;
import java.sql.Timestamp;
public class MuteCommand extends BasicCommand {
public MuteCommand() {
super("mute", "bungeecore.ban");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(args.length < 3){
Message.send("USAGE_MUTE", sender);
return;
}
SteamwarUser target = unsafeUser(sender, args[0]);
if(target == null)
return;
Timestamp muteTime = BanCommand.parseTime(sender, args[1]);
if(muteTime == null)
return;
StringBuilder muteReason = new StringBuilder();
for (int i = 2; i < args.length; i++){
muteReason.append(args[i]).append(" ");
}
String msg = muteReason.toString();
target.mute(muteTime, msg, SteamwarUser.get(sender.getName()).getId(), args[1].equalsIgnoreCase("perma"));
Message.team("MUTE_TEAM_MUTED", new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((args[1].equalsIgnoreCase("perma")?"BAN_PERMA":"BAN_UNTIL"), muteTime), msg);
}
}

Datei anzeigen

@ -46,7 +46,7 @@ public class PollresultCommand extends BasicCommand {
ProxiedPlayer player = (ProxiedPlayer) sender; ProxiedPlayer player = (ProxiedPlayer) sender;
Map<String, Integer> voted = PollAnswer.getCurrentResults(); Map<String, Integer> voted = PollAnswer.getCurrentResults();
Message.send("POLLRESULT_HEADER", player, voted.values().stream().reduce(Integer::sum), PollSystem.getQuestion()); Message.send("POLLRESULT_HEADER", player, voted.values().stream().reduce(Integer::sum).orElse(0), PollSystem.getQuestion());
for (Map.Entry<String, Integer> e: voted.entrySet()) { for (Map.Entry<String, Integer> e: voted.entrySet()) {
Message.send("POLLRESULT_LIST", sender, e.getKey(), e.getValue()); Message.send("POLLRESULT_LIST", sender, e.getKey(), e.getValue());
} }

Datei anzeigen

@ -0,0 +1,115 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
public class PunishmentCommand {
public PunishmentCommand(String command, Punishment.PunishmentType punishmentType) {
new BasicCommand(command, "bungeecore.ban") {
@Override
public void execute(CommandSender sender, String[] args) {
if (punishmentType.isNeedsAdmin() && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) {
return;
}
if (args.length < 3) {
Message.send("PUNISHMENT_USAGE", sender, command);
return;
}
SteamwarUser target = unsafeUser(sender, args[0]);
if (target == null)
return;
Timestamp banTime = parseTime(sender, args[1]);
if (banTime == null)
return;
StringBuilder reason = new StringBuilder();
for (int i = 2; i < args.length; i++) {
reason.append(args[i]).append(" ");
}
boolean isPerma = args[1].equalsIgnoreCase("perma");
String msg = reason.toString();
target.punish(punishmentType, banTime, msg, SteamwarUser.get(sender.getName()).getId(), isPerma);
Message.team(punishmentType.getTeamMessage(), new Message("PREFIX"), target.getUserName(), sender.getName(), new Message((isPerma ? "PUNISHMENT_PERMA" : "PUNISHMENT_UNTIL"), banTime), msg);
}
};
String antiCommand = "un" + command;
new BasicCommand(antiCommand, "bungeecore.ban") {
@Override
public void execute(CommandSender sender, String[] args) {
if (punishmentType.isNeedsAdmin() && !SteamwarUser.get((ProxiedPlayer) sender).getUserGroup().isAdminGroup()) {
return;
}
if (args.length < 1) {
Message.send("UNPUNISHMENT_USAGE", sender, antiCommand);
return;
}
SteamwarUser target = existingUser(sender, args[0]);
if (target == null)
return;
if (!target.isPunished(punishmentType)) {
Message.send(punishmentType.getUsageNotPunished(), sender);
return;
}
Message.send(punishmentType.getUnpunishmentMessage(), sender, target.getUserName());
target.punish(punishmentType, Timestamp.from(new Date().toInstant()), antiCommand, SteamwarUser.get(sender.getName()).getId(), false);
}
};
}
public static Timestamp parseTime(CommandSender sender, String arg) {
if (arg.equalsIgnoreCase("perma")) {
return Timestamp.from(Instant.ofEpochSecond(946674800));
} else {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy_HH:mm");
try {
Date parsedDate = dateFormat.parse(arg);
return new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException e) {
dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try {
Date parsedDate = dateFormat.parse(arg.split("_")[0]);
return new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException exception) {
if (sender != null) {
Message.send("INVALID_TIME", sender);
}
return null;
}
}
}
}
}

Datei anzeigen

@ -22,6 +22,7 @@ package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.IgnoreSystem; import de.steamwar.bungeecore.sql.IgnoreSystem;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -44,8 +45,7 @@ public class RCommand extends BasicCommand {
} }
SteamwarUser user = SteamwarUser.get(player); SteamwarUser user = SteamwarUser.get(player);
if(user.isMuted()){ if (user.isPunishedWithMessage(player, Punishment.PunishmentType.Mute)) {
sender.sendMessage(user.muteMessage(player));
return; return;
} }

Datei anzeigen

@ -49,11 +49,14 @@ public class RankedCommand extends BasicCommand {
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if(!(sender instanceof ProxiedPlayer)) {
return;
}
if(args.length < 1){ if(args.length < 1){
getModes(sender, "/ranked "); getModes(sender, "/ranked ");
return; return;
}else if(!(sender instanceof ProxiedPlayer)) }
return;
ArenaMode mode = FightCommand.getMode(sender, args[0]); ArenaMode mode = FightCommand.getMode(sender, args[0]);
if(mode == null) if(mode == null)

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.listeners.ChatListener; import de.steamwar.bungeecore.listeners.ChatListener;
@ -28,6 +29,8 @@ import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.logging.Level;
public class ServerTeamchatCommand extends BasicCommand { public class ServerTeamchatCommand extends BasicCommand {
public ServerTeamchatCommand() { public ServerTeamchatCommand() {
@ -51,7 +54,11 @@ public class ServerTeamchatCommand extends BasicCommand {
String msg = msgBuilder.toString(); String msg = msgBuilder.toString();
msg = ChatColor.translateAlternateColorCodes('&', msg); msg = ChatColor.translateAlternateColorCodes('&', msg);
try {
SteamwarDiscordBot.instance().getServerTeamChatListener().send("<t:" + (System.currentTimeMillis() / 1000) + "> " + (player.getName() + "» " + msg).replaceAll("§[a-f0-9r]", "")); SteamwarDiscordBot.instance().getServerTeamChatListener().send("<t:" + (System.currentTimeMillis() / 1000) + "> " + (player.getName() + "» " + msg).replaceAll("§[a-f0-9r]", ""));
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send stc message to discord", e);
}
sendToTeam(msg, player); sendToTeam(msg, player);
} }
} }

Datei anzeigen

@ -19,8 +19,8 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.LoadEvaluation;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.Node;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -36,34 +36,22 @@ public class StatCommand extends BasicCommand {
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
Map<String, Integer> serverCount = new HashMap<>();
try { try {
Process process = new ProcessBuilder("ps", "x").start(); Process process = new ProcessBuilder("ps", "x").start();
process.waitFor(); new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(s -> {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); if (!s.contains("--port"))
Map<String, Integer> serverCounts = new HashMap<>();
bufferedReader.lines().forEach(s -> {
if (!s.contains("--port")) {
return; return;
} serverCount.compute(
String server = "SW"; s.contains("ssh -L") ? s.substring(s.indexOf("ssh -L") + 6).split(" ")[2] : "local",
if (s.contains("ssh -L")) { (server, count) -> (count != null ? count : 0) + 1
server = s.substring(s.indexOf("ssh -L") + 6).split(" ")[2]; );
}
serverCounts.put(server, serverCounts.computeIfAbsent(server, s1 -> 0) + 1);
}); });
serverCounts.forEach((s, integer) -> {
if (s.equals("SW")) {
Message.send("STAT_SERVER", sender, s, LoadEvaluation.getRamPercentage(), LoadEvaluation.getCPULoad(), integer);
} else {
Message.send("STAT_SERVER", sender, s.toUpperCase(), LoadEvaluation.getRemoteRamPercentage(s), LoadEvaluation.getRemoteCPULoad(s), integer);
}
});
if (serverCounts.isEmpty()) {
Message.send("NO_STATS", sender);
}
} catch (Exception e) { } catch (Exception e) {
throw new SecurityException(e.getMessage(), e); throw new SecurityException(e.getMessage(), e);
} }
Node.forEach(node -> Message.send("STAT_SERVER", sender, node.getName(), node.getLoad(), serverCount.getOrDefault(node.getName(), 0)));
} }
} }

Datei anzeigen

@ -441,10 +441,7 @@ public class TeamCommand extends BasicCommand {
Set<Event> events = TeamTeilnahme.getEvents(team.getTeamId()); Set<Event> events = TeamTeilnahme.getEvents(team.getTeamId());
if(!events.isEmpty()){ if(!events.isEmpty()){
StringBuilder sb = new StringBuilder(); Message.sendPrefixless("TEAM_INFO_EVENTS", player, events.stream().map(Event::getEventName).collect(Collectors.joining(", ")));
for(Event e : events)
sb.append(e.getEventName()).append(" ");
Message.sendPrefixless("TEAM_INFO_EVENTS", player, sb.toString());
} }
} }

Datei anzeigen

@ -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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.CommandSender;
import java.sql.Timestamp;
import java.util.Date;
public class UnbanCommand extends BasicCommand {
public UnbanCommand() {
super("unban", "bungeecore.ban");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(args.length < 1){
Message.send("UNBAN_USAGE", sender);
return;
}
SteamwarUser target = existingUser(sender, args[0]);
if(target == null)
return;
if(!target.isBanned()) {
Message.send("UNBAN_NOT_BANNED", sender);
return;
}
Message.send("UNBAN_UNBANNED", sender, target.getUserName());
target.ban(Timestamp.from(new Date().toInstant()), "Unban", SteamwarUser.get(sender.getName()).getId(), false);
}
}

Datei anzeigen

@ -31,4 +31,8 @@ public class PacketIdManager {
public static final byte INVENTORY_PACKET = 0x10; public static final byte INVENTORY_PACKET = 0x10;
public static final byte INVENTORY_CALLBACK_PACKET = 0x11; public static final byte INVENTORY_CALLBACK_PACKET = 0x11;
public static final byte INVENTORY_CLOSE_PACKET = 0x12; public static final byte INVENTORY_CLOSE_PACKET = 0x12;
//0x2(X) Server Information System
public static final byte I_AM_A_LOBBY = 0x20;
public static final byte FIGHT_INFO = 0x21;
} }

Datei anzeigen

@ -20,8 +20,9 @@
package de.steamwar.bungeecore.comms; package de.steamwar.bungeecore.comms;
import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataInput;
import net.md_5.bungee.api.config.ServerInfo;
public interface SpigotHandler { public interface SpigotHandler {
void handle(ByteArrayDataInput byteArrayDataInput); void handle(ByteArrayDataInput in, ServerInfo info);
} }

Datei anzeigen

@ -21,10 +21,9 @@ package de.steamwar.bungeecore.comms;
import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import de.steamwar.bungeecore.comms.handlers.InventoryCallbackHandler; import de.steamwar.bungeecore.comms.handlers.*;
import de.steamwar.bungeecore.comms.handlers.PrepareSchemHandler;
import de.steamwar.bungeecore.comms.handlers.TablistNameHandler;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.PluginMessageEvent; import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
@ -39,14 +38,14 @@ public class SpigotReceiver extends BasicListener {
public void onPluginMessage(PluginMessageEvent event) { public void onPluginMessage(PluginMessageEvent event) {
if(!event.getTag().equalsIgnoreCase("sw:bridge")) if(!event.getTag().equalsIgnoreCase("sw:bridge"))
return; return;
if(!event.getSender().getAddress().getHostName().equals("localhost")){
event.setCancelled(true); event.setCancelled(true);
if(!(event.getSender() instanceof Server))
return; return;
}
ByteArrayDataInput in = ByteStreams.newDataInput(event.getData()); ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());
Byte handler = in.readByte(); Byte handler = in.readByte();
handlerMap.get(handler).handle(in); handlerMap.get(handler).handle(in, ((Server) event.getSender()).getInfo());
event.setCancelled(true);
} }
public static void registerHandler(Byte id, SpigotHandler handler) { public static void registerHandler(Byte id, SpigotHandler handler) {
@ -55,7 +54,9 @@ public class SpigotReceiver extends BasicListener {
static { static {
registerHandler(PacketIdManager.INVENTORY_CALLBACK_PACKET, new InventoryCallbackHandler()); registerHandler(PacketIdManager.INVENTORY_CALLBACK_PACKET, new InventoryCallbackHandler());
registerHandler(PacketIdManager.TABLIST_NAME, new TablistNameHandler()); registerHandler(PacketIdManager.TABLIST_NAME, (in, info) -> {});
registerHandler(PacketIdManager.PREPARE_SCHEM, new PrepareSchemHandler()); registerHandler(PacketIdManager.PREPARE_SCHEM, new PrepareSchemHandler());
registerHandler(PacketIdManager.I_AM_A_LOBBY, new ImALobbyHandler());
registerHandler(PacketIdManager.FIGHT_INFO, new FightInfoHandler());
} }
} }

Datei anzeigen

@ -0,0 +1,60 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.comms.handlers;
import com.google.common.io.ByteArrayDataInput;
import de.steamwar.bungeecore.comms.SpigotHandler;
import de.steamwar.bungeecore.comms.packets.FightInfoPacket;
import de.steamwar.bungeecore.listeners.TablistManager;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class FightInfoHandler implements SpigotHandler {
private static final Set<ServerInfo> lobbys = new HashSet<>();
public static void addLobby(ServerInfo lobby) {
lobbys.add(lobby);
}
@Override
public void handle(ByteArrayDataInput in, ServerInfo info) {
FightInfoPacket packet = new FightInfoPacket(in);
packet.setServerName(info.getName());
TablistManager.newFightInfo(info, packet);
Iterator<ServerInfo> lobbyIt = lobbys.iterator();
while(lobbyIt.hasNext()) {
ServerInfo lobby = lobbyIt.next();
Iterator<ProxiedPlayer> it = lobby.getPlayers().iterator();
if(!it.hasNext()){
lobbyIt.remove();
continue;
}
packet.send(it.next());
}
}
}

Datei anzeigen

@ -0,0 +1,32 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.comms.handlers;
import com.google.common.io.ByteArrayDataInput;
import de.steamwar.bungeecore.comms.SpigotHandler;
import net.md_5.bungee.api.config.ServerInfo;
public class ImALobbyHandler implements SpigotHandler {
@Override
public void handle(ByteArrayDataInput in, ServerInfo info) {
FightInfoHandler.addLobby(info);
}
}

Datei anzeigen

@ -27,6 +27,7 @@ import de.steamwar.bungeecore.inventory.InvCallback;
import de.steamwar.bungeecore.inventory.SWInventory; import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -36,9 +37,9 @@ public class InventoryCallbackHandler implements SpigotHandler {
public static final Map<Integer, SWInventory> inventoryHashMap = new HashMap<>(); public static final Map<Integer, SWInventory> inventoryHashMap = new HashMap<>();
@Override @Override
public void handle(ByteArrayDataInput byteArrayDataInput) { public void handle(ByteArrayDataInput in, ServerInfo info) {
SteamwarUser owner = SteamwarUser.get(byteArrayDataInput.readInt()); SteamwarUser owner = SteamwarUser.get(in.readInt());
CallbackType type = CallbackType.valueOf(byteArrayDataInput.readUTF()); CallbackType type = CallbackType.valueOf(in.readUTF());
if(!inventoryHashMap.containsKey(owner.getId())) { if(!inventoryHashMap.containsKey(owner.getId())) {
BungeeCore.send(ProxyServer.getInstance().getPlayer(owner.getUuid()), BungeeCore.CHAT_PREFIX + "§cBitte erneut versuchen. Durch ein Softwareupdate konnte die übliche Aktion nicht durchgeführt werden."); BungeeCore.send(ProxyServer.getInstance().getPlayer(owner.getUuid()), BungeeCore.CHAT_PREFIX + "§cBitte erneut versuchen. Durch ein Softwareupdate konnte die übliche Aktion nicht durchgeführt werden.");
if(type == CallbackType.CLICK) { if(type == CallbackType.CLICK) {
@ -47,8 +48,8 @@ public class InventoryCallbackHandler implements SpigotHandler {
return; return;
} }
if(type == CallbackType.CLICK) { if(type == CallbackType.CLICK) {
int pos = byteArrayDataInput.readInt(); int pos = in.readInt();
InvCallback.ClickType clickType = InvCallback.ClickType.valueOf(byteArrayDataInput.readUTF()); InvCallback.ClickType clickType = InvCallback.ClickType.valueOf(in.readUTF());
inventoryHashMap.get(owner.getId()).handleCallback(clickType, pos); inventoryHashMap.get(owner.getId()).handleCallback(clickType, pos);
}else if(type == CallbackType.CLOSE) { }else if(type == CallbackType.CLOSE) {
if(inventoryHashMap.get(owner.getId()).isNext()) { if(inventoryHashMap.get(owner.getId()).isNext()) {

Datei anzeigen

@ -27,14 +27,15 @@ import de.steamwar.bungeecore.comms.SpigotHandler;
import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SchematicType;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
public class PrepareSchemHandler implements SpigotHandler { public class PrepareSchemHandler implements SpigotHandler {
@Override @Override
public void handle(ByteArrayDataInput byteArrayDataInput) { public void handle(ByteArrayDataInput in, ServerInfo info) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(byteArrayDataInput.readInt()).getUuid()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(in.readInt()).getUuid());
int schematicID = byteArrayDataInput.readInt(); int schematicID = in.readInt();
ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(byteArrayDataInput.readUTF())); ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(in.readUTF()));
BauCommand.stopBauserver(player); BauCommand.stopBauserver(player);
SubserverSystem.startTestServer(player, mode, mode.getRandomMap(), 0, schematicID); SubserverSystem.startTestServer(player, mode, mode.getRandomMap(), 0, schematicID);

Datei anzeigen

@ -1,20 +0,0 @@
package de.steamwar.bungeecore.comms.handlers;
import com.google.common.io.ByteArrayDataInput;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.comms.SpigotHandler;
import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class TablistNameHandler implements SpigotHandler {
@Override
public void handle(ByteArrayDataInput byteArrayDataInput) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(byteArrayDataInput.readInt()).getUuid());
Subserver subserver = Subserver.getSubserver(player.getServer().getInfo());
if(subserver == null)
return;
subserver.getTablistNames().put(player, byteArrayDataInput.readUTF());
}
}

Datei anzeigen

@ -0,0 +1,183 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.comms.packets;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import de.steamwar.bungeecore.comms.BungeePacket;
import de.steamwar.bungeecore.comms.PacketIdManager;
import java.util.ArrayList;
import java.util.List;
public class FightInfoPacket extends BungeePacket {
private String serverName; // Name of the Server
private final String gameMode; // GameMode aka Schematictype (if known, else "")
private final String arena; // Name of the arena
private final String blueName; // Name of the blue team, expected to begin with "§a" colorcode
private final String redName; // Name of the red team, expected to begin with "§a" colorcode
private final String fightState; // Fight state (technical term) (if known, else "")
private final int countdown; // Countdown state in seconds (if known, else 0)
private final int blueLeader; // SWUserID of the blue team leader (if known, else 0)
private final int redLeader; // SWUserID of the red team leader (if known, else 0)
private final int blueSchem; // Blue SchemID (if known, else 0)
private final int redSchem; // Red SchemID (if known, else 0)
private final List<Integer> bluePlayers; // List of Blue SWUserIDs
private final List<Integer> redPlayers; // List of Red SWUserIDs
private final List<Integer> spectators; // List of Spectator SWUserIDs
public FightInfoPacket(String serverName, String gameMode, String arena, String blueName, String redName, String fightState, int countdown, int blueLeader, int redLeader, int blueSchem, int redSchem, List<Integer> bluePlayers, List<Integer> redPlayers, List<Integer> spectators) {
this.serverName = serverName;
this.gameMode = gameMode;
this.arena = arena;
this.blueName = blueName;
this.redName = redName;
this.fightState = fightState;
this.countdown = countdown;
this.blueLeader = blueLeader;
this.redLeader = redLeader;
this.blueSchem = blueSchem;
this.redSchem = redSchem;
this.bluePlayers = bluePlayers;
this.redPlayers = redPlayers;
this.spectators = spectators;
}
public FightInfoPacket(ByteArrayDataInput in) {
this.serverName = in.readUTF();
this.gameMode = in.readUTF();
this.arena = in.readUTF();
this.blueName = in.readUTF();
this.redName = in.readUTF();
this.fightState = in.readUTF();
this.countdown = in.readInt();
this.blueLeader = in.readInt();
this.redLeader = in.readInt();
this.blueSchem = in.readInt();
this.redSchem = in.readInt();
this.bluePlayers = readPlayerList(in);
this.redPlayers = readPlayerList(in);
this.spectators = readPlayerList(in);
}
@Override
public int getId() {
return PacketIdManager.FIGHT_INFO;
}
@Override
public void writeVars(ByteArrayDataOutput out) {
out.writeUTF(serverName);
out.writeUTF(gameMode);
out.writeUTF(arena);
out.writeUTF(blueName);
out.writeUTF(redName);
out.writeUTF(fightState);
out.writeInt(countdown);
out.writeInt(blueLeader);
out.writeInt(redLeader);
out.writeInt(blueSchem);
out.writeInt(redSchem);
writePlayerList(out, bluePlayers);
writePlayerList(out, redPlayers);
writePlayerList(out, spectators);
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getGameMode() {
return gameMode;
}
public String getArena() {
return arena;
}
public String getBlueName() {
return blueName;
}
public String getRedName() {
return redName;
}
public String getFightState() {
return fightState;
}
public int getCountdown() {
return countdown;
}
public int getBlueLeader() {
return blueLeader;
}
public int getRedLeader() {
return redLeader;
}
public int getBlueSchem() {
return blueSchem;
}
public int getRedSchem() {
return redSchem;
}
public List<Integer> getBluePlayers() {
return bluePlayers;
}
public List<Integer> getRedPlayers() {
return redPlayers;
}
public List<Integer> getSpectators() {
return spectators;
}
public int playerSize(){
return bluePlayers.size() + redPlayers.size() + spectators.size();
}
private static List<Integer> readPlayerList(ByteArrayDataInput in) {
int length = in.readInt();
List<Integer> players = new ArrayList<>(length);
for(int i = 0; i < length; i++) {
players.add(in.readInt());
}
return players;
}
private void writePlayerList(ByteArrayDataOutput out, List<Integer> players) {
out.writeInt(players.size());
for(Integer player : players) {
out.writeInt(player);
}
}
}

Datei anzeigen

@ -19,8 +19,6 @@
package de.steamwar.bungeecore.inventory; package de.steamwar.bungeecore.inventory;
import de.steamwar.bungeecore.sql.Schematic;
import de.steamwar.bungeecore.sql.SchematicType;
import net.md_5.bungee.BungeeCord; import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -103,27 +101,6 @@ public class SWListInv<T> extends SWInventory {
return onlinePlayers; return onlinePlayers;
} }
public static List<SWListEntry<Schematic>> getSchemList(SchematicType type, int steamwarUserId){
List<SWListEntry<Schematic>> schemList = new ArrayList<>();
List<Schematic> schems;
if(type == null)
schems = Schematic.getSchemsAccessibleByUser(steamwarUserId);
else
schems = Schematic.getSchemsOfType(steamwarUserId, type);
for(Schematic s : schems){
String m;
if(s.getSchemItem().isEmpty())
m = "CAULDRON_ITEM";
else
m = s.getSchemItem();
SWItem item = new SWItem(m, "§e" + s.getSchemName());
schemList.add(new SWListEntry<>(item, s));
}
return schemList;
}
public static class SWListEntry<T>{ public static class SWListEntry<T>{
final SWItem item; final SWItem item;
final T object; final T object;

Datei anzeigen

@ -41,10 +41,10 @@ public class BanListener extends BasicListener {
@EventHandler @EventHandler
public void onLogin(LoginEvent event) { public void onLogin(LoginEvent event) {
SteamwarUser user = SteamwarUser.getOrCreate(event.getConnection()); SteamwarUser user = SteamwarUser.getOrCreate(event.getConnection());
if(user.isBanned()) { if (user.isPunished(Punishment.PunishmentType.Ban)) {
user.updateBanIP(event.getConnection().getAddress().getAddress().getHostAddress()); user.updateBanIP(event.getConnection().getAddress().getAddress().getHostAddress());
event.setCancelled(true); event.setCancelled(true);
event.setCancelReason(user.banMessage(ProxyServer.getInstance().getPlayer(event.getConnection().getUniqueId()))); event.setCancelReason(user.punishmentMessage(Punishment.PunishmentType.Ban, ProxyServer.getInstance().getPlayer(event.getConnection().getUniqueId())));
return; return;
} }
@ -55,7 +55,7 @@ public class BanListener extends BasicListener {
boolean perma = false; boolean perma = false;
for(BannedUserIPs banned : ips) { for(BannedUserIPs banned : ips) {
SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID()); SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID());
if(bannedUser.isBanned()) { if (bannedUser.isPunished(Punishment.PunishmentType.Ban)) {
Punishment ban = bannedUser.getPunishment(Punishment.PunishmentType.Ban); Punishment ban = bannedUser.getPunishment(Punishment.PunishmentType.Ban);
if(ban.isPerma()) { if(ban.isPerma()) {
perma = true; perma = true;

Datei anzeigen

@ -21,9 +21,9 @@ package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot; import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.listeners.IngameChatListener;
import de.steamwar.bungeecore.commands.TpCommand; import de.steamwar.bungeecore.commands.TpCommand;
import de.steamwar.bungeecore.comms.packets.PingPacket; import de.steamwar.bungeecore.comms.packets.PingPacket;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import de.steamwar.bungeecore.sql.Team; import de.steamwar.bungeecore.sql.Team;
import de.steamwar.bungeecore.sql.UserGroup; import de.steamwar.bungeecore.sql.UserGroup;
@ -36,8 +36,11 @@ import net.md_5.bungee.api.event.TabCompleteResponseEvent;
import net.md_5.bungee.api.scheduler.TaskScheduler; import net.md_5.bungee.api.scheduler.TaskScheduler;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class ChatListener extends BasicListener { public class ChatListener extends BasicListener {
@ -46,6 +49,12 @@ public class ChatListener extends BasicListener {
@EventHandler @EventHandler
public void onChatEvent(ChatEvent e){ public void onChatEvent(ChatEvent e){
if(e.getMessage().contains("jndi:ldap")) {
e.setCancelled(true);
SteamwarUser.get(((ProxiedPlayer) e.getSender()).getUniqueId()).punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.ofEpochSecond(946674800)), "Versuchte Exploit-Ausnutzung", 0, true);
return;
}
sanitize7(e); sanitize7(e);
if(e.getMessage().startsWith("/")) if(e.getMessage().startsWith("/"))
onCommand(e); onCommand(e);
@ -145,13 +154,12 @@ public class ChatListener extends BasicListener {
} }
SteamwarUser user = SteamwarUser.get(sender); SteamwarUser user = SteamwarUser.get(sender);
if(user.isMuted()){ if (user.isPunishedWithMessage(sender, Punishment.PunishmentType.Mute)) {
sender.sendMessage(user.muteMessage(sender));
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
if(!sender.hasPermission(ConnectionListener.TEAM_GROUP) && (e.getMessage().contains("http") || e.getMessage().contains("www"))){ if(!sender.hasPermission(ConnectionListener.TEAM_GROUP) && (e.getMessage().contains("http:") || e.getMessage().contains("https:") || e.getMessage().contains("www."))){
Message.send("CHAT_NO_LINKS", sender); Message.send("CHAT_NO_LINKS", sender);
e.setCancelled(true); e.setCancelled(true);
return; return;
@ -204,7 +212,11 @@ public class ChatListener extends BasicListener {
msg = "§" + team.getTeamColor() + team.getTeamKuerzel() + " §r" + msg; msg = "§" + team.getTeamColor() + team.getTeamKuerzel() + " §r" + msg;
} }
try {
SteamwarDiscordBot.instance().getIngameChatListener().send("<t:" + (System.currentTimeMillis() / 1000) + "> " + msg.replaceAll("§[a-f0-9r]", "")); SteamwarDiscordBot.instance().getIngameChatListener().send("<t:" + (System.currentTimeMillis() / 1000) + "> " + msg.replaceAll("§[a-f0-9r]", ""));
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send chat message to discord", e);
}
for(ProxiedPlayer target : ProxyServer.getInstance().getPlayers()){ for(ProxiedPlayer target : ProxyServer.getInstance().getPlayers()){
Subserver targetServer = Subserver.getSubserver(target); Subserver targetServer = Subserver.getSubserver(target);
if(!(targetServer == null || targetServer.getType() != Servertype.ARENA || targetServer.getServer() != target.getServer().getInfo())) continue; if(!(targetServer == null || targetServer.getType() != Servertype.ARENA || targetServer.getServer() != target.getServer().getInfo())) continue;
@ -224,8 +236,7 @@ public class ChatListener extends BasicListener {
} }
SteamwarUser user = SteamwarUser.get(sender); SteamwarUser user = SteamwarUser.get(sender);
if(user.isMuted()){ if (user.isPunishedWithMessage(sender, Punishment.PunishmentType.Mute)) {
sender.sendMessage(user.muteMessage(sender));
e.setCancelled(true); e.setCancelled(true);
return; return;
} }

Datei anzeigen

@ -21,7 +21,7 @@ package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.commands.CheckCommand; import de.steamwar.bungeecore.commands.CheckCommand;
import de.steamwar.bungeecore.sql.Schematic; import de.steamwar.bungeecore.sql.SchematicNode;
import de.steamwar.bungeecore.sql.SchematicType; import de.steamwar.bungeecore.sql.SchematicType;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -40,10 +40,10 @@ public class CheckListener extends BasicListener {
ProxiedPlayer player = e.getPlayer(); ProxiedPlayer player = e.getPlayer();
SteamwarUser user = SteamwarUser.get(player.getUniqueId()); SteamwarUser user = SteamwarUser.get(player.getUniqueId());
List<Schematic> uncheckedSchematics = new LinkedList<>(); List<SchematicNode> uncheckedSchematics = new LinkedList<>();
for(SchematicType type : SchematicType.values()){ for(SchematicType type : SchematicType.values()){
if(type.check()) if(type.check())
uncheckedSchematics.addAll(Schematic.getSchemsOfType(user.getId(), type)); uncheckedSchematics.addAll(SchematicNode.getAllSchematicsOfType(user.getId(), type.toDB()));
} }
if(!uncheckedSchematics.isEmpty()) if(!uncheckedSchematics.isEmpty())

Datei anzeigen

@ -26,13 +26,12 @@ import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.comms.packets.FightInfoPacket;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import de.steamwar.bungeecore.sql.Team;
import de.steamwar.bungeecore.sql.UserGroup; import de.steamwar.bungeecore.sql.UserGroup;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
@ -42,69 +41,11 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class TablistManager extends BasicListener { public class TablistManager extends BasicListener {
private static final Map<ProxiedPlayer, Tablist> tablists = new HashMap<>(); private static final Map<ProxiedPlayer, Tablist> tablists = new HashMap<>();
private int seconds = 0;
private Icon darkGray;
private Icon gray;
private int size;
private final TreeMap<String, List<ProxiedPlayer>> playerMap = new TreeMap<>();
public TablistManager(){
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::updateCustomTablist, 1, 1, TimeUnit.SECONDS);
try{
BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/dark_gray.png")), (icon) -> darkGray = icon);
BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/gray.png")), (icon) -> gray = icon);
}catch(IOException e){
throw new SecurityException("Could not load icons", e);
}
for(ProxiedPlayer p : ProxyServer.getInstance().getPlayers()){
tablists.put(p, new Tablist(p));
}
}
private void calculateSize() {
size = -1;
size += playerMap.size() * 2 + ProxyServer.getInstance().getPlayers().size();
size = (size + 19) / 20;
if(size > 5) size = 5;
}
private synchronized void updateCustomTablist(){
//Calculate server-player-map
playerMap.clear();
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) {
Server pserver = player.getServer();
if (pserver == null) //Happens temporarily
continue;
ServerInfo server = pserver.getInfo();
String serverName = server.getName();
Subserver subserver = Subserver.getSubserver(server);
if (subserver != null && subserver.getType() == Servertype.BAUSERVER) {
playerMap.computeIfAbsent("Bau", s -> new ArrayList<>()).add(player);
} else {
playerMap.computeIfAbsent(serverName, s -> new ArrayList<>()).add(player);
}
}
playerMap.forEach((server, players) -> players.sort((proxiedPlayer, t1) -> proxiedPlayer.getName().compareToIgnoreCase(t1.getName())));
//Set size
calculateSize();
for(Tablist tablist : tablists.values())
tablist.refresh();
seconds++;
}
@EventHandler @EventHandler
public synchronized void onJoin(PostLoginEvent e){ public synchronized void onJoin(PostLoginEvent e){
tablists.put(e.getPlayer(), new Tablist(e.getPlayer())); tablists.put(e.getPlayer(), new Tablist(e.getPlayer()));
@ -115,15 +56,68 @@ public class TablistManager extends BasicListener {
tablists.remove(e.getPlayer()); tablists.remove(e.getPlayer());
} }
private static final Map<ServerInfo, FightInfoPacket> fightInfos = new HashMap<>();
public static synchronized void newFightInfo(ServerInfo info, FightInfoPacket packet) {
fightInfos.put(info, packet);
fightInfos.keySet().removeIf(serverInfo -> serverInfo.getPlayers().isEmpty());
}
private static Icon darkGray;
private static Icon gray;
private int seconds = 0;
private int size;
private TablistGroup tablist;
public TablistManager(){
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::updateTablist, 1, 1, TimeUnit.SECONDS);
try{
BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/dark_gray.png")), (icon) -> darkGray = icon);
BungeeTabListPlusAPI.createIcon(ImageIO.read(new File("/configs/BungeeTabListPlus/heads/colors/gray.png")), (icon) -> gray = icon);
}catch(IOException e){
throw new SecurityException("Could not load icons", e);
}
ProxyServer.getInstance().getPlayers().forEach(p -> tablists.put(p, new Tablist(p)));
}
private synchronized void updateTablist(){
//Calculate server-player-map
tablist = new TablistGroup(true, "");
TablistGroup bau = new TablistGroup(false, "Bau");
for (ServerInfo server : ProxyServer.getInstance().getServersCopy().values()){
if(server.getPlayers().isEmpty())
continue;
Subserver subserver = Subserver.getSubserver(server);
if(subserver != null && subserver.getType() == Servertype.BAUSERVER)
bau.addSubTablist(new TablistServer(server));
else if(fightInfos.containsKey(server))
tablist.addSubTablist(new TablistServer(server, fightInfos.get(server)));
else
tablist.addSubTablist(new TablistServer(server));
}
if(bau.size() > 0)
tablist.addSubTablist(bau);
size = (int) Math.ceil((tablist.size() - 1) / 20.0);
tablists.values().forEach(Tablist::refresh);
seconds++;
}
private class Tablist extends DefaultCustomTablist { private class Tablist extends DefaultCustomTablist {
private final ProxiedPlayer player; private final ProxiedPlayer player;
private int pos = 0;
private Tablist(ProxiedPlayer player){ private Tablist(ProxiedPlayer player){
this.player = player; this.player = player;
BungeeTabListPlusAPI.setCustomTabList(player, this); BungeeTabListPlusAPI.setCustomTabList(player, this);
} }
private String calcHeader(ProxiedPlayer player){ private String header(){
int phase = (seconds % 16) / 3; int phase = (seconds % 16) / 3;
switch(phase){ switch(phase){
case 0: case 0:
@ -136,7 +130,7 @@ public class TablistManager extends BasicListener {
} }
} }
private String getPing(){ private String ping(){
int ping = player.getPing(); int ping = player.getPing();
if(ping < 50){ if(ping < 50){
return "§a" + ping; return "§a" + ping;
@ -151,126 +145,182 @@ public class TablistManager extends BasicListener {
if (player.getServer() == null) { if (player.getServer() == null) {
return; return;
} }
ServerInfo currentServer = player.getServer().getInfo(); pos = 0;
setHeader(calcHeader(player)); setHeader(header());
// TABLIST_FOOTER=§e{0} {1}§8ms §eSpieler§8: §7{2} setFooter("§e" + player.getServer().getInfo().getName() + " " + ping() + "§8ms §eSpieler§8: §7" + ProxyServer.getInstance().getPlayers().size());
setFooter("§e" + currentServer.getName() + " " + getPing() + "§8ms §eSpieler§8: §7" + ProxyServer.getInstance().getPlayers().size()); int currentSize = size > 4 ? tablist.slimSize(player) : size;
setSize(size, 20); setSize(currentSize, 20);
if (size >= 5) { tablist.print(this, size > 4);
refreshSlim(currentServer);
while (pos < currentSize*20){
setSlot(darkGray, "", 1000);
}
}
private void setSlot(Icon icon, String name, int ping){
if(pos / 20 >= getColumns())
return; return;
}
try { setSlot(pos % 20, pos / 20, icon, name, ping);
int i = 0; pos++;
for (String server : playerMap.navigableKeySet()) {
if (i > 0){
setSlot(i%20, i/20, darkGray, "", 1000);
i++;
}
if(server.equals("Bau"))
server = Message.parse("TABLIST_BAU", player);
setSlot(i%20, i/20, gray, "§7§l" + server, 1000);
i++;
i = update(currentServer, playerMap.get(server), i);
}
finish(i);
}catch(IndexOutOfBoundsException | NullPointerException e){
//Ignore IndexOutOfBoundsException
//Ignore NPE, happens sometimes (only 1s long) when somebody is joining, server switching or disconnecting
} }
} }
private void refreshSlim(ServerInfo currentServer) { private interface TablistPart {
try { int size();
int i = 0; int slimSize(ProxiedPlayer viewer);
boolean spacer = true; String name();
for (String server : playerMap.navigableKeySet()) { void print(Tablist viewer, boolean slim);
if (i > 0 && spacer) {
setSlot(i%20, i/20, darkGray, "", 1000);
i++;
}
spacer = true;
Team team = getTeam(player);
List<ProxiedPlayer> players = playerMap.get(server)
.stream()
.filter(p -> (p.getServer() != null && p.getServer().getInfo() == currentServer) || SteamwarUser.get(p).getUserGroup() != UserGroup.Member || (team != null && team == getTeam(p)))
.collect(Collectors.toList());
Subserver subserver = Subserver.getSubserver(player);
if (server.equals("Bau")) {
if (subserver != null && subserver.getType() == Servertype.BAUSERVER) {
players = playerMap.get(server);
}
server = Message.parse("TABLIST_BAU", player);
}
if (subserver != null && subserver.getType() == Servertype.ARENA && playerMap.get(server).size() == 1) {
players = playerMap.get(server);
} }
int increment = playerMap.get(server).size() - players.size(); private static class TablistGroup implements TablistPart {
if (players.isEmpty()) {
server += " §7(" + increment + ")"; private final boolean withHeaders;
spacer = false; private final String orderName;
} else if (increment != 0) { private final List<TablistPart> subTablists = new ArrayList<>();
server += " §7(+" + increment + ")";
private TablistGroup(boolean withHeaders, String orderName) {
this.withHeaders = withHeaders;
this.orderName = orderName;
} }
setSlot(i%20, i/20, gray, "§7§l" + server, 1000); private void addSubTablist(TablistPart tablist){
i++; subTablists.add(tablist);
i = update(currentServer, players, i); subTablists.sort((t1, t2) -> t1.name().compareToIgnoreCase(t2.name()));
} }
finish(i); @Override
}catch(IndexOutOfBoundsException | NullPointerException e){ public int size() {
//Ignore IndexOutOfBoundsException return slimSize(null);
//Ignore NPE, happens sometimes (only 1s long) when somebody is joining, server switching or disconnecting
}
} }
private int update(ServerInfo currentServer, List<ProxiedPlayer> players, int i) { @Override
for (ProxiedPlayer p : players){ public int slimSize(ProxiedPlayer viewer) {
boolean sameServer = currentServer == p.getServer().getInfo(); return subTablists.stream().mapToInt(tPart -> viewer == null ? tPart.size() : tPart.slimSize(viewer)).map(size -> {
setSlot(i % 20, i / 20, BungeeTabListPlusAPI.getIconFromPlayer(p), getTablistName(p), (sameServer ? 1 : 500)); size += withHeaders ? 1 : 0; // Space for header
i++; size += withHeaders && size > 1 ? 1 : 0; // Space for footer
} return size;
return i; }).sum();
} }
private void finish(int i) { @Override
while (i < size*20){ public String name() {
setSlot(i%20, i/20, darkGray, "", 1000); return orderName;
i++;
}
} }
private Team getTeam(ProxiedPlayer p) { @Override
Team team = Team.get(SteamwarUser.get(p).getTeam()); public void print(Tablist viewer, boolean slim) {
return team.getTeamId() <= 0 ? null : team; for (int i = 0; i < subTablists.size(); i++) {
} TablistPart tPart = subTablists.get(i);
boolean withoutFooter = i == subTablists.size() - 1;
private String getTablistName(ProxiedPlayer p) { if (withHeaders) {
Subserver server = Subserver.getSubserver(p); if (slim) {
if(server != null){ int slimSize = tPart.slimSize(viewer.player);
String tablistName = server.getTablistNames().get(p); int size = tPart.size();
if(tablistName != null) if (size == slimSize) {
return tablistName; viewer.setSlot(gray, "§7§l" + tPart.name(), 1000);
} } else if (slimSize == 0) {
viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7" + size + "§8)", 1000);
StringBuilder st = new StringBuilder(); withoutFooter = true;
UserGroup group = SteamwarUser.get(p).getUserGroup();
if (group == UserGroup.Member) {
Team team = getTeam(player);
if (team != null && team == getTeam(p)) st.append("§f");
else st.append("§7");
} else { } else {
st.append(group.getColorCode()); viewer.setSlot(gray, "§7§l" + tPart.name() + " §8(§7+" + (size - slimSize) + "§8)", 1000);
}
} else {
viewer.setSlot(gray, "§7§l" + tPart.name(), 1000);
}
}
tPart.print(viewer, slim);
if (withHeaders && !withoutFooter) {
viewer.setSlot(darkGray, "", 1000);
}
}
}
}
private static class TablistServer implements TablistPart {
private static class TablistPlayer {
private final ProxiedPlayer player;
private final String defaultName;
private TablistPlayer(ProxiedPlayer player, String defaultName) {
this.player = player;
this.defaultName = defaultName;
}
}
private final List<TablistPlayer> players = new ArrayList<>();
private final ServerInfo info;
private final Subserver subserver;
private TablistServer(ServerInfo info, FightInfoPacket packet){
this.info = info;
subserver = Subserver.getSubserver(info);
Collection<ProxiedPlayer> onlinePlayers = info.getPlayers();
addPlayers(packet.getBlueName().substring(0, 2), packet.getBluePlayers(), onlinePlayers);
addPlayers(packet.getRedName().substring(0, 2), packet.getRedPlayers(), onlinePlayers);
addPlayers("§7", packet.getSpectators(), onlinePlayers);
} }
return st.append(p.getName()).toString(); private void addPlayers(String prefix, List<Integer> teamPlayers, Collection<ProxiedPlayer> onlinePlayers){
teamPlayers.stream().map(SteamwarUser::get).map(
user -> onlinePlayers.stream().filter(player -> player.getUniqueId().equals(user.getUuid())).findAny()
).filter(Optional::isPresent).map(Optional::get).sorted(
(p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName())
).forEachOrdered(player -> players.add(new TablistPlayer(player, prefix + player.getName())));
}
private TablistServer(ServerInfo info) {
this.info = info;
subserver = Subserver.getSubserver(info);
info.getPlayers().forEach(player -> players.add(new TablistPlayer(player, SteamwarUser.get(player.getUniqueId()).getUserGroup().getColorCode() + player.getName())));
players.sort((tp1, tp2) -> tp1.player.getName().compareToIgnoreCase(tp2.player.getName()));
}
private boolean displaySlim(ProxiedPlayer viewer, ProxiedPlayer player){
if(viewer.getServer().getInfo() == info)
return true;
if(subserver != null && subserver.getType() == Servertype.ARENA && info.getPlayers().size() == 1)
return true;
SteamwarUser user = SteamwarUser.get(player);
if(user.getUserGroup() != UserGroup.Member)
return true;
return user.getTeam() != 0 && SteamwarUser.get(viewer).getTeam() == user.getTeam();
}
@Override
public int size() {
return players.size();
}
@Override
public int slimSize(ProxiedPlayer viewer) {
if(viewer.getServer().getInfo() == info)
return size();
return players.stream().mapToInt(player -> displaySlim(viewer, player.player) ? 1 : 0).sum();
}
@Override
public String name() {
return info.getName();
}
@Override
public void print(Tablist viewer, boolean slim) {
boolean sameServer = viewer.player.getServer().getInfo() == info;
SteamwarUser user = SteamwarUser.get(viewer.player.getUniqueId());
for(TablistPlayer player : players){
if(slim && !displaySlim(viewer.player, player.player))
continue;
int ping = sameServer ? 1 : 500;
String name = player.defaultName.startsWith("§7") && user.getTeam() != 0 && user.getTeam() == SteamwarUser.get(player.player.getUniqueId()).getTeam() ? "§f" + player.player.getName() : player.defaultName;
viewer.setSlot(BungeeTabListPlusAPI.getIconFromPlayer(player.player), name, ping);
}
} }
} }
} }

Datei anzeigen

@ -23,6 +23,7 @@ import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.sql.Mod; import de.steamwar.bungeecore.sql.Mod;
import de.steamwar.bungeecore.sql.Mod.ModType; import de.steamwar.bungeecore.sql.Mod.ModType;
import de.steamwar.bungeecore.sql.Punishment;
import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.SteamwarUser;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -75,7 +76,7 @@ class Utils {
if(max == ModType.YELLOW) if(max == ModType.YELLOW)
player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_SING", player, mods.get(0).getModName()))); player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_SING", player, mods.get(0).getModName())));
else{ else{
user.ban(Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_SING", player, mods.get(0).getModName()), 0, false); user.punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_SING", player, mods.get(0).getModName()), 0, false);
BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen des Mods " + mods.get(0).getModName() + " gebannt."); BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen des Mods " + mods.get(0).getModName() + " gebannt.");
} }
}else{ }else{
@ -85,7 +86,7 @@ class Utils {
if(max == ModType.YELLOW) if(max == ModType.YELLOW)
player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_PLUR", player, sb.toString()))); player.disconnect(BungeeCore.stringToText(Message.parse("MOD_YELLOW_PLUR", player, sb.toString())));
else{ else{
user.ban(Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_PLUR", player, sb.toString()), 0, false); user.punish(Punishment.PunishmentType.Ban, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), Message.parse("MOD_RED_PLUR", player, sb.toString()), 0, false);
BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + sb.toString() + " gebannt."); BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + sb.toString() + " gebannt.");
} }
} }

Datei anzeigen

@ -24,51 +24,97 @@ import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
public class CheckedSchematic { public class CheckedSchematic {
private static final Statement create = new Statement("INSERT INTO CheckedSchematic (SchemName, SchemOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?)"); private static final Statement checkHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId IN (SELECT NodeId FROM SchematicNode WHERE NodeOwner = ?) AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' AND NodeId is not NULL ORDER BY EndTime DESC");
private static final Statement previous = new Statement("SELECT * FROM CheckedSchematic WHERE SchemName = ? AND SchemOwner = ? ORDER BY EndTime ASC"); private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC");
private static final Statement insert = new Statement("INSERT INTO CheckedSchematic (NodeId, NodeName, NodeOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?, ?)");
private final String schemName;
private final int schemOwner;
private final Integer node;
private final int validator; private final int validator;
private final Timestamp startTime; private final Timestamp startTime;
private final Timestamp endTime; private final Timestamp endTime;
private final String reason; private final String declineReason;
private CheckedSchematic(ResultSet rs) throws SQLException { private CheckedSchematic(ResultSet rs) throws SQLException {
schemName = rs.getString("SchemName"); this.node = rs.getInt("NodeId");
schemOwner = rs.getInt("SchemOwner"); this.validator = rs.getInt("Validator");
validator = rs.getInt("Validator"); this.startTime = rs.getTimestamp("StartTime");
startTime = rs.getTimestamp("StartTime"); this.endTime = rs.getTimestamp("EndTime");
endTime = rs.getTimestamp("EndTime"); this.declineReason = rs.getString("DeclineReason");
reason = rs.getString("DeclineReason");
} }
public static void create(String schemName, int schemOwner, int validator, Timestamp startTime, Timestamp endTime, String reason){ public static void create(int nodeId, String name, int owner, int validator, Timestamp startTime, Timestamp endTime, String reason){
create.update(schemName, schemOwner, validator, startTime, endTime, reason); insert.update(nodeId, name, owner, validator, startTime, endTime, reason);
} }
public static List<CheckedSchematic> previousChecks(String schemName, int schemOwner){ public static void create(SchematicNode node, int validator, Timestamp startTime, Timestamp endTime, String reason){
return previous.select(rs -> { create(node.getId(), node.getName(), node.getOwner(), validator, startTime, endTime, reason);
}
public static List<CheckedSchematic> previousChecks(SchematicNode node){
return nodeHistory.select(rs -> {
List<CheckedSchematic> schematics = new ArrayList<>(); List<CheckedSchematic> schematics = new ArrayList<>();
while(rs.next()) while(rs.next())
schematics.add(new CheckedSchematic(rs)); schematics.add(new CheckedSchematic(rs));
return schematics; return schematics;
}, schemName, schemOwner); }, node.getId());
}
public static List<CheckedSchematic> getLastDeclinedOfNode(SchematicNode node){
return getLastDeclinedOfNode(node.getId());
}
public static List<CheckedSchematic> getLastDeclinedOfNode(int node){
return nodeHistory.select(rs -> {
List<CheckedSchematic> lastDeclined = new ArrayList<>();
while(rs.next()){
lastDeclined.add(new CheckedSchematic(rs));
}
return lastDeclined;
}, node);
}
public static List<CheckedSchematic> getLastDeclined(UUID uuid){
return getLastDelined(SteamwarUser.get(uuid).getId());
}
public static List<CheckedSchematic> getLastDelined(int schemOwner){
return checkHistory.select(rs -> {
List<CheckedSchematic> history = new ArrayList<>();
while(rs.next())
history.add(new CheckedSchematic(rs));
return history;
}, schemOwner);
} }
public int getValidator() { public int getValidator() {
return validator; return validator;
} }
public Timestamp getStartTime() {
return startTime;
}
public Timestamp getEndTime() { public Timestamp getEndTime() {
return endTime; return endTime;
} }
public String getReason() { public String getDeclineReason() {
return reason; return declineReason;
}
public int getNode() {
return node;
}
public String getSchemName() {
return SchematicNode.getSchematicNode(node).getName();
}
public int getSchemOwner() {
return SchematicNode.getSchematicNode(node).getId();
} }
} }

Datei anzeigen

@ -0,0 +1,84 @@
/*
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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.sql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
public class NodeMember {
private static final Statement getNodeMember = new Statement("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?");
private static final Statement getNodeMembers = new Statement("SELECT * FROM NodeMember WHERE NodeId = ?");
private static final Statement getSchematics = new Statement("SELECT * FROM NodeMember WHERE UserId = ?");
private static final Statement createNodeMember = new Statement("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)");
private static final Statement deleteNodeMember = new Statement("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?");
public static NodeMember getNodeMember(int node, int member) {
return getNodeMember.select(rs -> {
if(!rs.next())
return null;
return new NodeMember(rs);
}, node, member);
}
public static Set<NodeMember> getNodeMembers(int node) {
return getNodeMembers.select(rs -> {
Set<NodeMember> members = new HashSet<>();
while (rs.next())
members.add(new NodeMember(rs));
return members;
}, node);
}
public static Set<NodeMember> getSchematics(int member) {
return getSchematics.select(rs -> {
Set<NodeMember> members = new HashSet<>();
while (rs.next())
members.add(new NodeMember(rs));
return members;
}, member);
}
public static NodeMember createNodeMember(int node, int member) {
createNodeMember.update(node, member);
return getNodeMember(node, member);
}
final int node;
final int member;
private NodeMember(ResultSet set) throws SQLException {
node = set.getInt("NodeId");
member = set.getInt("UserId");
}
public int getNode() {
return node;
}
public int getMember() {
return member;
}
public void delete() {
deleteNodeMember.update(node, member);
}
}

Datei anzeigen

@ -58,7 +58,7 @@ public class PollAnswer {
return getResults.select(rs -> { return getResults.select(rs -> {
Map<String, Integer> retMap = new HashMap<>(); Map<String, Integer> retMap = new HashMap<>();
while (rs.next()) while (rs.next())
retMap.put(PollSystem.getAnswer(rs.getInt("Answer")), rs.getInt("Times")); retMap.put(PollSystem.getAnswer(rs.getInt("Answer")-1), rs.getInt("Times"));
return retMap; return retMap;
}, PollSystem.getQuestion()); }, PollSystem.getQuestion());
} }

Datei anzeigen

@ -19,9 +19,8 @@
package de.steamwar.bungeecore.sql; package de.steamwar.bungeecore.sql;
import de.steamwar.bungeecore.BungeeCore; import lombok.AllArgsConstructor;
import de.steamwar.bungeecore.Message; import lombok.Getter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -35,7 +34,6 @@ public class Punishment {
private static final Statement getPunishments = new Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); private static final Statement getPunishments = new Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)");
private static final Statement getAllPunishments = new Statement("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC"); private static final Statement getAllPunishments = new Statement("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC");
private static final Statement insert = new Statement("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)"); private static final Statement insert = new Statement("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)");
private static final Statement update = new Statement("UPDATE Punishments SET EndTime = ?, Reason = ?, Perma = ? WHERE PunishmentId = ?");
public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) {
return getPunishment.select(rs -> { return getPunishment.select(rs -> {
@ -116,35 +114,33 @@ public class Punishment {
return perma; return perma;
} }
public void updateEndTime(int from, String newreason, Timestamp newUpdate, boolean perma) {
if(newreason.equals(reason) && newUpdate.equals(endTime) && this.perma == perma)
return;
ProxiedPlayer player = BungeeCore.get().getProxy().getPlayer(SteamwarUser.get(from).getUuid());
String newReason = Message.parse("BAN_CHANGED", player, reason,
SteamwarUser.get(from).getUserName(),
getBantime(endTime, this.perma),
getBantime(newUpdate, perma),
newreason);
update.update(newUpdate, newReason, perma, id);
this.reason = newReason;
this.perma = perma;
this.endTime = newUpdate;
}
public String getBantime(Timestamp endTime, boolean perma) { public String getBantime(Timestamp endTime, boolean perma) {
if(perma) if (perma) {
return "permanent"; return "permanent";
else } else {
return endTime.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")); return endTime.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"));
} }
}
public boolean isCurrent() { public boolean isCurrent() {
return isPerma() || getEndTime().after(new Date()); return isPerma() || getEndTime().after(new Date());
} }
@AllArgsConstructor
@Getter
public enum PunishmentType { public enum PunishmentType {
Ban, Ban(false, "BAN_TEAM", "BAN_PERMA", "BAN_UNTIL", "UNBAN_ERROR", "UNBAN"),
Mute; 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;
} }
} }

Datei anzeigen

@ -1,127 +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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.sql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Schematic {
private static final Statement schemByName = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemName = ? AND SchemOwner = ?");
private static final Statement schemById = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemID = ?");
private static final Statement schemsByType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?");
private static final Statement schemsByUserType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ? AND SchemOwner = ?");
private static final Statement schemsOfUser = new Statement("SELECT SchemID, SchemName, SchemOwner, Item, SchemType, Rank, SchemFormat, Item FROM Schematic WHERE SchemOwner = ? ORDER BY SchemName");
private static final Statement updateType = new Statement("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?");
private static final Statement updateRank = new Statement("UPDATE Schematic SET Rank = ? WHERE SchemID = ?");
private final int schemID;
private final String schemName;
private final int schemOwner;
private SchematicType schemType;
private final String schemItem;
private Schematic(ResultSet rs) throws SQLException {
this.schemID = rs.getInt("SchemID");
this.schemName = rs.getString("SchemName");
this.schemOwner = rs.getInt("SchemOwner");
this.schemType = SchematicType.fromDB(rs.getString("SchemType"));
this.schemItem = rs.getString("Item");
}
public static Schematic getSchemFromDB(String schemName, int schemOwner){
return schemByName.select(rs -> {
if(!rs.next())
return new Schematic(rs);
return null;
}, schemName, schemOwner);
}
public static Schematic getSchemFromDB(int schemID){
return schemById.select(rs -> {
if(!rs.next())
throw new SecurityException("Failed loading schematic " + schemID);
return new Schematic(rs);
}, schemID);
}
public static List<Schematic> getAllSchemsOfType(SchematicType schemType){
return schemsByType.select(rs -> {
List<Schematic> schematics = new ArrayList<>();
while(rs.next())
schematics.add(new Schematic(rs));
return schematics;
}, schemType.toDB());
}
public static List<Schematic> getSchemsOfType(int userId, SchematicType schemType){
return schemsByUserType.select(rs -> {
List<Schematic> schematics = new ArrayList<>();
while(rs.next())
schematics.add(new Schematic(rs));
return schematics;
}, schemType.toDB(), userId);
}
public static List<Schematic> getSchemsAccessibleByUser(int schemOwner){
return schemsOfUser.select(rs -> {
List<Schematic> schematics = new ArrayList<>();
while(rs.next()){
schematics.add(new Schematic(rs));
}
List<SchematicMember> addedSchems = SchematicMember.getAccessibleSchems(schemOwner);
for(SchematicMember schem : addedSchems){
schematics.add(getSchemFromDB(schem.getSchemName(), schem.getSchemOwner()));
}
return schematics;
}, schemOwner);
}
public int getSchemID() {
return schemID;
}
public String getSchemName() {
return schemName;
}
public int getSchemOwner() {
return schemOwner;
}
public String getSchemItem() {
return schemItem;
}
public SchematicType getSchemType() {
return schemType;
}
public void setSchemType(SchematicType schemType) {
this.schemType = schemType;
updateType.update(schemType.toDB(), schemID);
}
public void setRank(int rank) {
updateRank.update(rank, schemID);
}
}

Datei anzeigen

@ -1,71 +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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.sql;
import java.util.ArrayList;
import java.util.List;
public class SchematicMember {
private static final Statement insert = new Statement("INSERT INTO SchemMember (SchemName, SchemOwner, Member) VALUES (?, ?, ?)");
private static final Statement selectSchems = new Statement("SELECT * FROM SchemMember WHERE Member = ?");
private static final Statement delete = new Statement("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?");
private final int schemOwner;
private final String schemName;
private final int member;
private SchematicMember(String schemName, int schemOwner, int schemMember, boolean updateDB){
this.schemOwner = schemOwner;
member = schemMember;
this.schemName = schemName;
if(updateDB)
updateDB();
}
private void updateDB(){
insert.update(schemName, schemOwner, member);
}
public static List<SchematicMember> getAccessibleSchems(int schemMember){
return selectSchems.select(rs -> {
List<SchematicMember> schematicMembers = new ArrayList<>();
while(rs.next())
schematicMembers.add(new SchematicMember(rs.getString("SchemName"), rs.getInt("SchemOwner"), schemMember, false));
return schematicMembers;
}, schemMember);
}
public int getSchemOwner() {
return schemOwner;
}
public String getSchemName() {
return schemName;
}
public int getMember() {
return member;
}
public void remove(){
delete.update(schemOwner, schemName, member);
}
}

Datei anzeigen

@ -0,0 +1,470 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.sql;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
public class SchematicNode {
private static final Statement createNode = new Statement("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)");
private static final Statement getSchematicNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL");
private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?");
private static final Statement getSchematicsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL");
private static final Statement getSchematicsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ?");
private static final Statement getDirsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL AND NodeType is NULL");
private static final Statement getDirsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? AND NodeType is NULL");
private static final Statement getSchematicDirectory_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL");
private static final Statement getSchematicDirectory = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?");
private static final Statement getSchematicNodeO_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL");
private static final Statement getSchematicNodeO = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ?");
private static final Statement getSchematicNodeId = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?");
private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ?");
private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ?");
private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND ((s.NodeOwner = ? AND s.ParentNode IS NULL) OR NOT s.NodeOwner = ?) GROUP BY s.NodeId ORDER BY s.NodeName");
private static final Statement getAccessibleByUserByTypeInNode = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ?");
private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null");
private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ?");
private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN");
private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN LEFT Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1");
private static final Statement getAllParentsOfNode = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? UNION SELECT SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN");
private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode");
private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?");
private static final Statement updateDatabase = new Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?");
private static final Statement selSchemData = new Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?");
private static final Statement deleteNode = new Statement("DELETE FROM SchematicNode WHERE NodeId = ?");
public static SchematicNode createSchematic(int owner, String name, Integer parent) {
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;
createNode.update(name, owner, parent, type, item);
return getSchematicNode(owner, name, parent);
}
private Timestamp lastUpdate;
public static SchematicNode getSchematicNode(int owner, String name, SchematicNode parent) {
return getSchematicNode(owner, name, parent.getId());
}
private SchematicNode(ResultSet set) throws SQLException {
id = set.getInt("NodeId");
owner = set.getInt("NodeOwner");
name = set.getString("NodeName");
parent = set.getInt("ParentNode");
if(set.wasNull()) {
parent = null;
}
item = set.getString("NodeItem");
type = set.getString("NodeType");
lastUpdate = set.getTimestamp("LastUpdate");
if (type != null) {
isDir = false;
rank = set.getInt("NodeRank");
schemFormat = set.getBoolean("NodeFormat");
} else {
isDir = true;
}
}
public static List<SchematicNode> 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;
}
Statement.ResultSetUser<SchematicNode> user = rs -> {
while (rs.next()) {
SchematicNode node = new SchematicNode(rs);
return node;
}
return null;
};
if(parent == null) {
return getSchematicNode_Null.select(user, owner, name);
} else {
return getSchematicNode.select(user, owner, name, parent);
}
}
public static List<SchematicNode> getSchematicNodeInNode(Integer parent) {
if(parent != null && parent == 0)
parent = null;
Statement.ResultSetUser<List<SchematicNode>> user = rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next())
nodes.add(new SchematicNode(rs));
return nodes;
};
if(parent == null) {
return getSchematicsInNode_Null.select(user);
}else {
return getSchematicsInNode.select(user, parent);
}
}
public static List<SchematicNode> getSchematicDirectoryInNode(Integer parent) {
if(parent != null && parent == 0)
parent = null;
Statement.ResultSetUser<List<SchematicNode>> user = rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next())
nodes.add(new SchematicNode(rs));
return nodes;
};
if(parent == null) {
return getDirsInNode_Null.select(user);
}else {
return getDirsInNode.select(user, parent);
}
}
public static SchematicNode getSchematicDirectory(String name, Integer parent) {
if(parent != null && parent == 0)
parent = null;
Statement.ResultSetUser<SchematicNode> user = rs -> {
while (rs.next()) {
SchematicNode node = new SchematicNode(rs);
if(node.isDir())
return node;
}
return null;
};
if(parent == null) {
return getSchematicDirectory_Null.select(user, name);
}else {
return getSchematicDirectory.select(user, name, parent);
}
}
public static SchematicNode getSchematicNode(String name, Integer parent) {
if(parent != null && parent == 0)
parent = null;
Statement.ResultSetUser<SchematicNode> user = rs -> {
while (rs.next()) {
return new SchematicNode(rs);
}
return null;
};
if(parent == null) {
return getSchematicNodeO_Null.select(user, name);
}else {
return getSchematicNodeO.select(user, name, parent);
}
}
public static SchematicNode getSchematicNode(int id) {
return getSchematicNodeId.select(rs -> {
if (!rs.next())
return null;
return new SchematicNode(rs);
}, id);
}
public static List<SchematicNode> getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) {
Statement.ResultSetUser<List<SchematicNode>> user = rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next()) {
nodes.add(new SchematicNode(rs));
}
return nodes;
};
if(parent == null || parent == 0) {
return getAccessibleByUserByTypeInNode_Null.select(user, owner, owner, schemType);
} else {
return getAccessibleByUserByTypeInNode.select(user, owner, owner, schemType, parent);
}
}
public static List<SchematicNode> getAllAccessibleSchematicsOfType(int user, String schemType) {
return getAccessibleByUserByType.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next()) {
nodes.add(new SchematicNode(rs));
}
return nodes;
}, user, user, schemType);
}
public static List<SchematicNode> getAllSchematicsOfType(int owner, String schemType) {
return getAllSchemsOfTypeOwner.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next())
nodes.add(new SchematicNode(rs));
return nodes;
}, owner, schemType);
}
public static List<SchematicNode> getAllSchematicsOfType(String schemType) {
return getAllSchemsOfType.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while (rs.next())
nodes.add(new SchematicNode(rs));
return nodes;
}, schemType);
}
public static List<SchematicNode> deepGet(Integer parent, Predicate<SchematicNode> filter) {
List<SchematicNode> finalList = new ArrayList<>();
List<SchematicNode> 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<SchematicNode> getSchematicsAccessibleByUser(int user, Integer parent) {
if (parent != null && parent != 0) {
if(isSchematicAccessibleForUser.select(rs -> {
rs.next();
return rs.getInt("Accessible") > 0;
}, parent, user, user))
return getSchematicNodeInNode(parent);
} else {
return getAccessibleByUser.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while(rs.next())
nodes.add(new SchematicNode(rs));
return nodes;
}, user, user, user, user);
}
return Collections.emptyList();
}
public static List<SchematicNode> getAllSchematicsAccessibleByUser(int user) {
return getAllSchematicsAccessibleByUser.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while(rs.next()) {
nodes.add(new SchematicNode(rs));
}
return nodes;
}, user, user);
}
public static List<SchematicNode> getAllParentsOfNode(SchematicNode node) {
return getAllParentsOfNode(node.getId());
}
public static List<SchematicNode> getAllParentsOfNode(int node) {
return getAllParentsOfNode.select(rs -> {
List<SchematicNode> nodes = new ArrayList<>();
while(rs.next()) {
nodes.add(new SchematicNode(rs));
}
return nodes;
}, node);
}
private final int id;
private final int owner;
private String name;
private Integer parent;
private String item;
private String type;
private boolean schemFormat;
private int rank;
private final boolean isDir;
private Map<Integer, String> brCache = new HashMap<>();
public static List<SchematicNode> filterSchems(int user, Predicate<SchematicNode> filter) {
List<SchematicNode> finalList = new ArrayList<>();
List<SchematicNode> 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 countNodes.select(rs -> {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
});
}
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() {
return item;
}
public void setItem(String item) {
this.item = item;
updateDB();
}
public String getType() {
if(isDir)
throw new SecurityException("Node is Directory");
return type;
}
public void setType(String type) {
if(isDir)
throw new SecurityException("Node is Directory");
this.type = type;
updateDB();
}
public boolean isDir() {
return isDir;
}
public boolean getSchemFormat() {
if(isDir)
throw new SecurityException("Node is Directory");
return schemFormat;
}
public int getRank() {
if(isDir)
throw new SecurityException("Node is Directory");
return rank;
}
public void setRank(int rank) {
if(isDir)
throw new SecurityException("Node is Directory");
this.rank = rank;
}
public SchematicType getSchemtype() {
if(isDir())
throw new RuntimeException("Is Directory");
return SchematicType.fromDB(type);
}
public SchematicNode getParentNode() {
if(parent == null) return null;
return SchematicNode.getSchematicNode(parent);
}
public boolean accessibleByUser(int user) {
return NodeMember.getNodeMember(id, user) != null;
}
public Set<NodeMember> 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("/");
while (currentNode.getParentNode() != null) {
currentNode = currentNode.getParentNode();
builder.insert(0, split)
.insert(0, currentNode.getName());
if (currentNode.getMembers().stream().anyMatch(member -> member.getMember() == user.getId())) {
break;
}
}
return builder.toString();
}
private void updateDB() {
updateDB.update(name, owner, parent, item, type, rank, id);
this.lastUpdate = Timestamp.from(Instant.now());
this.brCache.clear();
}
public void delete() {
if (isDir()) {
getSchematicNodeInNode(getId()).forEach(SchematicNode::delete);
}
deleteNode.update(id);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SchematicNode))
return false;
SchematicNode node = (SchematicNode) obj;
return node.getId() == id;
}
}

Datei anzeigen

@ -19,7 +19,8 @@
package de.steamwar.bungeecore.sql; package de.steamwar.bungeecore.sql;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.commands.CheckCommand;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration; import net.md_5.bungee.config.YamlConfiguration;
@ -36,17 +37,7 @@ public class SchematicType {
private static final List<SchematicType> types; private static final List<SchematicType> types;
static { static {
File file = new File(BungeeCore.get().getDataFolder(), "SchematicTypes.yml"); File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem");
if(!file.exists())
throw new SecurityException("SchematicType-ConfigFile not found!");
Configuration config;
try {
config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
} catch (IOException e) {
throw new SecurityException("Could not load SchematicTypes", e);
}
List<SchematicType> tmpTypes = new LinkedList<>(); List<SchematicType> tmpTypes = new LinkedList<>();
Map<String, SchematicType> tmpFromDB = new HashMap<>(); Map<String, SchematicType> tmpFromDB = new HashMap<>();
@ -55,16 +46,38 @@ public class SchematicType {
tmpTypes.add(Normal); tmpTypes.add(Normal);
tmpFromDB.put(Normal.name().toLowerCase(), Normal); tmpFromDB.put(Normal.name().toLowerCase(), Normal);
for(String type : config.getKeys()){ if(folder.exists()) {
Configuration section = config.getSection(type); for(File configFile : folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))) {
assert section != null; Configuration config;
String checktype = section.getString("checktype"); try {
SchematicType current = new SchematicType(type, section.getString("kuerzel"), Type.valueOf(section.getString("type")), checktype != null ? tmpFromDB.get(checktype.toLowerCase()) : null); config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
tmpTypes.add(current); } catch (IOException e) {
if(current.checkType != null) throw new SecurityException("Could not load SchematicTypes", e);
tmpFightType.put(current.checkType, current); }
if(!config.contains("Schematic"))
continue;
String type = config.getString("Schematic.Type");
assert type != null;
String shortcut = config.getString("Schematic.Shortcut");
if(tmpFromDB.containsKey(type.toLowerCase()))
continue;
SchematicType checktype = null;
if(!config.getStringList("CheckQuestions").isEmpty()) {
checktype = new SchematicType("C" + type, "C" + shortcut, Type.CHECK_TYPE, null);
tmpTypes.add(checktype);
tmpFromDB.put(checktype.toDB(), checktype);
CheckCommand.setCheckQuestions(checktype, config);
}
SchematicType current = new SchematicType(type, shortcut, config.getKeys().contains("Server") ? Type.FIGHT_TYPE : Type.NORMAL, checktype);
if(checktype != null)
tmpFightType.put(checktype, current);
tmpFromDB.put(type.toLowerCase(), current); tmpFromDB.put(type.toLowerCase(), current);
} }
}
fromDB = Collections.unmodifiableMap(tmpFromDB); fromDB = Collections.unmodifiableMap(tmpFromDB);
fightType = Collections.unmodifiableMap(tmpFightType); fightType = Collections.unmodifiableMap(tmpFightType);
@ -74,7 +87,7 @@ public class SchematicType {
private final String name; private final String name;
private final String kuerzel; private final String kuerzel;
private final Type type; private final Type type;
private SchematicType checkType; private final SchematicType checkType;
private SchematicType(String name, String kuerzel, Type type, SchematicType checkType){ private SchematicType(String name, String kuerzel, Type type, SchematicType checkType){
this.name = name; this.name = name;

Datei anzeigen

@ -40,23 +40,22 @@ public class Statement implements AutoCloseable {
Statement.user = user; Statement.user = user;
Statement.password = password; Statement.password = password;
try { try {
con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); con = DriverManager.getConnection(url + "?autoReconnect=true&useServerPrepStmts=true", user, password);
} catch (SQLException e) { } catch (SQLException e) {
ProxyServer.getInstance().stop(); ProxyServer.getInstance().stop();
throw new SecurityException("Could not start SQL-Connection", e); throw new SecurityException("Could not start SQL-Connection", e);
} }
} }
private static void reset(SQLException e) { private static void reset() {
BungeeCore.get().getLogger().log(Level.WARNING, "SQL Exception thrown", e);
closeAll(); closeAll();
connect(url, user, password); connect(url, user, password);
try { try {
for (Statement statement : statements) { for (Statement statement : statements) {
statement.init(); statement.init();
} }
} catch (SQLException ex) { } catch (SQLException e) {
throw new SecurityException("Could not reprepare SQL Statements", ex); throw new SecurityException("Could not reprepare SQL statements", e);
} }
} }
@ -71,6 +70,7 @@ public class Statement implements AutoCloseable {
} }
public static void closeAll() { public static void closeAll() {
synchronized (statements) {
for (Statement statement : statements) { for (Statement statement : statements) {
try { try {
statement.st.close(); statement.st.close();
@ -82,28 +82,38 @@ public class Statement implements AutoCloseable {
try { try {
con.close(); con.close();
} catch (SQLException e) { } catch (SQLException e) {
BungeeCore.log("Could not close SQL-Connection", e); BungeeCore.get().getLogger().log(Level.INFO, "Could not close SQL connection", e);
}
}
}
public static boolean connectionStable() {
try {
return !con.isClosed();
} catch (SQLException e) {
return false;
} }
} }
private final String sql; private final String sql;
private PreparedStatement st; private PreparedStatement st;
Statement(String sql) { public Statement(String sql) {
this.sql = sql; this.sql = sql;
statements.add(this); statements.add(this);
try { try {
init(); init();
} catch (SQLException e) { } catch (SQLException e) {
reset(e); throw new SecurityException("Could not init SQL statement", e);
} }
} }
private synchronized void init() throws SQLException { private void init() throws SQLException {
st = con.prepareStatement(sql); st = con.prepareStatement(sql);
} }
<T> T select(ResultSetUser<T> user, Object... objects) { public <T> T select(ResultSetUser<T> user, Object... objects) {
synchronized (statements) {
return prepare(() -> { return prepare(() -> {
ResultSet rs = st.executeQuery(); ResultSet rs = st.executeQuery();
T result = user.use(rs); T result = user.use(rs);
@ -111,23 +121,21 @@ public class Statement implements AutoCloseable {
return result; return result;
}, objects); }, objects);
} }
void update(Object... objects) {
prepare(st::executeUpdate, objects);
} }
private synchronized <T> T prepare(SQLRunnable<T> runnable, Object... objects) { public void update(Object... objects) {
synchronized (statements) {
prepare(st::executeUpdate, objects);
}
}
private <T> T prepare(SQLRunnable<T> runnable, Object... objects) {
try { try {
setObjects(objects); setObjects(objects);
return runnable.run(); return runnable.run();
} catch (SQLException e) { } catch (SQLException e) {
reset(e); reset();
try { throw new SecurityException("Could not execute SQL statement", e);
setObjects(objects);
return runnable.run();
} catch (SQLException ex) {
throw new SecurityException("Could not execute SQL statement", ex);
}
} }
} }
@ -137,7 +145,7 @@ public class Statement implements AutoCloseable {
} }
} }
interface ResultSetUser<T> { public interface ResultSetUser<T> {
T use(ResultSet rs) throws SQLException; T use(ResultSet rs) throws SQLException;
} }

Datei anzeigen

@ -61,7 +61,7 @@ public class SteamwarUser {
private static final Map<String, SteamwarUser> usersByName = new HashMap<>(); private static final Map<String, SteamwarUser> usersByName = new HashMap<>();
private static final Map<UUID, SteamwarUser> usersByUUID = new HashMap<>(); private static final Map<UUID, SteamwarUser> usersByUUID = new HashMap<>();
private static final Map<Integer, SteamwarUser> usersById = new HashMap<>(); private static final Map<Integer, SteamwarUser> usersById = new HashMap<>();
private static final Map<String, SteamwarUser> usersByDiscord = new HashMap<>(); private static final Map<Long, SteamwarUser> usersByDiscord = new HashMap<>();
private static final InetAddress LIXFEL_DE; private static final InetAddress LIXFEL_DE;
private static final String API_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static final String API_URL = "https://api.mojang.com/users/profiles/minecraft/";
private static final JsonParser jsonParser = new JsonParser(); private static final JsonParser jsonParser = new JsonParser();
@ -73,7 +73,7 @@ public class SteamwarUser {
private int team; private int team;
private boolean leader; private boolean leader;
private final Map<Punishment.PunishmentType, Punishment> punishments; private final Map<Punishment.PunishmentType, Punishment> punishments;
private String discordId; private Long discordId;
static { static {
try { try {
@ -91,12 +91,16 @@ public class SteamwarUser {
userGroup = UserGroup.getUsergroup(rs.getString("UserGroup")); userGroup = UserGroup.getUsergroup(rs.getString("UserGroup"));
team = rs.getInt("Team"); team = rs.getInt("Team");
leader = rs.getBoolean("Leader"); leader = rs.getBoolean("Leader");
discordId = rs.getString("DiscordId"); discordId = rs.getLong("DiscordId");
if(rs.wasNull()) {
discordId = null;
}
usersById.put(id, this); usersById.put(id, this);
usersByName.put(userName.toLowerCase(), this); usersByName.put(userName.toLowerCase(), this);
usersByUUID.put(uuid, this); usersByUUID.put(uuid, this);
if(discordId != null) if (discordId != null) {
usersByDiscord.put(discordId, this); usersByDiscord.put(discordId, this);
}
punishments = Punishment.getPunishmentsOfPlayer(id); punishments = Punishment.getPunishmentsOfPlayer(id);
} }
@ -112,8 +116,9 @@ public class SteamwarUser {
} }
} else { } else {
user = SteamwarUser.createUserInDatabase(connection.getUniqueId(), connection.getName()); user = SteamwarUser.createUserInDatabase(connection.getUniqueId(), connection.getName());
if(user == null) if (user == null) {
throw new SecurityException("user == null"); throw new SecurityException("user == null");
}
ConnectionListener.newPlayer(user.uuid); ConnectionListener.newPlayer(user.uuid);
} }
@ -133,6 +138,11 @@ public class SteamwarUser {
return null; return null;
} }
user = SteamwarUser.get(uuid);
if (user != null) {
return user;
}
return SteamwarUser.createUserInDatabase(uuid, name); return SteamwarUser.createUserInDatabase(uuid, name);
} }
@ -143,8 +153,9 @@ public class SteamwarUser {
public static SteamwarUser get(String userName) { public static SteamwarUser get(String userName) {
userName = userName.toLowerCase(); userName = userName.toLowerCase();
if(usersByName.containsKey(userName)) if (usersByName.containsKey(userName)) {
return usersByName.get(userName); return usersByName.get(userName);
}
return byName.select(rs -> { return byName.select(rs -> {
if (rs.next()) if (rs.next())
return new SteamwarUser(rs); return new SteamwarUser(rs);
@ -153,8 +164,9 @@ public class SteamwarUser {
} }
public static SteamwarUser get(UUID uuid) { public static SteamwarUser get(UUID uuid) {
if(usersByUUID.containsKey(uuid)) if (usersByUUID.containsKey(uuid)) {
return usersByUUID.get(uuid); return usersByUUID.get(uuid);
}
return byUUID.select(rs -> { return byUUID.select(rs -> {
if (rs.next()) if (rs.next())
return new SteamwarUser(rs); return new SteamwarUser(rs);
@ -167,8 +179,9 @@ public class SteamwarUser {
} }
public static SteamwarUser get(int id) { public static SteamwarUser get(int id) {
if(usersById.containsKey(id)) if (usersById.containsKey(id)) {
return usersById.get(id); return usersById.get(id);
}
return byID.select(rs -> { return byID.select(rs -> {
rs.next(); rs.next();
return new SteamwarUser(rs); return new SteamwarUser(rs);
@ -190,8 +203,8 @@ public class SteamwarUser {
} }
public static SteamwarUser get(Long discordId) { public static SteamwarUser get(Long discordId) {
if(usersByDiscord.containsKey(discordId.toString())) if(usersByDiscord.containsKey(discordId))
return usersByDiscord.get(discordId.toString()); return usersByDiscord.get(discordId);
return byDiscord.select(rs -> { return byDiscord.select(rs -> {
if (rs.next()) if (rs.next())
return new SteamwarUser(rs); return new SteamwarUser(rs);
@ -211,8 +224,8 @@ public class SteamwarUser {
final URL url = new URL(API_URL + playerName); final URL url = new URL(API_URL + playerName);
String uuid = jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString(); String uuid = jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString();
return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
} catch (IOException e) { } catch (NoSuchElementException | IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID", e); BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID " + playerName, e);
return null; return null;
} }
} }
@ -247,11 +260,11 @@ public class SteamwarUser {
return punishments.getOrDefault(type, null); return punishments.getOrDefault(type, null);
} }
public String getDiscordId() { public Long getDiscordId() {
return discordId; return discordId;
} }
public void setDiscordId(String discordId) { public void setDiscordId(Long discordId) {
usersByDiscord.remove(this.discordId); usersByDiscord.remove(this.discordId);
this.discordId = discordId; this.discordId = discordId;
updateDiscord.update(discordId, id); updateDiscord.update(discordId, id);
@ -260,43 +273,57 @@ public class SteamwarUser {
} }
} }
public boolean isBanned() { public boolean isPunished(Punishment.PunishmentType punishment) {
if(!punishments.containsKey(Punishment.PunishmentType.Ban)) if (!punishments.containsKey(punishment)) {
return false; return false;
if(!punishments.get(Punishment.PunishmentType.Ban).isCurrent()) { }
if (!punishments.get(punishment).isCurrent()) {
if (punishment == Punishment.PunishmentType.Ban) {
deleteIPs.update(id); deleteIPs.update(id);
punishments.remove(Punishment.PunishmentType.Ban); }
punishments.remove(punishment);
return false; return false;
} }
return true; return true;
} }
public boolean isMuted(){ public boolean isPunishedWithMessage(ProxiedPlayer player, Punishment.PunishmentType punishment) {
if(!punishments.containsKey(Punishment.PunishmentType.Mute)) if (!isPunished(punishment)) {
return false;
if(!punishments.get(Punishment.PunishmentType.Mute).isCurrent()) {
punishments.remove(Punishment.PunishmentType.Mute);
return false; return false;
} }
player.sendMessage(punishmentMessage(punishment, player));
return true; return true;
} }
public TextComponent banMessage(ProxiedPlayer player){ public void punish(Punishment.PunishmentType punishment, Timestamp time, String banReason, int from, boolean perma) {
Punishment punishment = punishments.get(Punishment.PunishmentType.Ban); punishments.remove(punishment);
if (punishment.isPerma()) { punishments.put(punishment, Punishment.createPunishment(id, from, punishment, banReason, time, perma));
return BungeeCore.stringToText(Message.parsePrefixed("BANNED_MESSAGE_PERMA", player, punishment.getReason()));
if (punishment != Punishment.PunishmentType.Ban) {
return;
}
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
if (player != null) {
updateBanIP(player.getAddress().getAddress().getHostAddress());
player.disconnect(punishmentMessage(punishment, player));
for (BannedUserIPs banned : BannedUserIPs.get(player.getAddress().getAddress().getHostAddress())) {
SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID());
if (isPunished(punishment) && bannedUser.getPunishment(punishment).getEndTime().before(time)) {
bannedUser.punish(punishment, time, banReason, from, perma);
}
}
} else { } else {
return BungeeCore.stringToText(Message.parsePrefixed("BANNED_MESSAGE_UNTIL", player, punishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), updateBanIP("");
punishment.getReason()));
} }
} }
public TextComponent muteMessage(ProxiedPlayer player){ public TextComponent punishmentMessage(Punishment.PunishmentType punishment, ProxiedPlayer player) {
Punishment punishment = punishments.get(Punishment.PunishmentType.Mute); Punishment currentPunishment = punishments.get(punishment);
if (punishment.isPerma()) { if (currentPunishment.isPerma()) {
return BungeeCore.stringToText(Message.parsePrefixed("MUTED_MESSAGE_PERMA", player, punishment.getReason())); return BungeeCore.stringToText(Message.parsePrefixed(punishment.getPlayerMessagePerma(), player, currentPunishment.getReason()));
} else { } else {
return BungeeCore.stringToText(Message.parsePrefixed("MUTED_MESSAGE_UNTIL", player, punishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), punishment.getReason())); return BungeeCore.stringToText(Message.parsePrefixed(punishment.getPlayerMessageUntil(), player, currentPunishment.getEndTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(Message.parse("TIMEFORMAT", player))), currentPunishment.getReason()));
} }
} }
@ -304,40 +331,9 @@ public class SteamwarUser {
BannedUserIPs.banIP(this, ip); BannedUserIPs.banIP(this, ip);
} }
public void ban(Timestamp time, String banReason, int from, boolean perma){
if(isBanned()) {
punishments.get(Punishment.PunishmentType.Ban).updateEndTime(from, banReason, time, perma);
return;
}
punishments.remove(Punishment.PunishmentType.Ban);
punishments.put(Punishment.PunishmentType.Ban, Punishment.createPunishment(id, from, Punishment.PunishmentType.Ban, banReason, time, perma));
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
if(player != null){
updateBanIP(player.getAddress().getAddress().getHostAddress());
player.disconnect(banMessage(player));
for (BannedUserIPs banned:
BannedUserIPs.get(player.getAddress().getAddress().getHostAddress())) {
SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID());
if(bannedUser.isBanned() && banned.getTimestamp().before(time))
bannedUser.ban(time, banReason, from, perma);
}
}else
updateBanIP("");
}
public void mute(Timestamp time, String muteReason, int from, boolean perma){
if(isMuted()) {
punishments.get(Punishment.PunishmentType.Mute).updateEndTime(from, muteReason, time, perma);
return;
}
punishments.remove(Punishment.PunishmentType.Mute);
punishments.put(Punishment.PunishmentType.Mute, Punishment.createPunishment(id, from, Punishment.PunishmentType.Mute, muteReason, time, perma));
}
public double getOnlinetime() { public double getOnlinetime() {
return getPlaytime.select(rs -> { return getPlaytime.select(rs -> {
if(rs.next()) if (rs.next() && rs.getBigDecimal("Playtime") != null)
return rs.getBigDecimal("Playtime").doubleValue(); return rs.getBigDecimal("Playtime").doubleValue();
return 0.0; return 0.0;
}, id); }, id);

Datei anzeigen

@ -95,8 +95,6 @@ HELP_BAU_TESTARENA_HOVER=§eTestarena starten
#Usage description of various commands #Usage description of various commands
USAGE_ALERT=§8/§7alert §8[§eNachricht§8] USAGE_ALERT=§8/§7alert §8[§eNachricht§8]
USAGE_BAN=§8/§7ban §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8]
USAGE_MUTE=§8/§7mute §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8]
USAGE_IGNORE=§8/§7ignore §8[§eSpieler§8] USAGE_IGNORE=§8/§7ignore §8[§eSpieler§8]
#ModListener #ModListener
@ -107,25 +105,59 @@ MOD_YELLOW_PLUR=§7Deaktiviere die Mods\n§e{0}\n§7um weiter auf §eSteam§8War
#Various commands #Various commands
ALERT=§f{0} ALERT=§f{0}
STAT_SERVER=§7Server §f{0} - §7Ram §f{1} §7CPU §f{2} §7Server Count §f{3} STAT_SERVER=§7Server §e{0}§8: §7Load §e{1} §7Serveranzahl §e{2}
NO_STATS=§7Kein Bau oder Fight Server gestartet
#Ban&Mute-Command #Ban&Mute-Command
BAN_TEAM_BANNED={0} §c{1} wurde von {2} {3} gebannt. §f§lGrund: §f{4} PUNISHMENT_USAGE=§8/§7{0} §8[§eSpieler§8] [§edd§8.§emm§8.§eyyyy §7oder §edd§8.§emm§8.§eyyyy§8_§ehh§8:§emm §7oder §eperma§8] [§eGrund§8]
BANNED_MESSAGE_PERMA=§cDu bist permanent gebannt. §r§lGrund§r: §c{0} UNPUNISHMENT_USAGE=§8/§7{0} §8[§eSpieler§8]
BANNED_MESSAGE_UNTIL=§cDu bist bis zum {0} gebannt. §r§lGrund§r: §c{1}
MUTE_TEAM_MUTED={0} §c{1} wurde von {2} {3} gemuted. §f§lGrund: §f{4} PUNISHMENT_UNTIL=bis zum {0}
MUTED_MESSAGE_PERMA=§cDu bist permanent gemuted. §r§lGrund§r: §c{0} PUNISHMENT_PERMA=permanent
MUTED_MESSAGE_UNTIL=§cDu bist bis zum {0} gemuted. §r§lGrund§r: §c{1}
BAN_CHANGED={0}verändert von {1} von {2} auf {3} wegen {4} BAN_TEAM={0} §e{1} §7wurde von §e{2} {3} §e§lgebannt§8. §7Grund§8: §f{4}
BAN_PERMA=permanent BAN_PERMA=§7Du bist §epermanent §e§lgebannt§8. §7Grund§8: §e{0}
BAN_UNTIL=bis zum {0} BAN_UNTIL=§7Du bist §ebis zum {0} §e§lgebannt§8. §7Grund§8: §e{1}
UNBAN_ERROR=§cDer Spieler ist nicht gebannt.
UNBAN=§7Du hast §e{0} §e§lentbannt.
BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c BAN_AVOIDING_ALERT=§cMögliche Bannumgehung durch §r{0}§c: §c
BAN_AVOIDING_LIST={0} §e{1} §c BAN_AVOIDING_LIST={0} §e{1} §c
BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung BAN_AVOIDING_BAN_HOVER=§cBanne Spieler wegen Bannumgehung
MUTE_TEAM={0} §e{1} §7wurde von §e{2} {3} §e§lgemuted§8. §7Grund§8: §f{4}
MUTE_PERMA=§7Du bist §epermanent §e§lgemuted§8. §7Grund§8: §e{0}
MUTE_UNTIL=§7Du bist §ebis zum {0} §e§lgemuted§8. §7Grund§8: §e{1}
UNMUTE_ERROR=§cDer Spieler ist nicht gemuted.
UNMUTE=§7Du hast §e{0} §e§lentmuted.
NOSCHEMRECEIVING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematicerhalten ausgeschlossen§8. §7Grund§8: §f{4}
NOSCHEMRECEIVING_PERMA=§7Du bist §epermanent §7vom Erhalten von §e§lSchematics ausgeschlossen§8. §7Grund§8: §e{0}
NOSCHEMRECEIVING_UNTIL=§7Du bist §ebis zum {0} §7vom Erhalten von §e§lSchematics ausgeschlossen§8. §7Grund§8: §e{1}
UNNOSCHEMRECEIVING_ERROR=§cDer Spieler ist nicht vom Erhalten von Schematics ausgeschlossen.
UNNOSCHEMRECEIVING=§e{0} §7darf nun wieder §e§lSchematics erhalten§8.
NOSCHEMSHARING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematicverteilen ausgeschlossen§8. §7Grund§8: §f{4}
NOSCHEMSHARING_PERMA=§7Du bist §epermanent §7vom §e§lVerteilen von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{0}
NOSCHEMSHARING_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lVerteilen von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{1}
UNNOSCHEMSHARING_ERROR=§cDer Spieler ist nicht vom Verteilen von Schematics ausgeschlossen.
UNNOSCHEMSHARING=§e{0} §7darf nun wieder §e§lSchematics verteilen§8.
NOSCHEMSUBMITTING_TEAM={0} §e{1} §7wurde von §e{2} {3} §7vom §e§lSchematiceinsenden ausgeschlossen§8. §7Grund§8: §f{4}
NOSCHEMSUBMITTING_PERMA=§7Du bist §epermanent §7vom §e§lEinsenden von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{0}
NOSCHEMSUBMITTING_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lEinsenden von Schematics§7 ausgeschlossen§8. §7Grund§8: §e{1}
UNNOSCHEMSUBMITTING_ERROR=§cDer Spieler ist nicht vom Einsenden von Schematics ausgeschlossen.
UNNOSCHEMSUBMITTING=§e{0} §7darf nun wieder §e§lSchematis einsenden§8.
NODEVSERVER_TEAM={0} §e{1} §7hat §e{2} §7mit Grund §f{4}§7 zu generft und hat daher §e§lDevserververbot §7erhalten§8, §e{3}
NODEVSERVER_PERMA=§7Du bist §epermanent §7vom §e§lDevserver §7ausgeschlossen§8. §7Grund§8: §e{0}
NODEVSERVER_UNTIL=§7Du bist §ebis zum {0} §7vom §e§lDevserver §7ausgeschlossen§8. §7Grund§8: §e{1}
UNNODEVSERVER_ERROR=§cDer Spieler ist nicht vom Devserver ausgeschlossen.
UNNODEVSERVER=§e{0} §7darf nun wieder dem §e§lDevserver beitreten§8.
#BugCommand
BUG_MESSAGE=§7Dein Bugreport wurde gespeichert. BUG_MESSAGE=§7Dein Bugreport wurde gespeichert.
#IgnoreCommand
IGNORE_YOURSELF=§cWie willst du dich selber ignorieren? IGNORE_YOURSELF=§cWie willst du dich selber ignorieren?
IGNORE_ALREADY=§cDu ignorierst diesen Spieler bereits. IGNORE_ALREADY=§cDu ignorierst diesen Spieler bereits.
IGNORE_MESSAGE=§7Du ignorierst nun §e{0}§8. IGNORE_MESSAGE=§7Du ignorierst nun §e{0}§8.
@ -424,11 +456,6 @@ TP_USAGE=§8/§7tp §8[§eSpieler§8]
TP_USAGE_EVENT=§8/§7tp §8[§eSpieler §7oder §eTeam§8] TP_USAGE_EVENT=§8/§7tp §8[§eSpieler §7oder §eTeam§8]
TP_NOT_FOUND=§cKonnte das angegebene Ziel nicht finden. TP_NOT_FOUND=§cKonnte das angegebene Ziel nicht finden.
#UnbanCommand
UNBAN_USAGE=§8/§7unban §8[§eSpieler§8]
UNBAN_NOT_BANNED=§cDer Spieler ist nicht gebannt.
UNBAN_UNBANNED=Du hast {0} entbannt.
#UnignoreCommand #UnignoreCommand
UNIGNORE_USAGE=§8/§7unignore §8[§eSpieler§8] UNIGNORE_USAGE=§8/§7unignore §8[§eSpieler§8]
UNIGNORE_NOT_PLAYER=§cDiesen Spieler gibt es nicht! UNIGNORE_NOT_PLAYER=§cDiesen Spieler gibt es nicht!
@ -523,3 +550,11 @@ VERIFY_SUCCESS=§7Erfolgreich mit dem Discord Account §e{0} §7verknüpft
DISCORD_TICKET_MESSAGE=§7Ticket §e{0}§7» §f§l{1}: §7{2} DISCORD_TICKET_MESSAGE=§7Ticket §e{0}§7» §f§l{1}: §7{2}
DISCORD_TICKET_NEW=§7Ticket §e{0}§7» §aTicket wurde geöffnet! DISCORD_TICKET_NEW=§7Ticket §e{0}§7» §aTicket wurde geöffnet!
DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket wurde geschlossen! DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket wurde geschlossen!
#GDPR Query
GDPR_STATUS_WEBSITE=§7Website kann nicht automatisiert gepackt werden und muss daher manuell hinzugefügt werden.
GDPR_STATUS_WORLD=§7Packe Bauwelten...
GDPR_STATUS_INVENTORIES=§7Suche und packe Inventare...
GDPR_STATUS_DATABASE=§7Packe Datenbankinhalte...
GDPR_STATUS_LOGS=§7Suche und packe logs...
GDPR_STATUS_FINISHED=§7Packen abgeschlossen

6
steamwarci.yml Normale Datei
Datei anzeigen

@ -0,0 +1,6 @@
build:
- "ln -s /home/gitea/lib"
- "mvn package -B"
artifacts:
"/binarys/bungeecore.jar": "target/bungeecore.jar"