SteamWar/BungeeCore
Archiviert
13
2

WIP Velocity: Commands, Discord, Inventory
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed

Signed-off-by: Lixfel <git-5w3l@lixfel.de>
Dieser Commit ist enthalten in:
Lixfel 2024-06-15 23:19:55 +02:00
Ursprung c39e2a0566
Commit ef71323b05
83 geänderte Dateien mit 878 neuen und 906 gelöschten Zeilen

Datei anzeigen

@ -29,7 +29,7 @@ plugins {
id 'java' id 'java'
id 'application' id 'application'
id 'com.github.johnrengelman.shadow' version '5.0.0' id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'de.steamwar.gradle' version 'RELEASE' id 'de.steamwar.gradle' version 'RELEASE'
} }
@ -38,8 +38,10 @@ version ''
compileJava.options.encoding = 'UTF-8' compileJava.options.encoding = 'UTF-8'
sourceCompatibility = 1.8 java {
targetCompatibility = 1.8 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
mainClassName = '' mainClassName = ''
@ -57,6 +59,12 @@ sourceSets {
repositories { repositories {
mavenCentral() mavenCentral()
maven {
url 'https://repo.papermc.io/repository/maven-public/'
content {
includeGroup 'com.velocitypowered'
}
}
maven { maven {
url 'https://m2.dv8tion.net/releases' url 'https://m2.dv8tion.net/releases'
content { content {
@ -86,8 +94,18 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.22' testAnnotationProcessor 'org.projectlombok:lombok:1.18.22'
compileOnly 'de.steamwar:waterfall:RELEASE' compileOnly 'com.velocitypowered:velocity-api:3.3.0-SNAPSHOT'
compileOnly 'de.steamwar:persistentbungeecore:RELEASE' annotationProcessor 'com.velocitypowered:velocity-api:3.3.0-SNAPSHOT'
//compileOnly 'com.velocitypowered:velocity-proxy:3.3.0-SNAPSHOT'
//implementation 'org.reflections:reflections:0.10.2'
compileOnly 'io.netty:netty-buffer:4.1.106.Final'
compileOnly 'io.netty:netty-transport:4.1.106.Final'
implementation 'org.yaml:snakeyaml:2.2'
compileOnly files('persistentvelocitycore.jar')
implementation("net.dv8tion:JDA:4.4.0_352") { implementation("net.dv8tion:JDA:4.4.0_352") {
exclude module: 'opus-java' exclude module: 'opus-java'
} }

Datei anzeigen

@ -1,5 +1,5 @@
#Sat Apr 10 23:34:12 CEST 2021 #Sat Apr 10 23:34:12 CEST 2021
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-all.zip
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

Datei anzeigen

@ -26,6 +26,6 @@ pluginManagement {
} }
} }
rootProject.name = 'BungeeCore' rootProject.name = 'VelocityCore'
include 'CommonCore' include 'CommonCore'

Datei anzeigen

@ -20,6 +20,7 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import de.steamwar.sql.SchematicType; import de.steamwar.sql.SchematicType;
import lombok.Getter;
import net.md_5.bungee.api.ProxyServer; 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;
@ -37,6 +38,7 @@ public class ArenaMode {
private static final Map<String, ArenaMode> byChat = new HashMap<>(); private static final Map<String, ArenaMode> byChat = new HashMap<>();
private static final Map<String, ArenaMode> byInternal = new HashMap<>(); private static final Map<String, ArenaMode> byInternal = new HashMap<>();
private static final Map<SchematicType, ArenaMode> bySchemType = new HashMap<>(); private static final Map<SchematicType, ArenaMode> bySchemType = new HashMap<>();
@Getter
private static final List<ArenaMode> allModes = new LinkedList<>(); private static final List<ArenaMode> allModes = new LinkedList<>();
static { static {
@ -49,9 +51,9 @@ public class ArenaMode {
bySchemType.clear(); bySchemType.clear();
allModes.clear(); allModes.clear();
File folder = new File(ProxyServer.getInstance().getPluginsFolder(), "FightSystem"); File folder = new File(VelocityCore.get().getDataDirectory().getParent().toFile(), "FightSystem");
for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) { for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().toList()) {
Configuration config; Configuration config;
try { try {
config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
@ -94,21 +96,26 @@ public class ArenaMode {
return bySchemType.get(schemType); return bySchemType.get(schemType);
} }
public static List<ArenaMode> getAllModes(){ @Getter
return allModes;
}
private final String displayName; private final String displayName;
@Getter
private final String folder; private final String folder;
private final List<String> chatNames; private final List<String> chatNames;
@Getter
private final String serverJar; private final String serverJar;
@Getter
private final String config; private final String config;
@Getter
private final List<String> maps; private final List<String> maps;
private final Map<String, String> lowerToRealMapNames = new HashMap<>(); private final Map<String, String> lowerToRealMapNames = new HashMap<>();
@Getter
private final boolean historic; private final boolean historic;
@Getter
private final String internalName; private final String internalName;
@Getter
private final boolean ranked; private final boolean ranked;
@Getter
private final String schemType; private final String schemType;
private ArenaMode(String internalName, Configuration config) { private ArenaMode(String internalName, Configuration config) {
@ -135,18 +142,6 @@ public class ArenaMode {
bySchemType.put(SchematicType.fromDB(this.schemType), this); bySchemType.put(SchematicType.fromDB(this.schemType), this);
} }
public String getDisplayName() {
return displayName;
}
public String serverJar() {
return serverJar;
}
public String getConfig(){
return config;
}
public String hasMap(String map){ public String hasMap(String map){
for(String m : maps){ for(String m : maps){
if(m.equalsIgnoreCase(map)) if(m.equalsIgnoreCase(map))
@ -155,18 +150,10 @@ public class ArenaMode {
return null; return null;
} }
public String getFolder() {
return folder;
}
public String getRandomMap(){ public String getRandomMap(){
return maps.get(random.nextInt(maps.size())); return maps.get(random.nextInt(maps.size()));
} }
public List<String> getMaps() {
return maps;
}
public String convertToRealMapName(String map){ public String convertToRealMapName(String map){
return lowerToRealMapNames.get(map.toLowerCase()); return lowerToRealMapNames.get(map.toLowerCase());
} }
@ -179,19 +166,4 @@ public class ArenaMode {
return chatNames.isEmpty(); return chatNames.isEmpty();
} }
public boolean isHistoric(){
return historic;
}
public boolean isRanked() {
return ranked;
}
public String getSchemType() {
return schemType;
}
public String getInternalName() {
return internalName;
}
} }

Datei anzeigen

@ -20,27 +20,25 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.ProxyServer;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
class Broadcaster { class Broadcaster {
private static String [] broadCastMsgs; private final List<String> broadcasts = VelocityCore.get().getConfig().getBroadcasts();
private int lastBroadCast = 0; private int lastBroadCast = 0;
Broadcaster() { Broadcaster() {
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { if(!broadcasts.isEmpty())
if(!ProxyServer.getInstance().getPlayers().isEmpty() && broadCastMsgs.length > 0) VelocityCore.schedule(this::broadcast).repeat(10, TimeUnit.MINUTES).schedule();
Chatter.broadcast().system("PLAIN_STRING", broadCastMsgs[lastBroadCast]);
lastBroadCast++;
if(lastBroadCast == broadCastMsgs.length){
lastBroadCast = 0;
}
}, 10, 10, TimeUnit.MINUTES);
} }
static void setBroadCastMsgs(String[] broadCastMsgs) { private void broadcast() {
Broadcaster.broadCastMsgs = broadCastMsgs; if(!VelocityCore.getProxy().getAllPlayers().isEmpty())
Chatter.broadcast().system("PLAIN_STRING", broadcasts.get(lastBroadCast++));
if(lastBroadCast == broadcasts.size())
lastBroadCast = 0;
} }
} }

Datei anzeigen

@ -0,0 +1,74 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 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 com.velocitypowered.api.proxy.server.RegisteredServer;
import lombok.Getter;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
@Getter
public class Config {
public static Config load() {
TypeDescription typeDescription = new TypeDescription(Config.class);
typeDescription.addPropertyParameters("servers", String.class, Config.Server.class);
Constructor constructor = new Constructor(Config.class, new LoaderOptions());
constructor.addTypeDescription(typeDescription);
try{
return new Yaml(constructor).load(new FileInputStream(new File(VelocityCore.get().getDataDirectory().toFile(), "config.yml")));
}catch(IOException e){
VelocityCore.getProxy().shutdown();
throw new SecurityException("Could not load config.yml", e);
}
}
private String lobbyserver;
private boolean eventmode = false;
private Map<String, Server> servers = Collections.emptyMap();
private List<String> broadcasts = Collections.emptyList();
private Poll poll = null;
public RegisteredServer lobbyserver() {
return VelocityCore.getProxy().getServer(lobbyserver).orElseThrow();
}
@Getter
public static class Poll {
private String question;
private List<String> answers;
}
@Getter
public static class Server {
private String permission = "user";
private int spectatePort = 0;
private List<String> commands;
}
}

Datei anzeigen

@ -22,8 +22,7 @@ package de.steamwar.bungeecore;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.sql.EventFight; import de.steamwar.sql.EventFight;
import de.steamwar.sql.Team; import de.steamwar.sql.Team;
import net.md_5.bungee.api.ProxyServer; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.HashMap; import java.util.HashMap;
@ -43,7 +42,7 @@ public class EventStarter {
public EventStarter() { public EventStarter() {
EventFight.loadAllComingFights(); EventFight.loadAllComingFights();
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::run, 1, 10, TimeUnit.SECONDS); VelocityCore.schedule(this::run).delay(10, TimeUnit.SECONDS).schedule();
} }
public static Map<Integer, Subserver> getEventServer() { public static Map<Integer, Subserver> getEventServer() {
@ -61,7 +60,7 @@ public class EventStarter {
//Don't start EventServer if not the event bungee //Don't start EventServer if not the event bungee
String command; String command;
if(BungeeCore.EVENT_MODE || next.getSpectatePort() == 0) { if(VelocityCore.get().getConfig().isEventmode() || next.getSpectatePort() == 0) {
ServerStarter starter = new ServerStarter().event(next); ServerStarter starter = new ServerStarter().event(next);
starter.callback(subserver -> { starter.callback(subserver -> {
@ -73,7 +72,7 @@ public class EventStarter {
} else { } else {
command = "/" + spectatePorts.get(next.getSpectatePort()); command = "/" + spectatePorts.get(next.getSpectatePort());
} }
Chatter.broadcast().system("EVENT_FIGHT_BROADCAST", "EVENT_FIGHT_BROADCAST_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, command), blue.getTeamColor(), blue.getTeamName(), red.getTeamColor(), red.getTeamName()); Chatter.broadcast().system("EVENT_FIGHT_BROADCAST", "EVENT_FIGHT_BROADCAST_HOVER", ClickEvent.runCommand(command), blue.getTeamColor(), blue.getTeamName(), red.getTeamColor(), red.getTeamName());
} }
} }

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import net.md_5.bungee.BungeeCord; import java.io.BufferedReader;
import net.md_5.bungee.api.ProxyServer; import java.io.File;
import java.io.IOException;
import java.io.*; import java.io.InputStreamReader;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -74,7 +74,7 @@ public abstract class Node {
protected Node(String hostname) { protected Node(String hostname) {
this.hostname = hostname; this.hostname = hostname;
nodes.add(this); nodes.add(this);
BungeeCord.getInstance().getScheduler().schedule(BungeeCore.get(), this::calcLoadLimit, 1, 2, TimeUnit.SECONDS); VelocityCore.schedule(this::calcLoadLimit).repeat(2, TimeUnit.SECONDS).schedule();
} }
public void execute(String... command) { public void execute(String... command) {
@ -83,7 +83,7 @@ public abstract class Node {
} catch (IOException e) { } catch (IOException e) {
throw new SecurityException("Could not execute command", e); throw new SecurityException("Could not execute command", e);
} catch (InterruptedException e) { } catch (InterruptedException e) {
ProxyServer.getInstance().getLogger().log(Level.SEVERE, "Interrupted during execution", e); VelocityCore.getLogger().log(Level.SEVERE, "Interrupted during execution", e);
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
@ -155,7 +155,7 @@ public abstract class Node {
try (BufferedReader meminfo = new BufferedReader(new InputStreamReader(Files.newInputStream(MEMINFO.toPath())))) { try (BufferedReader meminfo = new BufferedReader(new InputStreamReader(Files.newInputStream(MEMINFO.toPath())))) {
calcLoadLimit(meminfo); calcLoadLimit(meminfo);
} catch (IOException e) { } catch (IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not read local load", e); VelocityCore.getLogger().log(Level.SEVERE, "Could not read local load", e);
belowLoadLimit = false; belowLoadLimit = false;
} }
} }
@ -170,7 +170,7 @@ public abstract class Node {
public RemoteNode(String hostname) { public RemoteNode(String hostname) {
super(hostname); super(hostname);
BungeeCore.get().getLogger().log(Level.INFO, "Added node " + hostname); VelocityCore.getLogger().log(Level.INFO, "Added node " + hostname);
} }
@Override @Override
@ -207,7 +207,7 @@ public abstract class Node {
} }
} catch (IOException e) { } catch (IOException e) {
if(belowLoadLimit) if(belowLoadLimit)
BungeeCore.get().getLogger().log(Level.SEVERE, "Could read remote load", e); VelocityCore.getLogger().log(Level.SEVERE, "Could read remote load", e);
belowLoadLimit = false; belowLoadLimit = false;
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();

Datei anzeigen

@ -1,13 +1,12 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.sql.*; import de.steamwar.sql.*;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files; import java.nio.file.Files;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
@ -18,8 +17,8 @@ import java.util.stream.Collectors;
public class ServerStarter { public class ServerStarter {
private static final Portrange BAU_PORTS = BungeeCore.MAIN_SERVER ? new Portrange(10100, 20000) : new Portrange(2100, 2200); private static final Portrange BAU_PORTS = VelocityCore.MAIN_SERVER ? new Portrange(10100, 20000) : new Portrange(2100, 2200);
private static final Portrange ARENA_PORTS = BungeeCore.MAIN_SERVER ? new Portrange(3000, 3100) : (BungeeCore.EVENT_MODE ? new Portrange(4000, 5000) : BAU_PORTS); private static final Portrange ARENA_PORTS = VelocityCore.MAIN_SERVER ? new Portrange(3000, 3100) : (VelocityCore.get().getConfig().isEventmode() ? new Portrange(4000, 5000) : BAU_PORTS);
public static final String SERVER_PATH = "/servers/"; public static final String SERVER_PATH = "/servers/";
private static final String USER_HOME = System.getProperty("user.home") + "/"; private static final String USER_HOME = System.getProperty("user.home") + "/";
@ -49,13 +48,13 @@ public class ServerStarter {
private ServerConstructor constructor = (serverName, port, builder, shutdownCallback, failureCallback) -> new Arenaserver(serverName, gameMode, fightMap, allowMerge, port, builder, shutdownCallback); private ServerConstructor constructor = (serverName, port, builder, shutdownCallback, failureCallback) -> new Arenaserver(serverName, gameMode, fightMap, allowMerge, port, builder, shutdownCallback);
private Consumer<Subserver> callback = subserver -> {}; private Consumer<Subserver> callback = subserver -> {};
private final Set<ProxiedPlayer> playersToSend = new HashSet<>(); private final Set<Player> playersToSend = new HashSet<>();
private final Map<String, String> arguments = new HashMap<>(); private final Map<String, String> arguments = new HashMap<>();
public ServerStarter arena(ArenaMode mode, String map) { public ServerStarter arena(ArenaMode mode, String map) {
portrange = ARENA_PORTS; portrange = ARENA_PORTS;
serverNameProvider = port -> mode.getDisplayName() + (port - portrange.start); serverNameProvider = port -> mode.getDisplayName() + (port - portrange.start);
serverJar = mode.serverJar(); serverJar = mode.getServerJar();
allowMerge = true; allowMerge = true;
fightMap = map; fightMap = map;
gameMode = mode.getInternalName(); gameMode = mode.getInternalName();
@ -67,7 +66,7 @@ public class ServerStarter {
public ServerStarter event(EventFight eventFight) { public ServerStarter event(EventFight eventFight) {
arena(ArenaMode.getByInternal(eventFight.getSpielmodus()), eventFight.getMap()); arena(ArenaMode.getByInternal(eventFight.getSpielmodus()), eventFight.getMap());
node = BungeeCore.local; node = VelocityCore.local;
worldDir = EVENT_PATH; worldDir = EVENT_PATH;
worldCleanup = () -> {}; worldCleanup = () -> {};
arguments.put("fightID", String.valueOf(eventFight.getFightID())); arguments.put("fightID", String.valueOf(eventFight.getFightID()));
@ -80,7 +79,7 @@ public class ServerStarter {
return this; return this;
} }
public ServerStarter test(ArenaMode mode, String map, ProxiedPlayer owner) { public ServerStarter test(ArenaMode mode, String map, Player owner) {
arena(mode, map); arena(mode, map);
buildWithTemp(owner); buildWithTemp(owner);
portrange = BAU_PORTS; portrange = BAU_PORTS;
@ -88,12 +87,12 @@ public class ServerStarter {
return send(owner); return send(owner);
} }
public ServerStarter blueLeader(ProxiedPlayer player) { public ServerStarter blueLeader(Player player) {
arguments.put("blueLeader", player.getUniqueId().toString()); arguments.put("blueLeader", player.getUniqueId().toString());
return send(player); return send(player);
} }
public ServerStarter redLeader(ProxiedPlayer player) { public ServerStarter redLeader(Player player) {
arguments.put("redLeader", player.getUniqueId().toString()); arguments.put("redLeader", player.getUniqueId().toString());
return send(player); return send(player);
} }
@ -132,7 +131,7 @@ public class ServerStarter {
startCondition = () -> { startCondition = () -> {
Bauserver subserver = Bauserver.get(owner); Bauserver subserver = Bauserver.get(owner);
if(subserver != null) { if(subserver != null) {
for(ProxiedPlayer p : playersToSend) for(Player p : playersToSend)
SubserverSystem.sendPlayer(subserver, p); SubserverSystem.sendPlayer(subserver, p);
return false; return false;
} }
@ -142,7 +141,7 @@ public class ServerStarter {
return bauweltMember.isSupervisor(); return bauweltMember.isSupervisor();
}); });
if (!atLeastOneSupervisor) { if (!atLeastOneSupervisor) {
for (ProxiedPlayer p : playersToSend) { for (Player p : playersToSend) {
Chatter.of(p).system("BAU_START_NOT_ALLOWED"); Chatter.of(p).system("BAU_START_NOT_ALLOWED");
} }
} }
@ -152,7 +151,7 @@ public class ServerStarter {
return this; return this;
} }
public ServerStarter tutorial(ProxiedPlayer owner, Tutorial tutorial) { public ServerStarter tutorial(Player owner, Tutorial tutorial) {
directory = new File(SERVER_PATH, "Tutorial"); directory = new File(SERVER_PATH, "Tutorial");
buildWithTemp(owner); buildWithTemp(owner);
tempWorld(TUTORIAL_PATH + tutorial.getTutorialId()); tempWorld(TUTORIAL_PATH + tutorial.getTutorialId());
@ -166,7 +165,7 @@ public class ServerStarter {
worldCleanup = () -> SubserverSystem.deleteFolder(node, worldDir + worldName); worldCleanup = () -> SubserverSystem.deleteFolder(node, worldDir + worldName);
} }
private void buildWithTemp(ProxiedPlayer owner) { private void buildWithTemp(Player owner) {
build(owner.getUniqueId()); build(owner.getUniqueId());
// Stop existing build server // Stop existing build server
@ -200,7 +199,7 @@ public class ServerStarter {
startCondition = () -> { startCondition = () -> {
Builderserver subserver = Builderserver.get(worldName); Builderserver subserver = Builderserver.get(worldName);
if (subserver != null) { if (subserver != null) {
for(ProxiedPlayer p : playersToSend) for(Player p : playersToSend)
SubserverSystem.sendPlayer(subserver, p); SubserverSystem.sendPlayer(subserver, p);
return false; return false;
} }
@ -221,7 +220,7 @@ public class ServerStarter {
return this; return this;
} }
public ServerStarter send(ProxiedPlayer player) { public ServerStarter send(Player player) {
playersToSend.add(player); playersToSend.add(player);
return this; return this;
} }
@ -241,7 +240,7 @@ public class ServerStarter {
if(node == null) { if(node == null) {
node = Node.getNode(); node = Node.getNode();
if(node == null) { if(node == null) {
for (ProxiedPlayer p : playersToSend) for (Player p : playersToSend)
Chatter.of(p).system("SERVER_START_OVERLOAD"); Chatter.of(p).system("SERVER_START_OVERLOAD");
return false; return false;
@ -281,13 +280,13 @@ public class ServerStarter {
} }
private void postStart(Subserver subserver) { private void postStart(Subserver subserver) {
for(ProxiedPlayer p : playersToSend) for(Player p : playersToSend)
SubserverSystem.sendPlayer(subserver, p); SubserverSystem.sendPlayer(subserver, p);
callback.accept(subserver); callback.accept(subserver);
} }
private static boolean startingBau(ProxiedPlayer p) { private static boolean startingBau(Player p) {
Bauserver subserver = Bauserver.get(p.getUniqueId()); Bauserver subserver = Bauserver.get(p.getUniqueId());
if(subserver != null && !subserver.isStarted()) { if(subserver != null && !subserver.isStarted()) {
Chatter.of(p).system("BAU_START_ALREADY"); Chatter.of(p).system("BAU_START_ALREADY");
@ -335,7 +334,7 @@ public class ServerStarter {
Set<Integer> usedPorts; Set<Integer> usedPorts;
synchronized (Subserver.getServerList()) { synchronized (Subserver.getServerList()) {
usedPorts = Subserver.getServerList().stream().map(server -> ((InetSocketAddress) server.getServer().getSocketAddress()).getPort()).collect(Collectors.toSet()); usedPorts = Subserver.getServerList().stream().map(server -> server.getServer().getAddress().getPort()).collect(Collectors.toSet());
} }
while(usedPorts.contains(current)) { while(usedPorts.contains(current)) {

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.network.NetworkSender; import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.network.handlers.FightInfoHandler; import de.steamwar.bungeecore.network.handlers.FightInfoHandler;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
@ -26,8 +27,7 @@ import de.steamwar.messages.Message;
import de.steamwar.network.packets.server.StartingServerPacket; import de.steamwar.network.packets.server.StartingServerPacket;
import de.steamwar.sql.IgnoreSystem; import de.steamwar.sql.IgnoreSystem;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.chat.ClickEvent; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.UUID; import java.util.UUID;
@ -46,10 +46,10 @@ public class SubserverSystem {
Chatter o = Chatter.of(owner); Chatter o = Chatter.of(owner);
o.system("SERVER_ADD_MEMBER", p); o.system("SERVER_ADD_MEMBER", p);
o.prefixless("SERVER_ADD_MESSAGE", new Message("SERVER_ADD_MESSAGE_HOVER"), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.user().getUserName())); o.prefixless("SERVER_ADD_MESSAGE", new Message("SERVER_ADD_MESSAGE_HOVER"), ClickEvent.runCommand("/bau addmember " + p.user().getUserName()));
} }
public static void sendPlayer(Subserver subserver, ProxiedPlayer player) { public static void sendPlayer(Subserver subserver, Player player) {
subserver.sendPlayer(player); subserver.sendPlayer(player);
if(!subserver.isStarted() && FightInfoHandler.onLobby(player)) if(!subserver.isStarted() && FightInfoHandler.onLobby(player))
NetworkSender.send(player, new StartingServerPacket(SteamwarUser.get(player.getUniqueId()).getId())); NetworkSender.send(player, new StartingServerPacket(SteamwarUser.get(player.getUniqueId()).getId()));

Datei anzeigen

@ -19,9 +19,18 @@
package de.steamwar.bungeecore; package de.steamwar.bungeecore;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Dependency;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.scheduler.Scheduler;
import de.steamwar.bungeecore.commands.*; import de.steamwar.bungeecore.commands.*;
import de.steamwar.bungeecore.discord.DiscordBot; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.config.DiscordConfig; import de.steamwar.bungeecore.discord.DiscordConfig;
import de.steamwar.bungeecore.listeners.*; import de.steamwar.bungeecore.listeners.*;
import de.steamwar.bungeecore.mods.*; import de.steamwar.bungeecore.mods.*;
import de.steamwar.bungeecore.network.handlers.*; import de.steamwar.bungeecore.network.handlers.*;
@ -35,41 +44,71 @@ import de.steamwar.sql.Team;
import de.steamwar.sql.UserElo; import de.steamwar.sql.UserElo;
import de.steamwar.sql.internal.Statement; import de.steamwar.sql.internal.Statement;
import lombok.Getter; import lombok.Getter;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
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.nio.file.Path;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger;
public class BungeeCore extends Plugin { @Plugin(
id = "velocitycore",
name = "VelocityCore",
dependencies = {
@Dependency(id = "persistentvelocitycore")
}
)
public class VelocityCore {
public static boolean MAIN_SERVER; public static boolean MAIN_SERVER;
public static boolean EVENT_MODE;
public static String LOBBY_SERVER; private static VelocityCore instance;
public static VelocityCore get() {
private static BungeeCore instance; return instance;
}
public static Node local; public static Node local;
public static Scheduler.TaskBuilder schedule(Runnable runnable) {
return instance.proxyServer.getScheduler().buildTask(instance, runnable);
}
public static ProxyServer getProxy() {
return instance.proxyServer;
}
public static Logger getLogger() {
return instance.logger;
}
private final ProxyServer proxyServer;
private final Logger logger;
@Getter
private final Path dataDirectory;
@Getter
Config config;
private ErrorLogger errorLogger; private ErrorLogger errorLogger;
private TablistManager tablistManager; private TablistManager tablistManager;
@Getter @Getter
private TeamCommand teamCommand; private TeamCommand teamCommand;
@Override @Inject
public void onEnable(){ public VelocityCore(ProxyServer proxyServer, Logger logger, @DataDirectory Path dataDirectory) {
setInstance(this); this.proxyServer = proxyServer;
MAIN_SERVER = ProxyServer.getInstance().getConfig().getListeners().stream().anyMatch(info -> ((InetSocketAddress) info.getSocketAddress()).getPort() == 25565); this.logger = logger;
loadConfig(); this.dataDirectory = dataDirectory;
instance = this;
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
config = Config.load();
MAIN_SERVER = proxyServer.getBoundAddress().getPort() == 25565;
errorLogger = new ErrorLogger(); errorLogger = new ErrorLogger();
@ -84,7 +123,10 @@ public class BungeeCore extends Plugin {
return tabCompleter.apply(sender, s); return tabCompleter.apply(sender, s);
} }
}); });
ProxyServer.getInstance().getScheduler().schedule(this, TabCompletionCache::invalidateOldEntries, 1, 1, TimeUnit.SECONDS); schedule(TabCompletionCache::invalidateOldEntries).repeat(1, TimeUnit.SECONDS).schedule();
initStaticServers();
PollSystem.init();
new Hostname(); new Hostname();
new ServerListPing(); new ServerListPing();
@ -153,7 +195,7 @@ public class BungeeCore extends Plugin {
new PunishmentCommand("noteamserver", Punishment.PunishmentType.NoTeamServer); new PunishmentCommand("noteamserver", Punishment.PunishmentType.NoTeamServer);
new PunishmentCommand("note", Punishment.PunishmentType.Note); new PunishmentCommand("note", Punishment.PunishmentType.Note);
if(!EVENT_MODE){ if(!config.isEventmode()){
new BauCommand(helpCommand); new BauCommand(helpCommand);
new WebpasswordCommand(); new WebpasswordCommand();
new FightCommand(); new FightCommand();
@ -178,27 +220,28 @@ public class BungeeCore extends Plugin {
tablistManager = new TablistManager(); tablistManager = new TablistManager();
new SettingsChangedListener(); new SettingsChangedListener();
getProxy().getScheduler().schedule(this, () -> { schedule(() -> {
SteamwarUser.clear(); SteamwarUser.clear();
UserElo.clear(); UserElo.clear();
Team.clear(); Team.clear();
}, 1, 1, TimeUnit.HOURS); }).repeat(1, TimeUnit.HOURS).schedule();
if (DiscordConfig.loaded) { DiscordConfig discordConfig = DiscordConfig.load();
if (discordConfig != null) {
try { try {
new DiscordBot(); new DiscordBot(discordConfig);
} catch (Throwable e) { } catch (Throwable e) {
getLogger().log(Level.SEVERE, "Could not initialize discord bot", e); logger.log(Level.SEVERE, "Could not initialize discord bot", e);
} }
} }
} }
@Override @Subscribe
public void onDisable(){ public void onProxyShutdown(ProxyShutdownEvent event) {
try { try {
DiscordBot.withBot(bot -> bot.getJda().shutdown()); DiscordBot.withBot(bot -> bot.getJda().shutdown());
} catch (Throwable e) { } catch (Throwable e) {
getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e); logger.log(Level.SEVERE, "Could not shutdown discord bot", e);
} }
if(tablistManager != null) if(tablistManager != null)
@ -207,54 +250,16 @@ public class BungeeCore extends Plugin {
Statement.closeAll(); Statement.closeAll();
} }
public static BungeeCore get() { private void initStaticServers() {
return instance; for (Map.Entry<String, Config.Server> entry : config.getServers().entrySet()) {
} Config.Server server = entry.getValue();
List<String> cmds = server.getCommands();
private static void loadConfig(){
Configuration config;
try{
if(!get().getDataFolder().exists() && !get().getDataFolder().mkdir())
throw new IOException();
File configFile = new File(get().getDataFolder().getPath(), "config.yml");
if(!configFile.exists()){
boolean created = configFile.createNewFile();
if(created)
ProxyServer.getInstance().stop("Config file not initialized");
else
ProxyServer.getInstance().stop("Could not save conig file");
return;
}
config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
}catch(Exception e){
get().getLogger().log(Level.SEVERE, "Could not save/load config.yml", e);
ProxyServer.getInstance().stop();
return;
}
LOBBY_SERVER = config.getString("lobbyserver");
EVENT_MODE = config.getBoolean("eventmode");
Broadcaster.setBroadCastMsgs(config.getStringList("broadcasts").toArray(new String[1]));
PollSystem.init(config.getString("poll.question"), config.getStringList("poll.answers"));
final Configuration servers = config.getSection("servers");
for(final String serverName : servers.getKeys()){
final Configuration server = servers.getSection(serverName);
List<String> cmds = server.getStringList("commands");
String cmd = cmds.remove(0); String cmd = cmds.remove(0);
if(server.contains("spectatePort")) if(server.getSpectatePort() != 0)
EventStarter.addSpectateServer(server.getInt("spectatePort"), cmd); EventStarter.addSpectateServer(server.getSpectatePort(), cmd);
new ServerSwitchCommand( new ServerSwitchCommand(cmd, entry.getKey(), cmds.toArray(new String[0]));
cmd,
serverName,
cmds.toArray(new String[0])
);
} }
} }
private static void setInstance(BungeeCore core){
instance = core;
}
} }

Datei anzeigen

@ -23,7 +23,6 @@ import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.ChatColor;
public class AlertCommand extends SWCommand { public class AlertCommand extends SWCommand {
@ -39,7 +38,7 @@ public class AlertCommand extends SWCommand {
} }
String s = String.join(" ", message); String s = String.join(" ", message);
Chatter.broadcast().system("ALERT", ChatColor.translateAlternateColorCodes('&', s)); Chatter.broadcast().system("ALERT", s.replace('&', '§'));
if ("-discord".equals(sendToDiscord)) if ("-discord".equals(sendToDiscord))
DiscordBot.withBot(bot -> bot.getAnnouncementChannel().send(s)); DiscordBot.withBot(bot -> bot.getAnnouncementChannel().send(s));

Datei anzeigen

@ -19,14 +19,15 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.command.PreviousArguments; import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper; import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ProxyServer;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -40,15 +41,15 @@ public class ArenaCommand extends SWCommand {
@Register @Register
public void arenaJoin(PlayerChatter sender, Subserver server) { public void arenaJoin(PlayerChatter sender, Subserver server) {
TpCommand.teleport(sender, server.getServer()); TpCommand.teleport(sender, server.getRegisteredServer());
} }
@ClassMapper(value = Subserver.class, local = true) @ClassMapper(value = Subserver.class, local = true)
public TypeMapper<Subserver> serverInfoTypeMapper() { public TypeMapper<Subserver> serverInfoTypeMapper() {
return new TypeMapper<Subserver>() { return new TypeMapper<>() {
@Override @Override
public Subserver map(Chatter sender, PreviousArguments previousArguments, String s) { public Subserver map(Chatter sender, PreviousArguments previousArguments, String s) {
return Subserver.getSubserver(ProxyServer.getInstance().getServerInfo(s)); return Subserver.getSubserver(VelocityCore.getProxy().getServer(s).map(RegisteredServer::getServerInfo).orElse(null));
} }
@Override @Override

Datei anzeigen

@ -36,7 +36,6 @@ import de.steamwar.messages.PlayerChatter;
import de.steamwar.network.packets.server.BaumemberUpdatePacket; import de.steamwar.network.packets.server.BaumemberUpdatePacket;
import de.steamwar.sql.BauweltMember; import de.steamwar.sql.BauweltMember;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer;
import java.util.Collection; import java.util.Collection;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -149,7 +148,7 @@ public class BauCommand extends SWCommand {
Bauserver bauserver = Bauserver.get(owner.user().getUUID()); Bauserver bauserver = Bauserver.get(owner.user().getUUID());
if(bauserver != null) if(bauserver != null)
bauserver.getServer().getPlayers().stream().findAny().ifPresent(player -> NetworkSender.send(player, new BaumemberUpdatePacket())); bauserver.getRegisteredServer().getPlayersConnected().stream().findAny().ifPresent(player -> NetworkSender.send(player, new BaumemberUpdatePacket()));
Chatter.of(user.getUUID()).system("BAU_MEMBER_SET_TARGET", owner, new Message(permName)); Chatter.of(user.getUUID()).system("BAU_MEMBER_SET_TARGET", owner, new Message(permName));
owner.system("BAU_MEMBER_SET", new Message(permName)); owner.system("BAU_MEMBER_SET", new Message(permName));
@ -164,8 +163,8 @@ public class BauCommand extends SWCommand {
Chatter member = Chatter.of(user.getUUID()); Chatter member = Chatter.of(user.getUUID());
member.system("BAU_DELMEMBER_DELETED_TARGET", owner); member.system("BAU_DELMEMBER_DELETED_TARGET", owner);
member.withPlayer(player -> { member.withPlayer(player -> {
if (Bauserver.get(owner.user().getUUID()).getServer().getPlayers().contains(player)) if (Bauserver.get(owner.user().getUUID()).getRegisteredServer().getPlayersConnected().contains(player))
player.connect(ProxyServer.getInstance().getServerInfo(BungeeCore.LOBBY_SERVER)); player.createConnectionRequest(VelocityCore.get().getConfig().lobbyserver()).fireAndForget();
}); });
owner.system("BAU_DELMEMBER_DELETED"); owner.system("BAU_DELMEMBER_DELETED");
@ -196,14 +195,14 @@ public class BauCommand extends SWCommand {
inventory.addItem(0, new SWItem(new Message("BAU_DELETE_GUI_DELETE"), 10), click -> { inventory.addItem(0, new SWItem(new Message("BAU_DELETE_GUI_DELETE"), 10), click -> {
String world = version.getWorldFolder(ServerStarter.WORLDS_BASE_PATH) + (version != ServerVersion.SPIGOT_12 ? sender.user().getId() : sender.user().getUUID().toString()); String world = version.getWorldFolder(ServerStarter.WORLDS_BASE_PATH) + (version != ServerVersion.SPIGOT_12 ? sender.user().getId() : sender.user().getUUID().toString());
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
Bauserver subserver = Bauserver.get(sender.user().getUUID()); Bauserver subserver = Bauserver.get(sender.user().getUUID());
if(subserver != null) if(subserver != null)
subserver.stop(); subserver.stop();
SubserverSystem.deleteFolder(BungeeCore.local, world); SubserverSystem.deleteFolder(VelocityCore.local, world);
sender.system("BAU_DELETE_DELETED"); sender.system("BAU_DELETE_DELETED");
}); }).schedule();
inventory.close(); inventory.close();
}); });
@ -215,7 +214,7 @@ public class BauCommand extends SWCommand {
@Register("testarena") @Register("testarena")
public void testarena(PlayerChatter sender, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) { public void testarena(PlayerChatter sender, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) {
FightCommand.createArena(sender, "/bau testarena ", false, arenaMode, map, false, (chatter, mode, m) -> FightCommand.createArena(sender, "/bau testarena ", false, arenaMode, map, false, (chatter, mode, m) ->
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> new ServerStarter().test(mode, m, sender.getPlayer()).start()) VelocityCore.schedule(() -> new ServerStarter().test(mode, m, sender.getPlayer()).start()).schedule()
); );
} }

Datei anzeigen

@ -32,7 +32,7 @@ public class BugCommand extends SWCommand {
public void bugMessage(Chatter sender, String... message) { public void bugMessage(Chatter sender, String... message) {
SWException.log( SWException.log(
String.join(" ", message), String.join(" ", message),
sender.withPlayerOrOffline(player -> player.getServer().getInfo().getName(), () -> "offline") + " " + sender.user().getUserName() + " " + sender.user().getId() sender.withPlayerOrOffline(player -> player.getCurrentServer().map(connection -> connection.getServerInfo().getName()).orElse("offline"), () -> "offline") + " " + sender.user().getUserName() + " " + sender.user().getId()
); );
sender.system("BUG_MESSAGE"); sender.system("BUG_MESSAGE");
} }

Datei anzeigen

@ -1,16 +1,15 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.ArenaMode; import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.ServerStarter; import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.bungeecore.ServerVersion; import de.steamwar.bungeecore.ServerVersion;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.PreviousArguments; import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper; import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ProxyServer;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -72,11 +71,11 @@ public class BuilderCloudCommand extends SWCommand {
return; return;
} }
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
BungeeCore.local.execute("/binarys/deployarena.py", arenaMode.getConfig(), Integer.toString(version.getVersionSuffix()), map); VelocityCore.local.execute("/binarys/deployarena.py", arenaMode.getConfig(), Integer.toString(version.getVersionSuffix()), map);
ArenaMode.init(); ArenaMode.init();
sender.system("BUILDERCLOUD_DEPLOY_FINISHED"); sender.system("BUILDERCLOUD_DEPLOY_FINISHED");
}); }).schedule();
} }
@Cached(global = true) @Cached(global = true)

Datei anzeigen

@ -19,15 +19,18 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*; import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.IgnoreSystem; import de.steamwar.sql.IgnoreSystem;
import de.steamwar.command.SWCommand; import net.kyori.adventure.text.event.ClickEvent;
import de.steamwar.command.TypeValidator;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.LinkedList; import java.util.LinkedList;
@ -40,15 +43,15 @@ public class ChallengeCommand extends SWCommand {
} }
@Register(description = "CHALLENGE_USAGE") @Register(description = "CHALLENGE_USAGE")
public void challenge(@Validator("arenaPlayer") PlayerChatter sender, @Validator("target") ProxiedPlayer target, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) { public void challenge(@Validator("arenaPlayer") PlayerChatter sender, @Validator("target") Player target, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) {
FightCommand.createArena(sender, "/challenge " + target.getName() + " ", false, arenaMode, map, false, (chatter, mode, m) -> { FightCommand.createArena(sender, "/challenge " + target.getUsername() + " ", false, arenaMode, map, false, (chatter, mode, m) -> {
ProxiedPlayer p = sender.getPlayer(); Player p = sender.getPlayer();
if(challenges.containsKey(target) && challenges.get(target).contains(p)){ if(challenges.containsKey(target) && challenges.get(target).contains(p)){
challenges.remove(target); challenges.remove(target);
challenges.remove(p); challenges.remove(p);
new ServerStarter().arena(mode, map).blueLeader(sender.getPlayer()).redLeader(target).callback( new ServerStarter().arena(mode, map).blueLeader(sender.getPlayer()).redLeader(target).callback(
arena -> Chatter.broadcast().system("CHALLENGE_BROADCAST", "CHALLENGE_BROADCAST_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/arena " + arena.getServer().getName()), mode.getDisplayName(), p.getName(), target.getName()) arena -> Chatter.broadcast().system("CHALLENGE_BROADCAST", "CHALLENGE_BROADCAST_HOVER", ClickEvent.runCommand("/arena " + arena.getServer().getName()), mode.getDisplayName(), p, target)
).start(); ).start();
}else{ }else{
if(!challenges.containsKey(p)){ if(!challenges.containsKey(p)){
@ -57,16 +60,16 @@ public class ChallengeCommand extends SWCommand {
challenges.get(p).add(target); challenges.get(p).add(target);
sender.system("CHALLENGE_CHALLENGED", target.getName(), mode.getDisplayName()); sender.system("CHALLENGE_CHALLENGED", target, mode.getDisplayName());
Chatter.of(target).system("CHALLENGE_CHALLENGED_TARGET", p.getName(), mode.getDisplayName(), mode.getMaps().size() != 1 ? new Message("CHALLENGE_CHALLENGED_MAP", m) : ""); Chatter.of(target).system("CHALLENGE_CHALLENGED_TARGET", p, mode.getDisplayName(), mode.getMaps().size() != 1 ? new Message("CHALLENGE_CHALLENGED_MAP", m) : "");
Chatter.of(target).system("CHALLENGE_ACCEPT", new Message("CHALLENGE_ACCEPT_HOVER"), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/challenge " + p.getName() + " " + mode.getChatName() + " " + m)); Chatter.of(target).system("CHALLENGE_ACCEPT", new Message("CHALLENGE_ACCEPT_HOVER"), ClickEvent.runCommand("/challenge " + p.getUsername() + " " + mode.getChatName() + " " + m));
} }
}); });
} }
@Validator(value = "target", local = true) @Validator(value = "target", local = true)
public TypeValidator<ProxiedPlayer> targetValidator() { public TypeValidator<Player> targetValidator() {
return (sender, value, messageSender) -> { return (sender, value, messageSender) -> {
if (value == null) { if (value == null) {
sender.system("CHALLENGE_OFFLINE"); sender.system("CHALLENGE_OFFLINE");
@ -90,7 +93,7 @@ public class ChallengeCommand extends SWCommand {
}; };
} }
public static void remove(ProxiedPlayer player){ public static void remove(Player player){
challenges.remove(player); challenges.remove(player);
} }
} }

Datei anzeigen

@ -19,7 +19,11 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*; import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.Bauserver;
import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.util.DiscordAlert; import de.steamwar.bungeecore.discord.util.DiscordAlert;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
@ -27,13 +31,9 @@ import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*; import de.steamwar.sql.*;
import net.md_5.bungee.api.ChatColor; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.ProxyServer; import net.kyori.adventure.text.format.NamedTextColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.config.Configuration;
import java.awt.*; import java.awt.*;
import java.sql.Timestamp; import java.sql.Timestamp;
@ -50,26 +50,26 @@ public class CheckCommand extends SWCommand {
private static final Map<UUID, CheckSession> currentCheckers = new HashMap<>(); private static final Map<UUID, CheckSession> currentCheckers = new HashMap<>();
private static final Map<Integer, CheckSession> currentSchems = new HashMap<>(); private static final Map<Integer, CheckSession> currentSchems = new HashMap<>();
public static void setCheckQuestions(SchematicType checkType, Configuration config) { public static void setCheckQuestions(SchematicType checkType, List<String> checkQuestions) {
checkQuestions.put(checkType, config.getStringList("CheckQuestions")); CheckCommand.checkQuestions.put(checkType, checkQuestions);
} }
public static void addFightType(SchematicType checkType, SchematicType fightType) { public static void addFightType(SchematicType checkType, SchematicType fightType) {
fightTypes.put(checkType, fightType); fightTypes.put(checkType, fightType);
} }
public static boolean isChecking(ProxiedPlayer player){ public static boolean isChecking(Player player){
return currentCheckers.containsKey(player.getUniqueId()); return currentCheckers.containsKey(player.getUniqueId());
} }
public static SchematicNode getCheckingSchem(ProxiedPlayer player) { public static SchematicNode getCheckingSchem(Player player) {
return currentCheckers.get(player.getUniqueId()).schematic; return currentCheckers.get(player.getUniqueId()).schematic;
} }
public CheckCommand() { public CheckCommand() {
super("check", ConnectionListener.CHECK_PERMISSION); super("check", ConnectionListener.CHECK_PERMISSION);
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> sendReminder(Chatter.serverteam()), 10, 10, TimeUnit.MINUTES); VelocityCore.schedule(() -> sendReminder(Chatter.serverteam())).repeat(10, TimeUnit.MINUTES).schedule();
} }
public static void sendReminder(Chatter chatter) { public static void sendReminder(Chatter chatter) {
@ -77,7 +77,7 @@ public class CheckCommand extends SWCommand {
if(schematics.size() == currentCheckers.size()) if(schematics.size() == currentCheckers.size())
return; return;
chatter.system("CHECK_REMINDER", new Message("CHECK_REMINDER_HOVER"), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check list"), schematics.size() - currentCheckers.size()); chatter.system("CHECK_REMINDER", new Message("CHECK_REMINDER_HOVER"), ClickEvent.runCommand("/check list"), schematics.size() - currentCheckers.size());
} }
@Register(value = "list", description = "CHECK_HELP_LIST") @Register(value = "list", description = "CHECK_HELP_LIST")
@ -96,13 +96,13 @@ public class CheckCommand extends SWCommand {
if (current == null) { if (current == null) {
sender.prefixless("CHECK_LIST_TO_CHECK", sender.prefixless("CHECK_LIST_TO_CHECK",
new Message("CHECK_LIST_TO_CHECK_HOVER"), new Message("CHECK_LIST_TO_CHECK_HOVER"),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check schematic " + schematic.getId()), ClickEvent.runCommand("/check schematic " + schematic.getId()),
waitTime, waitTime,
schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName()); schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName());
} else { } else {
sender.prefixless("CHECK_LIST_CHECKING", sender.prefixless("CHECK_LIST_CHECKING",
new Message("CHECK_LIST_CHECKING_HOVER"), new Message("CHECK_LIST_CHECKING_HOVER"),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + current.checker.user().getUserName()), ClickEvent.runCommand("/join " + current.checker.user().getUserName()),
waitTime, waitTime,
schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName(), current.checker.user().getUserName()); schematic.getSchemtype().getKuerzel(), SteamwarUser.get(schematic.getOwner()).getUserName(), schematic.getName(), current.checker.user().getUserName());
} }
@ -118,7 +118,7 @@ public class CheckCommand extends SWCommand {
SchematicNode schem = SchematicNode.getSchematicNode(Integer.parseInt(schemID)); SchematicNode schem = SchematicNode.getSchematicNode(Integer.parseInt(schemID));
if(!schem.getSchemtype().check()){ if(!schem.getSchemtype().check()){
ProxyServer.getInstance().getLogger().log(Level.SEVERE, () -> sender.user().getUserName() + " tried to check an uncheckable schematic!"); VelocityCore.getLogger().log(Level.SEVERE, () -> sender.user().getUserName() + " tried to check an uncheckable schematic!");
return; return;
}else if(schem.getOwner() == sender.user().getId()) { }else if(schem.getOwner() == sender.user().getId()) {
sender.system("CHECK_SCHEMATIC_OWN"); sender.system("CHECK_SCHEMATIC_OWN");
@ -139,7 +139,7 @@ public class CheckCommand extends SWCommand {
abort(sender.getPlayer()); abort(sender.getPlayer());
} }
public static void abort(ProxiedPlayer player) { public static void abort(Player player) {
if(notChecking(player)) if(notChecking(player))
return; return;
@ -183,7 +183,7 @@ public class CheckCommand extends SWCommand {
return currentSchems.get(schematic.getId()).checker.user().getUserName(); return currentSchems.get(schematic.getId()).checker.user().getUserName();
} }
private static boolean notChecking(ProxiedPlayer player){ private static boolean notChecking(Player player){
if(!isChecking(player)){ if(!isChecking(player)){
Chatter.of(player).system("CHECK_NOT_CHECKING"); Chatter.of(player).system("CHECK_NOT_CHECKING");
return true; return true;
@ -203,7 +203,7 @@ public class CheckCommand extends SWCommand {
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(), () -> { VelocityCore.schedule(() -> {
ArenaMode mode = ArenaMode.getBySchemType(fightTypes.get(schematic.getSchemtype())); ArenaMode mode = ArenaMode.getBySchemType(fightTypes.get(schematic.getSchemtype()));
if(!new ServerStarter().test(mode, mode.getRandomMap(), checker.getPlayer()).check(schematic.getId()).start()) { if(!new ServerStarter().test(mode, mode.getRandomMap(), checker.getPlayer()).check(schematic.getId()).start()) {
remove(); remove();
@ -215,7 +215,7 @@ public class CheckCommand extends SWCommand {
for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic)) for(CheckedSchematic previous : CheckedSchematic.previousChecks(schematic))
checker.prefixless("CHECK_SCHEMATIC_PREVIOUS", previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getDeclineReason()); checker.prefixless("CHECK_SCHEMATIC_PREVIOUS", previous.getEndTime(), SteamwarUser.get(previous.getValidator()).getUserName(), previous.getDeclineReason());
next(); next();
}); }).schedule();
} }
private void next() { private void next() {
@ -224,24 +224,16 @@ public class CheckCommand extends SWCommand {
return; return;
} }
checker.sendMessage(ChatMessageType.SYSTEM, TextComponent.fromLegacy(checkList.next())); checker.prefixless("PLAIN_STRING", checkList.next());
TextComponent next = new TextComponent(); checker.sendMessage(Component
next.setColor(ChatColor.GREEN); .text(checker.parseToPlain(checkList.hasNext() ? "CHECK_NEXT" : "CHECK_ACCEPT"))
if(checkList.hasNext()){ .color(NamedTextColor.GREEN)
next.setText(checker.parseToPlain("CHECK_NEXT")); .clickEvent(ClickEvent.runCommand("/check next"))
next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check next")); .append(Component
}else{ .text(" " + checker.parseToPlain("CHECK_DECLINE"))
next.setText(checker.parseToPlain("CHECK_ACCEPT")); .color(NamedTextColor.RED)
next.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/check accept")); .clickEvent(ClickEvent.suggestCommand("/check decline "))));
}
TextComponent decline = new TextComponent(" " + checker.parseToPlain("CHECK_DECLINE"));
decline.setColor(ChatColor.RED);
decline.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/check decline "));
next.addExtra(decline);
checker.sendMessage(ChatMessageType.SYSTEM, next);
} }
private void accept(){ private void accept(){
@ -279,11 +271,11 @@ public class CheckCommand extends SWCommand {
schematic.setSchemtype(type); schematic.setSchemtype(type);
remove(); remove();
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
Bauserver subserver = Bauserver.get(checker.user().getUUID()); Bauserver subserver = Bauserver.get(checker.user().getUUID());
if(subserver != null) if(subserver != null)
subserver.stop(); subserver.stop();
}); }).schedule();
return true; return true;
} }

Datei anzeigen

@ -19,6 +19,9 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils; import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper; import de.steamwar.command.TypeMapper;
@ -26,8 +29,6 @@ import de.steamwar.command.TypeValidator;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.Punishment; import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import java.io.File; import java.io.File;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -37,7 +38,7 @@ import java.util.Map;
public class DevCommand extends SWCommand { public class DevCommand extends SWCommand {
private final File devServerDir = new File("/configs/DevServer"); private final File devServerDir = new File("/configs/DevServer");
private final Map<String, ServerInfo> devServers = new HashMap<>(); private final Map<String, RegisteredServer> devServers = new HashMap<>();
public DevCommand() { public DevCommand() {
super("dev"); super("dev");
@ -50,29 +51,29 @@ public class DevCommand extends SWCommand {
sender.system("DEV_NO_SERVER"); sender.system("DEV_NO_SERVER");
return; return;
} else if (devServers.size() == 1) { } else if (devServers.size() == 1) {
sender.getPlayer().connect(devServers.values().stream().findAny().get()); sender.getPlayer().createConnectionRequest(devServers.values().stream().findAny().get()).fireAndForget();
return; return;
} }
ServerInfo info = devServers.get(sender.getPlayer().getName().toLowerCase()); RegisteredServer server = devServers.get(sender.getPlayer().getUsername().toLowerCase());
if (info == null) { if (server == null) {
sender.system("DEV_UNKNOWN_SERVER"); sender.system("DEV_UNKNOWN_SERVER");
return; return;
} }
sender.getPlayer().connect(info); sender.getPlayer().createConnectionRequest(server).fireAndForget();
} }
@Register @Register
public void selectedCommand(@Validator PlayerChatter sender, @Mapper("dev") String name) { public void selectedCommand(@Validator PlayerChatter sender, @Mapper("dev") String name) {
updateDevServers(); updateDevServers();
ServerInfo info = devServers.get(name.toLowerCase()); RegisteredServer server = devServers.get(name.toLowerCase());
if (info == null) { if (server == null) {
sender.system("DEV_NO_SERVER"); sender.system("DEV_NO_SERVER");
return; return;
} }
sender.getPlayer().connect(info); sender.getPlayer().createConnectionRequest(server).fireAndForget();
} }
@ClassValidator(value = PlayerChatter.class, local = true) @ClassValidator(value = PlayerChatter.class, local = true)
@ -107,7 +108,7 @@ public class DevCommand extends SWCommand {
devServers.entrySet().removeIf(entry -> { devServers.entrySet().removeIf(entry -> {
if (!devServerFiles.containsKey(entry.getKey())) { if (!devServerFiles.containsKey(entry.getKey())) {
ProxyServer.getInstance().getServers().remove(entry.getValue().getName()); VelocityCore.getProxy().unregisterServer(entry.getValue().getServerInfo());
return true; return true;
} }
return false; return false;
@ -118,9 +119,7 @@ public class DevCommand extends SWCommand {
return; return;
SteamwarUser user = SteamwarUser.get(key); SteamwarUser user = SteamwarUser.get(key);
ServerInfo info = ProxyServer.getInstance().constructServerInfo("Dev " + user.getUserName(), new InetSocketAddress("127.0.0.1", value), "SteamWar.de - Subserver", false); devServers.put(user.getUserName().toLowerCase(), VelocityCore.getProxy().registerServer(new ServerInfo("Dev " + user.getUserName(), new InetSocketAddress("127.0.0.1", value))));
ProxyServer.getInstance().getServers().put(info.getName(), info);
devServers.put(user.getUserName().toLowerCase(), info);
}); });
} }
} }

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.inventory.SWInventory; import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.inventory.SWItem; import de.steamwar.bungeecore.inventory.SWItem;
@ -26,13 +27,11 @@ import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ChatColor; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent; import net.kyori.adventure.text.event.HoverEvent;
import net.md_5.bungee.api.chat.HoverEvent; import net.kyori.adventure.text.format.NamedTextColor;
import net.md_5.bungee.api.chat.TextComponent; import net.kyori.adventure.text.format.TextDecoration;
import net.md_5.bungee.api.chat.hover.content.Text;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class FightCommand extends SWCommand { public class FightCommand extends SWCommand {
@ -41,23 +40,21 @@ public class FightCommand extends SWCommand {
} }
private static void getModes(Chatter sender, String precommand, boolean historic){ private static void getModes(Chatter sender, String precommand, boolean historic){
TextComponent start = new TextComponent(); Component start = Component.empty();
TextComponent current = start;
for(ArenaMode mode : ArenaMode.getAllModes()){ for(ArenaMode mode : ArenaMode.getAllModes()){
if(mode.withoutChatName() || mode.isHistoric() != historic) if(mode.withoutChatName() || mode.isHistoric() != historic)
continue; continue;
String command = precommand + mode.getChatName(); String command = precommand + mode.getChatName();
current.setBold(true); start = start.append(Component
current.setColor(ChatColor.GRAY); .text(mode.getChatName() + " ")
current.setText(mode.getChatName() + " "); .color(NamedTextColor.GRAY)
current.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§e" + command))); .decorate(TextDecoration.BOLD)
current.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)); .hoverEvent(HoverEvent.showText(Component.text(("§e" + command))))
if(current != start) .clickEvent(ClickEvent.runCommand(command)));
start.addExtra(current);
current = new TextComponent();
} }
sender.sendMessage(ChatMessageType.SYSTEM, start); sender.sendMessage(start);
} }
private static boolean alreadyInArena(PlayerChatter sender){ private static boolean alreadyInArena(PlayerChatter sender){
@ -93,15 +90,13 @@ public class FightCommand extends SWCommand {
Arenaserver mergable = null; Arenaserver mergable = null;
synchronized (Subserver.getServerList()) { synchronized (Subserver.getServerList()) {
for (Subserver subserver : Subserver.getServerList()) { for (Subserver subserver : Subserver.getServerList()) {
if(subserver instanceof Arenaserver) { if(subserver instanceof Arenaserver arenaserver &&
Arenaserver arenaserver = (Arenaserver) subserver; (mode.getInternalName().equals(arenaserver.getMode()) && arenaserver.isAllowMerge() && arenaserver.getRegisteredServer().getPlayersConnected().size() == 1)) {
if(mode.getInternalName().equals(arenaserver.getMode()) && arenaserver.isAllowMerge() && arenaserver.getServer().getPlayers().size() == 1) {
mergable = arenaserver; mergable = arenaserver;
break; break;
} }
} }
} }
}
if(mergable == null) { if(mergable == null) {
declineMerge.run(sender, mode, map); declineMerge.run(sender, mode, map);
@ -115,7 +110,7 @@ public class FightCommand extends SWCommand {
}); });
Arenaserver finalMergable = mergable; Arenaserver finalMergable = mergable;
SWItem item = new SWItem(new Message("FIGHT_MERGE_INFO", mode.getDisplayName(), finalMergable.getMap()), 11); SWItem item = new SWItem(new Message("FIGHT_MERGE_INFO", mode.getDisplayName(), finalMergable.getMap()), 11);
item.addLore(new Message("FIGHT_MERGE_INFO_LORE_1", finalMergable.getServer().getPlayers().toArray(new ProxiedPlayer[1])[0].getName())); item.addLore(new Message("FIGHT_MERGE_INFO_LORE_1", finalMergable.getRegisteredServer().getPlayersConnected().toArray(new Player[1])[0].getUsername()));
inventory.addItem(4, item, click -> {}); inventory.addItem(4, item, click -> {});
inventory.addItem(8, new SWItem(new Message("FIGHT_MERGE_ACCEPT"), 10), click -> { inventory.addItem(8, new SWItem(new Message("FIGHT_MERGE_ACCEPT"), 10), click -> {
if(Subserver.getServerList().contains(finalMergable)) { if(Subserver.getServerList().contains(finalMergable)) {
@ -132,7 +127,7 @@ public class FightCommand extends SWCommand {
public void fight(@Validator("arenaPlayer") PlayerChatter sender, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) { public void fight(@Validator("arenaPlayer") PlayerChatter sender, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) {
createArena(sender, "/fight ", true, arenaMode, map, false, createArena(sender, "/fight ", true, arenaMode, map, false,
(p, mode, m) -> new ServerStarter().arena(mode, m).blueLeader(p.getPlayer()).callback( (p, mode, m) -> new ServerStarter().arena(mode, m).blueLeader(p.getPlayer()).callback(
arena -> Chatter.broadcast().system("FIGHT_BROADCAST", "FIGHT_BROADCAST_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/arena " + arena.getServer().getName()), mode.getDisplayName(), p.getPlayer().getName()) arena -> Chatter.broadcast().system("FIGHT_BROADCAST", "FIGHT_BROADCAST_HOVER", ClickEvent.runCommand("/arena " + arena.getServer().getName()), mode.getDisplayName(), p.getPlayer().getUsername())
).start() ).start()
); );
} }

Datei anzeigen

@ -1,13 +1,12 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.internal.Statement; import de.steamwar.sql.internal.Statement;
import net.md_5.bungee.BungeeCord;
import java.io.*; import java.io.*;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
@ -26,13 +25,13 @@ public class GDPRQuery extends SWCommand {
@Register @Register
public void generate(Chatter sender, SteamwarUser user) { public void generate(Chatter sender, SteamwarUser user) {
BungeeCord.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
try { try {
createZip(sender, user); createZip(sender, user);
} catch (IOException e) { } catch (IOException e) {
throw new SecurityException("Could not create zip", e); throw new SecurityException("Could not create zip", e);
} }
}); }).schedule();
} }
private void createZip(Chatter sender, SteamwarUser user) throws IOException { private void createZip(Chatter sender, SteamwarUser user) throws IOException {

Datei anzeigen

@ -19,10 +19,12 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.messages.Message;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.chat.ClickEvent; import de.steamwar.messages.Message;
import net.kyori.adventure.text.event.ClickEvent;
import java.util.function.Function;
public class HelpCommand extends SWCommand { public class HelpCommand extends SWCommand {
@ -32,7 +34,7 @@ public class HelpCommand extends SWCommand {
@Register @Register
public void genericCommand(Chatter sender) { public void genericCommand(Chatter sender) {
printPage(sender, ClickEvent.Action.RUN_COMMAND, printPage(sender, ClickEvent::runCommand,
"HELP_LOBBY", "/l", "HELP_LOBBY", "/l",
"HELP_BAU", "/build", "HELP_BAU", "/build",
"HELP_BAUSERVER", "/help build", "HELP_BAUSERVER", "/help build",
@ -65,12 +67,12 @@ public class HelpCommand extends SWCommand {
@Register({"build","other"}) @Register({"build","other"})
public void buildOther(Chatter sender) { public void buildOther(Chatter sender) {
printPage(sender, "HELP_BAU_GROUP_OTHER_TITLE", "HELP_TESTBLOCK", "HELP_SKULL", "HELP_BAUINFO"); printPage(sender, "HELP_BAU_GROUP_OTHER_TITLE", "HELP_TESTBLOCK", "HELP_SKULL", "HELP_BAUINFO");
sender.prefixless("HELP_SCHEMSUBMIT", new Message("HELP_SCHEMSUBMIT_HOVER"), new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.youtube.com/watch?v=9QrQ3UBWveE")); sender.prefixless("HELP_SCHEMSUBMIT", new Message("HELP_SCHEMSUBMIT_HOVER"), ClickEvent.openUrl("https://www.youtube.com/watch?v=9QrQ3UBWveE"));
} }
@Register("build") @Register("build")
public void sendBauHelpGroup(Chatter sender) { public void sendBauHelpGroup(Chatter sender) {
printPage(sender, ClickEvent.Action.RUN_COMMAND, printPage(sender, ClickEvent::runCommand,
"HELP_BAU_GROUP_ADMIN", "/help build admin", "HELP_BAU_GROUP_ADMIN", "/help build admin",
"HELP_BAU_GROUP_WORLD", "/help build world", "HELP_BAU_GROUP_WORLD", "/help build world",
"HELP_BAU_GROUP_PLAYER", "/help build player", "HELP_BAU_GROUP_PLAYER", "/help build player",
@ -83,7 +85,7 @@ public class HelpCommand extends SWCommand {
@Register({"build","owner"}) @Register({"build","owner"})
@Register({"build","bauwelt"}) @Register({"build","bauwelt"})
public void sendBauHelp(Chatter sender) { public void sendBauHelp(Chatter sender) {
printPage(sender, ClickEvent.Action.SUGGEST_COMMAND, printPage(sender, ClickEvent::suggestCommand,
"HELP_BAU_TP", "/build tp ", "HELP_BAU_TP", "/build tp ",
"HELP_BAU_ADDMEMBER", "/build addmember ", "HELP_BAU_ADDMEMBER", "/build addmember ",
"HELP_BAU_DELMEMBER", "/build delmember ", "HELP_BAU_DELMEMBER", "/build delmember ",
@ -96,13 +98,13 @@ public class HelpCommand extends SWCommand {
"HELP_BAU_UNLOCK", "/build unlock"); "HELP_BAU_UNLOCK", "/build unlock");
} }
private static void printPage(Chatter sender, ClickEvent.Action action, String... args) { private static void printPage(Chatter sender, Function<String, ClickEvent> action, String... args) {
for(int i = 0; i < args.length; i += 2) { for(int i = 0; i < args.length; i += 2) {
String message = args[i]; String message = args[i];
String hoverMessage = message + "_HOVER"; String hoverMessage = message + "_HOVER";
String command = args[i+1]; String command = args[i+1];
sender.system(message, new Message(hoverMessage), new ClickEvent(action, command)); sender.system(message, new Message(hoverMessage), action.apply(command));
} }
} }

Datei anzeigen

@ -24,7 +24,7 @@ import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.chat.ClickEvent; import net.kyori.adventure.text.event.ClickEvent;
public class HistoricCommand extends SWCommand { public class HistoricCommand extends SWCommand {
public HistoricCommand() { public HistoricCommand() {
@ -34,7 +34,7 @@ public class HistoricCommand extends SWCommand {
@Register @Register
public void historic(@Validator("arenaPlayer") PlayerChatter player, @Mapper("historicArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) { public void historic(@Validator("arenaPlayer") PlayerChatter player, @Mapper("historicArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) {
FightCommand.createArena(player, "/historic ", true, arenaMode, map, true, (p, mode, m) -> new ServerStarter().arena(mode, m).blueLeader(p.getPlayer()).callback( FightCommand.createArena(player, "/historic ", true, arenaMode, map, true, (p, mode, m) -> new ServerStarter().arena(mode, m).blueLeader(p.getPlayer()).callback(
arena -> Chatter.broadcast().system("HISTORIC_BROADCAST", "HISTORIC_BROADCAST_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/arena " + arena.getServer().getName()), mode.getDisplayName(), p.getPlayer().getName()) arena -> Chatter.broadcast().system("HISTORIC_BROADCAST", "HISTORIC_BROADCAST_HOVER", ClickEvent.runCommand("/arena " + arena.getServer().getName()), mode.getDisplayName(), p.getPlayer())
).start()); ).start());
} }
} }

Datei anzeigen

@ -23,7 +23,7 @@ import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.chat.ClickEvent; import net.kyori.adventure.text.event.ClickEvent;
public class JoinmeCommand extends SWCommand { public class JoinmeCommand extends SWCommand {
@ -33,6 +33,6 @@ public class JoinmeCommand extends SWCommand {
@Register @Register
public void genericCommand(PlayerChatter sender) { public void genericCommand(PlayerChatter sender) {
Chatter.broadcast().system("JOINME_BROADCAST", "JOINME_BROADCAST_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + sender.getPlayer().getName()), sender, sender.getPlayer().getServer().getInfo().getName()); Chatter.broadcast().system("JOINME_BROADCAST", "JOINME_BROADCAST_HOVER", ClickEvent.runCommand("/join " + sender.getPlayer().getUsername()), sender, sender.getPlayer().getCurrentServer().orElseThrow().getServerInfo().getName());
} }
} }

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class KickCommand extends SWCommand { public class KickCommand extends SWCommand {
@ -31,7 +31,7 @@ public class KickCommand extends SWCommand {
} }
@Register(description = "KICK_USAGE") @Register(description = "KICK_USAGE")
public void genericCommand(Chatter sender, @ErrorMessage("KICK_OFFLINE") ProxiedPlayer target, String... message) { public void genericCommand(Chatter sender, @ErrorMessage("KICK_OFFLINE") Player target, String... message) {
if (message.length == 0) { if (message.length == 0) {
Chatter.disconnect(target).system("KICK_NORMAL"); Chatter.disconnect(target).system("KICK_NORMAL");
} else { } else {

Datei anzeigen

@ -19,15 +19,13 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ServerConnection;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -40,36 +38,33 @@ public class ListCommand extends SWCommand {
super("list", ""); super("list", "");
} }
public static synchronized TreeMap<String, List<ProxiedPlayer>> getCustomTablist(){ public static synchronized TreeMap<String, List<Player>> getCustomTablist(){
TreeMap<String, List<ProxiedPlayer>> playerMap = new TreeMap<>(); TreeMap<String, List<Player>> playerMap = new TreeMap<>();
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { for (Player player : VelocityCore.getProxy().getAllPlayers()) {
Server pserver = player.getServer(); ServerConnection pserver = player.getCurrentServer().orElse(null);
if (pserver == null) //Happens temporarily if (pserver == null)
continue; continue;
ServerInfo server = pserver.getInfo(); Subserver subserver = Subserver.getSubserver(pserver.getServerInfo());
String serverName = server.getName();
Subserver subserver = Subserver.getSubserver(server);
if (subserver != null && subserver.getType() == Servertype.BAUSERVER) { if (subserver != null && subserver.getType() == Servertype.BAUSERVER) {
playerMap.computeIfAbsent("Bau", s -> new ArrayList<>()).add(player); playerMap.computeIfAbsent("Bau", s -> new ArrayList<>()).add(player);
} else { } else {
playerMap.computeIfAbsent(serverName, s -> new ArrayList<>()).add(player); playerMap.computeIfAbsent(pserver.getServerInfo().getName(), s -> new ArrayList<>()).add(player);
} }
} }
playerMap.forEach((server, players) -> players.sort((proxiedPlayer, t1) -> proxiedPlayer.getName().compareToIgnoreCase(t1.getName()))); playerMap.forEach((server, players) -> players.sort((player, t1) -> player.getUsername().compareToIgnoreCase(t1.getUsername())));
return playerMap; return playerMap;
} }
@Register @Register
public void list(Chatter sender) { public void list(Chatter sender) {
TreeMap<String, List<ProxiedPlayer>> playerMap = getCustomTablist(); TreeMap<String, List<Player>> playerMap = getCustomTablist();
for (String server : playerMap.navigableKeySet()) { for (String server : playerMap.navigableKeySet()) {
String serverName = server; String serverName = server;
if (server.equals("Bau")) { if (server.equals("Bau")) {
serverName = sender.parseToLegacy("TABLIST_BAU"); serverName = sender.parseToLegacy("TABLIST_BAU");
} }
sender.prefixless("LIST_COMMAND", serverName, playerMap.get(server).stream().map(CommandSender::getName).collect(Collectors.joining(", "))); sender.prefixless("LIST_COMMAND", serverName, playerMap.get(server).stream().map(Player::getUsername).collect(Collectors.joining(", ")));
} }
} }
} }

Datei anzeigen

@ -19,13 +19,13 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.listeners.ChatListener; import de.steamwar.bungeecore.listeners.ChatListener;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup; import de.steamwar.messages.ChatterGroup;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.IgnoreSystem; import de.steamwar.sql.IgnoreSystem;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import static de.steamwar.bungeecore.Storage.lastChats; import static de.steamwar.bungeecore.Storage.lastChats;
@ -36,12 +36,12 @@ public class MsgCommand extends SWCommand {
} }
@Register(description = "MSG_USAGE") @Register(description = "MSG_USAGE")
public void genericCommand(PlayerChatter sender, @ErrorMessage(value = "MSG_OFFLINE") ProxiedPlayer target, @ErrorMessage(value = "MSG_USAGE", allowEAs = false) String... message) { public void genericCommand(PlayerChatter sender, @ErrorMessage(value = "MSG_OFFLINE") Player target, @ErrorMessage(value = "MSG_USAGE", allowEAs = false) String... message) {
msg(sender, target, message); msg(sender, target, message);
} }
public static void msg(PlayerChatter sender, ProxiedPlayer target, String[] args) { public static void msg(PlayerChatter sender, Player target, String[] args) {
if(target == null || !target.isConnected()) { if(target == null) {
sender.system("MSG_OFFLINE"); sender.system("MSG_OFFLINE");
return; return;
} }
@ -57,7 +57,7 @@ public class MsgCommand extends SWCommand {
lastChats.put(target, sender.getPlayer()); lastChats.put(target, sender.getPlayer());
} }
public static void remove(ProxiedPlayer player){ public static void remove(Player player){
lastChats.remove(player); lastChats.remove(player);
} }
} }

Datei anzeigen

@ -20,7 +20,8 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import de.steamwar.bungeecore.BungeeCore; import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.bungeecore.listeners.ConnectionListener; import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.bungeecore.listeners.IPSanitizer; import de.steamwar.bungeecore.listeners.IPSanitizer;
@ -32,11 +33,6 @@ import de.steamwar.sql.BannedUserIPs;
import de.steamwar.sql.Punishment; import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm; import de.steamwar.sql.UserPerm;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
@ -77,7 +73,7 @@ public class PunishmentCommand {
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
// ignore, player does not exist // ignore, player does not exist
} catch (IOException e) { } catch (IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID " + playerName, e); VelocityCore.getLogger().log(Level.SEVERE, "Could not get offline player UUID " + playerName, e);
} }
return null; return null;
} }
@ -92,9 +88,9 @@ public class PunishmentCommand {
} }
public static void ban(SteamwarUser user, Timestamp time, String banReason, SteamwarUser punisher, boolean perma) { public static void ban(SteamwarUser user, Timestamp time, String banReason, SteamwarUser punisher, boolean perma) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(user.getUUID()); Player player = VelocityCore.getProxy().getPlayer(user.getUUID()).orElse(null);
if (player != null) { if (player != null) {
String ip = IPSanitizer.getTrueAddress(player.getPendingConnection()).getHostAddress(); String ip = IPSanitizer.getTrueAddress(player).getHostAddress();
Chatter.disconnect(player).system(punishmentMessage(user, Punishment.PunishmentType.Ban)); Chatter.disconnect(player).system(punishmentMessage(user, Punishment.PunishmentType.Ban));
for (BannedUserIPs banned : BannedUserIPs.get(ip)) { for (BannedUserIPs banned : BannedUserIPs.get(ip)) {
SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID()); SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID());
@ -220,7 +216,7 @@ public class PunishmentCommand {
@Register @Register
public void genericError(Chatter sender, String... args) { public void genericError(Chatter sender, String... args) {
sender.send(true, ChatMessageType.CHAT, null, null, new Message("PUNISHMENT_USAGE", command)); sender.system("PUNISHMENT_USAGE", command);
} }
@Mapper(value = "toPunish", local = true) @Mapper(value = "toPunish", local = true)
@ -233,8 +229,8 @@ public class PunishmentCommand {
@Override @Override
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) { public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
List<String> players = BungeeCord.getInstance().getPlayers().stream() List<String> players = VelocityCore.getProxy().getAllPlayers().stream()
.map(CommandSender::getName) .map(Player::getUsername)
.collect(Collectors.toList()); .collect(Collectors.toList());
players.add(s); players.add(s);
return players; return players;
@ -273,7 +269,7 @@ public class PunishmentCommand {
@Register @Register
public void genericError(Chatter sender, String... args) { public void genericError(Chatter sender, String... args) {
sender.send(true, ChatMessageType.CHAT, null, null, new Message("UNPUNISHMENT_USAGE", command)); sender.system("UNPUNISHMENT_USAGE", command);
} }
} }
} }

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.messages.Message;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.chat.ClickEvent; import de.steamwar.messages.Message;
import net.kyori.adventure.text.event.ClickEvent;
import java.util.Arrays; import java.util.Arrays;
@ -36,6 +36,6 @@ public class RulesCommand extends SWCommand {
sender.system("REGELN_RULES"); sender.system("REGELN_RULES");
for(String ruleset : Arrays.asList("REGELN_AS", "REGELN_MWG", "REGELN_WG", "REGELN_WS", "REGELN_QG", "REGELN_CONDUCT")) for(String ruleset : Arrays.asList("REGELN_AS", "REGELN_MWG", "REGELN_WG", "REGELN_WS", "REGELN_QG", "REGELN_CONDUCT"))
sender.prefixless(ruleset, new Message(ruleset + "_HOVER"), new ClickEvent(ClickEvent.Action.OPEN_URL, sender.parseToPlain(ruleset + "_URL"))); sender.prefixless(ruleset, new Message(ruleset + "_HOVER"), ClickEvent.openUrl(sender.parseToPlain(ruleset + "_URL")));
} }
} }

Datei anzeigen

@ -19,10 +19,9 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
public class ServerSwitchCommand extends SWCommand { public class ServerSwitchCommand extends SWCommand {
@ -35,7 +34,6 @@ public class ServerSwitchCommand extends SWCommand {
@Register @Register
public void genericCommand(PlayerChatter sender) { public void genericCommand(PlayerChatter sender) {
ServerInfo target = ProxyServer.getInstance().getServerInfo(serverName); sender.getPlayer().createConnectionRequest(VelocityCore.getProxy().getServer(serverName).orElseThrow()).fireAndForget();
sender.getPlayer().connect(target);
} }
} }

Datei anzeigen

@ -19,8 +19,10 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.messages.Message; import com.velocitypowered.api.proxy.ConnectionRequestBuilder;
import com.velocitypowered.api.proxy.server.ServerInfo;
import de.steamwar.bungeecore.Storage; import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.DiscordBot; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.inventory.SWItem; import de.steamwar.bungeecore.inventory.SWItem;
import de.steamwar.bungeecore.inventory.SWListInv; import de.steamwar.bungeecore.inventory.SWListInv;
@ -29,13 +31,13 @@ import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper; import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator; import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*; import de.steamwar.sql.*;
import net.md_5.bungee.api.*; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.chat.*; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.chat.hover.content.Text; import net.kyori.adventure.text.event.HoverEvent;
import net.md_5.bungee.api.config.ServerInfo; import net.kyori.adventure.text.format.NamedTextColor;
import net.md_5.bungee.api.event.ServerConnectEvent;
import java.net.*; import java.net.*;
import java.time.Instant; import java.time.Instant;
@ -306,7 +308,7 @@ public class TeamCommand extends SWCommand {
private String getMemberList(List<SteamwarUser> users, boolean leaders) { private String getMemberList(List<SteamwarUser> users, boolean leaders) {
return users.stream() return users.stream()
.filter(user -> user.isLeader() == leaders) .filter(user -> user.isLeader() == leaders)
.map(user -> (ProxyServer.getInstance().getPlayer(user.getUUID()) != null ? "§a" : "§e") + user.getUserName()) .map(user -> (VelocityCore.getProxy().getPlayer(user.getUUID()).isPresent() ? "§a" : "§e") + user.getUserName())
.collect(Collectors.joining(" ")); .collect(Collectors.joining(" "));
} }
@ -327,27 +329,25 @@ public class TeamCommand extends SWCommand {
Team tm = all.get(i); Team tm = all.get(i);
sender.prefixless("TEAM_LIST_TEAM", new Message("TEAM_LIST_TEAM_HOVER"), sender.prefixless("TEAM_LIST_TEAM", new Message("TEAM_LIST_TEAM_HOVER"),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team info " + tm.getTeamKuerzel()), tm.getTeamColor(), tm.getTeamKuerzel(), tm.getTeamName()); ClickEvent.runCommand("/team info " + tm.getTeamKuerzel()), tm.getTeamColor(), tm.getTeamKuerzel(), tm.getTeamName());
} }
BaseComponent beforePage = new TextComponent("«« "); Component beforePage = Component
if(page > 1){ .text("«« ")
beforePage.setColor(ChatColor.YELLOW); .color(page > 1 ? NamedTextColor.YELLOW : NamedTextColor.DARK_GRAY);
beforePage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(sender.parse("TEAM_LIST_PREV")))); if(page > 1)
beforePage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team list " + (page - 1))); beforePage = beforePage
}else .hoverEvent(HoverEvent.showText(sender.parse("TEAM_LIST_PREV")))
beforePage.setColor(ChatColor.DARK_GRAY); .clickEvent(ClickEvent.runCommand("/team list " + (page - 1)));
BaseComponent nextPage = sender.parse("TEAM_LIST_PAGE"); Component nextPage = sender.parse("TEAM_LIST_PAGE")
if(page < lastPage){ .color(page > 1 ? NamedTextColor.YELLOW : NamedTextColor.DARK_GRAY);
nextPage.setColor(ChatColor.YELLOW); if(page < lastPage)
nextPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(sender.parse("TEAM_LIST_NEXT")))); nextPage = nextPage
nextPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team list " + (page + 1))); .hoverEvent(HoverEvent.showText(sender.parse("TEAM_LIST_NEXT")))
}else .clickEvent(ClickEvent.runCommand("/team list " + (page + 1)));
nextPage.setColor(ChatColor.DARK_GRAY);
beforePage.addExtra(nextPage); sender.sendMessage(beforePage.append(nextPage));
sender.sendMessage(ChatMessageType.SYSTEM, beforePage);
} }
@Register("event") @Register("event")
@ -403,26 +403,21 @@ public class TeamCommand extends SWCommand {
InetSocketAddress address = new InetSocketAddress(targetTeam.getAddress(), targetTeam.getPort()); InetSocketAddress address = new InetSocketAddress(targetTeam.getAddress(), targetTeam.getPort());
ServerInfo serverInfo = Storage.teamServers.computeIfAbsent(targetTeam.getTeamId(), integer -> { ServerInfo serverInfo = Storage.teamServers.computeIfAbsent(targetTeam.getTeamId(), integer -> {
ServerInfo info = ProxyServer.getInstance().constructServerInfo("Team " + targetTeam.getTeamKuerzel(), address, "SteamWar.de - Teamserver", false); ServerInfo info = new ServerInfo("Team " + targetTeam.getTeamKuerzel(), address);
ProxyServer.getInstance().getServers().put(info.getName(), info); VelocityCore.getProxy().registerServer(info);
return info; return info;
}); });
if (!address.equals(serverInfo.getSocketAddress())) { if (!address.equals(serverInfo.getAddress())) {
serverInfo = Storage.teamServers.remove(targetTeam.getTeamId()); VelocityCore.getProxy().unregisterServer(Storage.teamServers.remove(targetTeam.getTeamId()));
ProxyServer.getInstance().getServers().remove(serverInfo.getName());
tp(sender, targetTeam); tp(sender, targetTeam);
return; return;
} }
sender.getPlayer().connect(ServerConnectRequest.builder() sender.getPlayer().createConnectionRequest(VelocityCore.getProxy().getServer(serverInfo.getName()).orElseThrow()).connect().whenComplete((result, throwable) -> {
.target(serverInfo) if(result.getStatus() != ConnectionRequestBuilder.Status.SUCCESS || throwable != null)
.reason(ServerConnectEvent.Reason.PLUGIN)
.callback((success, error) -> {
if (error != null)
sender.system("TEAM_OFFLINE"); sender.system("TEAM_OFFLINE");
}) });
.build());
} }
@Register(value = "server", description = "TEAM_SERVER_USAGE") @Register(value = "server", description = "TEAM_SERVER_USAGE")

Datei anzeigen

@ -19,6 +19,9 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.bungeecore.*; import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.util.BauLock; import de.steamwar.bungeecore.util.BauLock;
import de.steamwar.bungeecore.util.Chat19; import de.steamwar.bungeecore.util.Chat19;
@ -28,10 +31,6 @@ import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter; import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*; import de.steamwar.sql.*;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -51,11 +50,11 @@ public class TpCommand extends SWCommand {
@Register @Register
public void teleportCommand(PlayerChatter sender, @Mapper("to") String to, String... rest) { public void teleportCommand(PlayerChatter sender, @Mapper("to") String to, String... rest) {
ServerInfo server = getTarget(to); RegisteredServer server = getTarget(to);
//Give control of teleport command to server //Give control of teleport command to server
ProxiedPlayer p = sender.getPlayer(); Player p = sender.getPlayer();
if (server == p.getServer().getInfo() || server == null) { if (server == null || server.getPlayersConnected().contains(p)) {
if (rest.length == 0) { if (rest.length == 0) {
Chat19.chat(p, "/tp " + to); Chat19.chat(p, "/tp " + to);
} else { } else {
@ -70,7 +69,7 @@ public class TpCommand extends SWCommand {
@Mapper("to") @Mapper("to")
@Cached(cacheDuration = 10) @Cached(cacheDuration = 10)
public TypeMapper<String> tabCompleter() { public TypeMapper<String> tabCompleter() {
return new TypeMapper<String>() { return new TypeMapper<>() {
@Override @Override
public String map(Chatter sender, PreviousArguments previousArguments, String s) { public String map(Chatter sender, PreviousArguments previousArguments, String s) {
return s; return s;
@ -79,8 +78,8 @@ public class TpCommand extends SWCommand {
@Override @Override
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) { public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) { for (Player player : VelocityCore.getProxy().getAllPlayers()) {
list.add(player.getName()); list.add(player.getUsername());
} }
if (Event.get() != null) { if (Event.get() != null) {
EventStarter.getEventServer().keySet().forEach(teamId -> { EventStarter.getEventServer().keySet().forEach(teamId -> {
@ -89,23 +88,23 @@ public class TpCommand extends SWCommand {
list.add(team.getTeamKuerzel()); list.add(team.getTeamKuerzel());
}); });
} }
if (Storage.teamServers.containsValue(sender.getPlayer().getServer().getInfo())) { if (Storage.teamServers.containsValue(sender.getPlayer().getCurrentServer().orElseThrow().getServerInfo())) {
Storage.directTabItems.getOrDefault(sender.getPlayer(), Collections.emptyMap()).forEach((uuid, item) -> list.add(item.getUsername())); Storage.directTabItems.getOrDefault(sender.getPlayer(), Collections.emptyMap()).forEach((uuid, item) -> list.add(item.getProfile().getName()));
} }
return list; return list;
} }
}; };
} }
public static void teleport(PlayerChatter sender, ServerInfo server) { public static void teleport(PlayerChatter sender, RegisteredServer server) {
if(CheckCommand.isChecking(sender.getPlayer())){ if(CheckCommand.isChecking(sender.getPlayer())){
sender.system("CHECK_CHECKING"); sender.system("CHECK_CHECKING");
return; return;
} }
Subserver subserver = Subserver.getSubserver(server); Subserver subserver = Subserver.getSubserver(server.getServerInfo());
if(subserver == null) { if(subserver == null) {
sender.getPlayer().connect(server); sender.getPlayer().createConnectionRequest(server).fireAndForget();
return; return;
} }
@ -117,7 +116,7 @@ public class TpCommand extends SWCommand {
case BAUSERVER: case BAUSERVER:
Bauserver bauserver = (Bauserver) subserver; Bauserver bauserver = (Bauserver) subserver;
ProxiedPlayer checker = BungeeCord.getInstance().getPlayer(bauserver.getOwner()); Player checker = VelocityCore.getProxy().getPlayer(bauserver.getOwner()).orElse(null);
if (checker != null && CheckCommand.isChecking(checker)) { if (checker != null && CheckCommand.isChecking(checker)) {
if (!sender.user().hasPerm(UserPerm.CHECK) && CheckCommand.getCheckingSchem(checker).getOwner() != sender.user().getId()) { if (!sender.user().hasPerm(UserPerm.CHECK) && CheckCommand.getCheckingSchem(checker).getOwner() != sender.user().getId()) {
sender.system("JOIN_PLAYER_BLOCK"); sender.system("JOIN_PLAYER_BLOCK");
@ -143,13 +142,13 @@ public class TpCommand extends SWCommand {
SubserverSystem.sendPlayer(subserver, sender.getPlayer()); SubserverSystem.sendPlayer(subserver, sender.getPlayer());
} }
private static ServerInfo getTarget(String arg) { private static RegisteredServer getTarget(String arg) {
ServerInfo server = null; RegisteredServer server = null;
//Get target player server //Get target player server
ProxiedPlayer target = ProxyServer.getInstance().getPlayer(arg); Player target = VelocityCore.getProxy().getPlayer(arg).orElse(null);
if(target != null) if(target != null)
server = target.getServer().getInfo(); server = target.getCurrentServer().map(ServerConnection::getServer).orElse(server);
//Get target team event arena //Get target team event arena
if(server == null){ if(server == null){
@ -157,7 +156,7 @@ public class TpCommand extends SWCommand {
if(team != null){ if(team != null){
Subserver eventArena = EventStarter.getEventServer().get(team.getTeamId()); Subserver eventArena = EventStarter.getEventServer().get(team.getTeamId());
if(eventArena != null && Subserver.getServerList().contains(eventArena)) if(eventArena != null && Subserver.getServerList().contains(eventArena))
server = eventArena.getServer(); server = eventArena.getRegisteredServer();
} }
} }

Datei anzeigen

@ -33,7 +33,6 @@ import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Tutorial; import de.steamwar.sql.Tutorial;
import de.steamwar.sql.UserPerm; import de.steamwar.sql.UserPerm;
import net.md_5.bungee.api.ProxyServer;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
@ -100,7 +99,7 @@ public class TutorialCommand extends SWCommand {
return; return;
} else if(own && click.isShiftClick() && click.isRightClick()) { } else if(own && click.isShiftClick() && click.isRightClick()) {
tutorial.delete(); tutorial.delete();
SubserverSystem.deleteFolder(BungeeCore.local, world(tutorial).getPath()); SubserverSystem.deleteFolder(VelocityCore.local, world(tutorial).getPath());
openInventory(sender, released, own); openInventory(sender, released, own);
return; return;
} }
@ -147,15 +146,15 @@ public class TutorialCommand extends SWCommand {
} }
subserver.execute("save-all"); subserver.execute("save-all");
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
Tutorial tutorial = Tutorial.create(user.getId(), name, item); Tutorial tutorial = Tutorial.create(user.getId(), name, item);
File tutorialWorld = world(tutorial); File tutorialWorld = world(tutorial);
if (tutorialWorld.exists()) if (tutorialWorld.exists())
SubserverSystem.deleteFolder(BungeeCore.local, tutorialWorld.getPath()); SubserverSystem.deleteFolder(VelocityCore.local, tutorialWorld.getPath());
ServerStarter.copyWorld(BungeeCore.local, tempWorld.getPath(), tutorialWorld.getPath()); ServerStarter.copyWorld(VelocityCore.local, tempWorld.getPath(), tutorialWorld.getPath());
sender.system("TUTORIAL_CREATED"); sender.system("TUTORIAL_CREATED");
}, 1, TimeUnit.SECONDS); }).delay(1, TimeUnit.SECONDS).schedule();
} }
private File world(Tutorial tutorial) { private File world(Tutorial tutorial) {

Datei anzeigen

@ -46,7 +46,7 @@ public class TypeMappers {
} }
private static TypeMapper<ArenaMode> arenaModeTypeMapper(boolean historic) { private static TypeMapper<ArenaMode> arenaModeTypeMapper(boolean historic) {
return new TypeMapper<ArenaMode>() { return new TypeMapper<>() {
@Override @Override
public ArenaMode map(Chatter sender, PreviousArguments previousArguments, String s) { public ArenaMode map(Chatter sender, PreviousArguments previousArguments, String s) {
return ArenaMode.getByChat(s); return ArenaMode.getByChat(s);
@ -60,7 +60,7 @@ public class TypeMappers {
} }
private static TypeMapper<String> arenaMapTypeMapper() { private static TypeMapper<String> arenaMapTypeMapper() {
return new TypeMapper<String>() { return new TypeMapper<>() {
@Override @Override
public String map(Chatter sender, PreviousArguments previousArguments, String s) { public String map(Chatter sender, PreviousArguments previousArguments, String s) {
if (previousArguments.userArgs.length == 0) return null; if (previousArguments.userArgs.length == 0) return null;

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.util.AuthManager; import de.steamwar.bungeecore.discord.util.AuthManager;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
@ -51,7 +51,7 @@ public class VerifyCommand extends SWCommand {
User user = AuthManager.connectAuth(sender.user(), code); User user = AuthManager.connectAuth(sender.user(), code);
if(user != null) { if(user != null) {
BungeeCore.get().getLogger().log(Level.INFO, sender.user().getUserName() + " Verified with Discorduser: " + user.getIdLong()); VelocityCore.getLogger().log(Level.INFO, sender.user().getUserName() + " Verified with Discorduser: " + user.getIdLong());
sender.system("VERIFY_SUCCESS", user.getAsTag()); sender.system("VERIFY_SUCCESS", user.getAsTag());
} else { } else {
sender.system("VERIFY_INVALID"); sender.system("VERIFY_INVALID");

Datei anzeigen

@ -19,19 +19,19 @@
package de.steamwar.bungeecore.commands; package de.steamwar.bungeecore.commands;
import de.steamwar.messages.Message; import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.Storage; import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.mods.ModUtils; import de.steamwar.bungeecore.mods.ModUtils;
import de.steamwar.command.PreviousArguments; import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper; import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.sql.*; import de.steamwar.sql.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import net.md_5.bungee.BungeeCord; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.DecimalFormat; import java.text.DecimalFormat;
@ -66,21 +66,21 @@ public class WhoisCommand extends SWCommand {
sender.system("WHOIS_USERNAME", user.getUserName()); sender.system("WHOIS_USERNAME", user.getUserName());
sender.system("WHOIS_PREFIX", user.prefix().getColorCode() + user.prefix().getChatPrefix()); sender.system("WHOIS_PREFIX", user.prefix().getColorCode() + user.prefix().getChatPrefix());
sender.system("WHOIS_TEAM", new Message("WHOIS_TEAM_HOVER", team.getTeamName()), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team info " + team.getTeamKuerzel()), team.getTeamColor(), team.getTeamKuerzel(), team.getTeamName()); sender.system("WHOIS_TEAM", new Message("WHOIS_TEAM_HOVER", team.getTeamName()), ClickEvent.runCommand("/team info " + team.getTeamKuerzel()), team.getTeamColor(), team.getTeamKuerzel(), team.getTeamName());
if (!sender.user().hasPerm(UserPerm.TEAM)) if (!sender.user().hasPerm(UserPerm.TEAM))
return; return;
if (sender.user().hasPerm(UserPerm.MODERATION)) { if (sender.user().hasPerm(UserPerm.MODERATION)) {
sender.system("WHOIS_ID", user.getId()); sender.system("WHOIS_ID", user.getId());
sender.system("WHOIS_UUID", new Message("WHOIS_UUID_HOVER"), new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, user.getUUID().toString()), user.getUUID().toString()); sender.system("WHOIS_UUID", new Message("WHOIS_UUID_HOVER"), ClickEvent.copyToClipboard(user.getUUID().toString()), user.getUUID().toString());
if (user.getDiscordId() != null) if (user.getDiscordId() != null)
sender.system("WHOIS_DISCORD_ID", user.getDiscordId()); sender.system("WHOIS_DISCORD_ID", user.getDiscordId());
sender.system("WHOIS_PERMS", user.perms().stream().map(Enum::name).collect(Collectors.joining(", "))); sender.system("WHOIS_PERMS", user.perms().stream().map(Enum::name).collect(Collectors.joining(", ")));
} }
ProxiedPlayer target = BungeeCord.getInstance().getPlayer(user.getUUID()); Player target = VelocityCore.getProxy().getPlayer(user.getUUID()).orElse(null);
Timestamp firstJoin = user.getFirstjoin(); Timestamp firstJoin = user.getFirstjoin();
double onlineTime = user.getOnlinetime(); double onlineTime = user.getOnlinetime();
if(firstJoin == null && target != null) { if(firstJoin == null && target != null) {
@ -93,8 +93,8 @@ public class WhoisCommand extends SWCommand {
if(target != null) { if(target != null) {
sender.system("WHOIS_CURRENT_PLAYED", new DecimalFormat("####.##").format((Instant.now().getEpochSecond() - Storage.sessions.get(target).toInstant().getEpochSecond()) / 60d)); sender.system("WHOIS_CURRENT_PLAYED", new DecimalFormat("####.##").format((Instant.now().getEpochSecond() - Storage.sessions.get(target).toInstant().getEpochSecond()) / 60d));
sender.system("WHOIS_CURRENT_SERVER", target.getServer().getInfo().getName()); sender.system("WHOIS_CURRENT_SERVER", target.getCurrentServer().orElseThrow().getServerInfo().getName());
sender.system("WHOIS_CURRENT_PROTOCOL", target.getPendingConnection().getVersion()); sender.system("WHOIS_CURRENT_PROTOCOL", target.getProtocolVersion().getMostRecentSupportedVersion());
List<Mod> mods = ModUtils.getPlayerModMap().get(user.getUUID()); List<Mod> mods = ModUtils.getPlayerModMap().get(user.getUUID());
if(mods == null) if(mods == null)

Datei anzeigen

@ -19,15 +19,12 @@
package de.steamwar.bungeecore.discord; package de.steamwar.bungeecore.discord;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.channels.*; import de.steamwar.bungeecore.discord.channels.*;
import de.steamwar.bungeecore.discord.config.DiscordConfig; import de.steamwar.bungeecore.discord.listeners.ChannelListener;
import de.steamwar.bungeecore.discord.config.DiscordRole;
import de.steamwar.bungeecore.discord.config.DiscordTicketType;
import de.steamwar.bungeecore.discord.listeners.DiscordSchemUpload; import de.steamwar.bungeecore.discord.listeners.DiscordSchemUpload;
import de.steamwar.bungeecore.discord.listeners.DiscordTeamEvent; import de.steamwar.bungeecore.discord.listeners.DiscordTeamEvent;
import de.steamwar.bungeecore.discord.listeners.DiscordTicketHandler; import de.steamwar.bungeecore.discord.listeners.DiscordTicketHandler;
import de.steamwar.bungeecore.discord.listeners.ChannelListener;
import de.steamwar.bungeecore.discord.util.AuthManager; import de.steamwar.bungeecore.discord.util.AuthManager;
import de.steamwar.command.SWCommand; import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
@ -46,7 +43,6 @@ import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.md_5.bungee.api.ProxyServer;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.awt.*; import java.awt.*;
@ -56,7 +52,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.logging.Level;
public class DiscordBot { public class DiscordBot {
public static final String ARGUMENT_NAME = "arguments"; public static final String ARGUMENT_NAME = "arguments";
@ -73,7 +68,7 @@ public class DiscordBot {
} }
public static Guild getGuild() { public static Guild getGuild() {
return instance.jda.getGuildById(DiscordConfig.GUILD); return instance.jda.getGuildById(instance.config.getGuild());
} }
@Getter @Getter
@ -85,37 +80,39 @@ public class DiscordBot {
@Getter @Getter
private StaticMessageChannel eventChannel; private StaticMessageChannel eventChannel;
@Getter
private final DiscordConfig config;
@Getter @Getter
private final JDA jda; private final JDA jda;
public DiscordBot() { public DiscordBot(DiscordConfig config) {
instance = this; this.config = config;
try { try {
jda = JDABuilder jda = JDABuilder
.createDefault(DiscordConfig.TOKEN) .createDefault(config.getToken())
.setStatus(OnlineStatus.ONLINE) .setStatus(OnlineStatus.ONLINE)
.setMemberCachePolicy(MemberCachePolicy.ONLINE) .setMemberCachePolicy(MemberCachePolicy.ONLINE)
.build(); .build();
} catch (LoginException e) { } catch (LoginException e) {
throw new SecurityException("Could not Login: " + DiscordConfig.TOKEN, e); throw new SecurityException("Could not login", e);
} }
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), this::asyncInit); instance = this;
VelocityCore.schedule(this::asyncInit).schedule();
} }
private void asyncInit() { private void asyncInit() {
try { try {
jda.awaitReady(); jda.awaitReady();
} catch (InterruptedException e) { } catch (InterruptedException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Interrupted during JDA ready wait", e); Thread.currentThread().interrupt();
return;
} }
activity(); activity();
new StaticMessageChannel(DiscordConfig.ROLES_CHANNEL, () -> new MessageBuilder() new StaticMessageChannel(config.channel("roles"), () -> new MessageBuilder()
.setContent(DiscordConfig.ROLES_BASE_MESSAGE) .setContent("**Rollenvergabe**\nKlicke um eine Rolle zu bekommen:")
.setActionRows(ActionRow.of(DiscordConfig.ROLES.stream().map(DiscordRole::toButton).toArray(Button[]::new))), event -> InteractionReply.reply(event, reply -> { .setActionRows(ActionRow.of(config.getRoles().values().stream().map(DiscordConfig.DiscordRole::toButton).toArray(Button[]::new))), event -> InteractionReply.reply(event, reply -> {
Member member = event.getMember(); Member member = event.getMember();
Guild guild = event.getGuild(); Guild guild = event.getGuild();
Role role = guild.getRoleById(event.getComponentId()); Role role = guild.getRoleById(event.getComponentId());
@ -128,12 +125,12 @@ public class DiscordBot {
reply.system("DC_ROLE_ADDED", role.getAsMention()); reply.system("DC_ROLE_ADDED", role.getAsMention());
} }
})); }));
new StaticMessageChannel(DiscordConfig.RULES_CHANNEL, () -> new MessageBuilder() new StaticMessageChannel(config.channel("rules"), () -> new MessageBuilder()
.setEmbeds(new EmbedBuilder() .setEmbeds(new EmbedBuilder()
.setDescription(String.join("\n", DiscordConfig.RULES_RULES)) .setDescription(String.join("\n", config.getRules()))
.setColor(Color.GRAY) .setColor(Color.GRAY)
.setAuthor("SteamWar", "https://steamwar.de") .setAuthor("SteamWar", "https://steamwar.de")
.setTitle(DiscordConfig.RULES_TITLE) .setTitle("Regeln und Infos")
.build()) .build())
.setActionRows( .setActionRows(
ActionRow.of(Button.link("https://steamwar.de", "Website"), Button.link("https://steamwar.de/youtube", "YouTube")), ActionRow.of(Button.link("https://steamwar.de", "Website"), Button.link("https://steamwar.de/youtube", "YouTube")),
@ -142,26 +139,26 @@ public class DiscordBot {
if(event.getComponentId().equals("auth")) if(event.getComponentId().equals("auth"))
event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + AuthManager.createDiscordAuthToken(event.getUser()) + "`` auf dem Minecraft Server ein").setEphemeral(true).queue(); event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + AuthManager.createDiscordAuthToken(event.getUser()) + "`` auf dem Minecraft Server ein").setEphemeral(true).queue();
}); });
new StaticMessageChannel(DiscordConfig.TICKET_CHANNEL, () -> new MessageBuilder() new StaticMessageChannel(config.channel("ticket"), () -> new MessageBuilder()
.setEmbeds(new EmbedBuilder() .setEmbeds(new EmbedBuilder()
.setDescription(DiscordConfig.TICKET_MESSAGE) .setDescription("Hier kannst du Tickets öffnen, welche nur von dir und Teammitgliedern eingesehen werden können.")
.setTitle("SteamWar Tickets") .setTitle("SteamWar Tickets")
.setColor(Color.RED) .setColor(Color.RED)
.build()) .build())
.setActionRows(ActionRow.of(Arrays.stream(DiscordTicketType.values()).map(DiscordTicketType::toButton).toArray(Button[]::new))), DiscordTicketHandler::openTicket); .setActionRows(ActionRow.of(Arrays.stream(DiscordTicketType.values()).map(DiscordTicketType::toButton).toArray(Button[]::new))), DiscordTicketHandler::openTicket);
eventChannel = new StaticMessageChannel(DiscordConfig.EVENTS_CHANNEL, EventChannel::get); eventChannel = new StaticMessageChannel(config.channel("events"), EventChannel::get);
StaticMessageChannel checklistChannel = new StaticMessageChannel(DiscordConfig.SCHEMATICS_CHANNEL, ChecklistChannel::get); StaticMessageChannel checklistChannel = new StaticMessageChannel(config.channel("checklist"), ChecklistChannel::get);
announcementChannel = new DiscordChannel(DiscordConfig.ANNOUNCEMENTS_CHANNEL) { announcementChannel = new DiscordChannel(config.channel("announcement")) {
@Override @Override
public void received(GuildMessageReceivedEvent event) { public void received(GuildMessageReceivedEvent event) {
Chatter.broadcast().system("ALERT", event.getMessage().getContentDisplay()); Chatter.broadcast().system("ALERT", event.getMessage().getContentDisplay());
} }
}; };
ingameChat = new DiscordChatRoom(DiscordConfig.INGAME_CHANNEL, "CHAT_DISCORD_GLOBAL", Chatter::broadcast); ingameChat = new DiscordChatRoom(config.channel("ingame"), "CHAT_DISCORD_GLOBAL", Chatter::broadcast);
serverTeamChat = new DiscordChatRoom(DiscordConfig.SERVER_TEAM_CHANNEL, "CHAT_SERVERTEAM", Chatter::serverteam); serverTeamChat = new DiscordChatRoom(config.channel("serverteam"), "CHAT_SERVERTEAM", Chatter::serverteam);
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { VelocityCore.schedule(() -> {
try { try {
activity(); activity();
eventChannel.update(); eventChannel.update();
@ -169,7 +166,7 @@ public class DiscordBot {
} catch (ErrorResponseException e) { } catch (ErrorResponseException e) {
//ignored //ignored
} }
}, 30, 30, TimeUnit.SECONDS); }).repeat(30, TimeUnit.SECONDS).schedule();
Guild guild = getGuild(); Guild guild = getGuild();
commandSetup(jda.retrieveCommands(), jda.updateCommands()); commandSetup(jda.retrieveCommands(), jda.updateCommands());
@ -199,7 +196,7 @@ public class DiscordBot {
Event event = Event.get(); Event event = Event.get();
jda.getPresence().setActivity(event != null ? Activity.competing("dem Event " + event.getEventName()) : Activity.playing("auf SteamWar.de")); jda.getPresence().setActivity(event != null ? Activity.competing("dem Event " + event.getEventName()) : Activity.playing("auf SteamWar.de"));
} else { } else {
int count = ProxyServer.getInstance().getOnlineCount(); int count = VelocityCore.getProxy().getPlayerCount();
jda.getPresence().setActivity(Activity.playing(count == 1 ? "mit 1 Spieler" : ("mit " + count + " Spielern"))); jda.getPresence().setActivity(Activity.playing(count == 1 ? "mit 1 Spieler" : ("mit " + count + " Spielern")));
} }

Datei anzeigen

@ -0,0 +1,89 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 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.discord;
import de.steamwar.bungeecore.VelocityCore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.interactions.components.ButtonStyle;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Getter
public class DiscordConfig {
public static DiscordConfig load() {
File file = new File(System.getProperty("user.home"), "discord.yml");
if(!file.exists() || VelocityCore.get().getConfig().isEventmode())
return null;
TypeDescription typeDescription = new TypeDescription(DiscordConfig.class);
typeDescription.addPropertyParameters("roles", String.class, DiscordRole.class);
Constructor constructor = new Constructor(DiscordConfig.class, new LoaderOptions());
constructor.addTypeDescription(typeDescription);
try{
return new Yaml(constructor).load(new FileInputStream(file));
}catch(IOException e){
throw new SecurityException("Could not load discord bot configuration", e);
}
}
public String channel(String type) {
return channels.get(type);
}
private String token;
private String guild;
private Map<String, String> channels;
private Map<String, String> ranks;
private Map<String, DiscordRole> roles;
private List<String> rules;
private String ticketcategory;
//public static final Map<UserPerm, String> RANKS = new HashMap<>();
@Data
@AllArgsConstructor
public static class DiscordRole {
private String emoji;
private String label;
private String roleId;
public Button toButton() {
return Button.of(ButtonStyle.SECONDARY, roleId, label, Emoji.fromUnicode(emoji));
}
}
}

Datei anzeigen

@ -1,23 +1,23 @@
/* /*
This file is a part of the SteamWar software. * This file is a part of the SteamWar software.
*
Copyright (C) 2020 SteamWar.de-Serverteam * Copyright (C) 2024 SteamWar.de-Serverteam
*
This program is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. * (at your option) any later version.
*
This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
*
You should have received a copy of the GNU Affero General Public License * 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/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package de.steamwar.bungeecore.discord.config; package de.steamwar.bungeecore.discord;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import net.dv8tion.jda.api.entities.Emoji; import net.dv8tion.jda.api.entities.Emoji;

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore.discord.channels; package de.steamwar.bungeecore.discord.channels;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.DiscordBot; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.listeners.ChannelListener; import de.steamwar.bungeecore.discord.listeners.ChannelListener;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
@ -31,8 +31,8 @@ import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent; import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.chat.BaseComponent; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
@AllArgsConstructor @AllArgsConstructor
@ -92,12 +92,12 @@ public class DiscordChannel extends Chatter.PlayerlessChatter {
} }
@Override @Override
public BaseComponent parse(boolean prefixed, Message message) { public Component parse(boolean prefixed, Message message) {
return super.parse(false, message); return super.parse(false, message);
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
send(msg.toPlainText()); send(PlainTextComponentSerializer.plainText().serialize(msg));
} }
} }

Datei anzeigen

@ -20,8 +20,8 @@
package de.steamwar.bungeecore.discord.channels; package de.steamwar.bungeecore.discord.channels;
import net.dv8tion.jda.api.interactions.Interaction; import net.dv8tion.jda.api.interactions.Interaction;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.chat.BaseComponent; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -46,13 +46,13 @@ public class InteractionReply extends DiscordChannel {
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
if(replied) { if(replied) {
super.sendMessage(type, msg); super.sendMessage(msg);
return; return;
} }
messages.add(msg.toPlainText()); messages.add(PlainTextComponentSerializer.plainText().serialize(msg));
} }
public void submit() { public void submit() {

Datei anzeigen

@ -1,106 +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.discord.config;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.sql.UserPerm;
import lombok.experimental.UtilityClass;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@UtilityClass
public class DiscordConfig {
public static boolean loaded = false;
public static String TOKEN;
public static String GUILD;
public static String ANNOUNCEMENTS_CHANNEL;
public static String EVENTS_CHANNEL;
public static String INGAME_CHANNEL;
public static String SERVER_TEAM_CHANNEL;
public static String SCHEMATICS_CHANNEL;
public static String ROLES_CHANNEL;
public static String ROLES_BASE_MESSAGE;
public static final List<DiscordRole> ROLES = new ArrayList<>();
public static String RULES_CHANNEL;
public static String RULES_TITLE;
public static List<String> RULES_RULES;
public static String TICKET_CATEGORY;
public static String TICKET_CHANNEL;
public static String TICKET_MESSAGE;
public static String TICKET_LOG;
public static final Map<UserPerm, String> RANKS = new HashMap<>();
static {
File file = new File(System.getProperty("user.home"), "discord.yml");
if(file.exists() && !BungeeCore.EVENT_MODE) {
try {
DiscordConfig.loadConfig(ConfigurationProvider.getProvider(YamlConfiguration.class).load(file));
} catch (IOException e) {
throw new SecurityException("Could not load discord bot configuration", e);
}
}
}
public static void loadConfig(Configuration config) {
TOKEN = config.getString("token");
GUILD = config.getString("guild");
ANNOUNCEMENTS_CHANNEL = config.getString("announcements-channel");
EVENTS_CHANNEL = config.getString("events-channel");
INGAME_CHANNEL = config.getString("ingame-channel");
SERVER_TEAM_CHANNEL = config.getString("server-team-channel");
SCHEMATICS_CHANNEL = config.getString("schematics-channel");
Configuration rolesSection = config.getSection("roles-claim");
ROLES_CHANNEL = rolesSection.getString("channel");
ROLES_BASE_MESSAGE = rolesSection.getString("base");
for (String roles : rolesSection.getSection("roles").getKeys()) {
Configuration role = rolesSection.getSection("roles").getSection(roles);
ROLES.add(new DiscordRole(role.getString("emoji"),
role.getString("label"),
role.getString("roleId")));
}
Configuration rulesSection = config.getSection("rules");
RULES_CHANNEL = rulesSection.getString("channel");
RULES_TITLE = rulesSection.getString("title");
RULES_RULES = rulesSection.getStringList("rules");
Configuration ticketSection = config.getSection("tickets");
TICKET_CATEGORY = ticketSection.getString("category");
TICKET_CHANNEL = ticketSection.getString("channel");
TICKET_MESSAGE = ticketSection.getString("message");
TICKET_LOG = ticketSection.getString("log");
Configuration ranksSections = config.getSection("ranks");
for (String type : ranksSections.getKeys()) {
RANKS.put(UserPerm.valueOf(type.toUpperCase()), ranksSections.getString(type));
}
loaded = true;
}
}

Datei anzeigen

@ -1,39 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.config;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.interactions.components.ButtonStyle;
@Data
@AllArgsConstructor
public class DiscordRole {
private String emoji;
private String label;
private String roleId;
public Button toButton() {
return Button.of(ButtonStyle.SECONDARY, roleId, label, Emoji.fromUnicode(emoji));
}
}

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.discord.listeners; package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.channels.DiscordChannel; import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.sql.NodeData; import de.steamwar.sql.NodeData;
import de.steamwar.sql.Punishment; import de.steamwar.sql.Punishment;
@ -82,7 +82,7 @@ public class DiscordSchemUpload extends ListenerAdapter {
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} catch (ExecutionException | IOException e) { } catch (ExecutionException | IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not upload schem \"" + name + "\" for user \"" + user.getUserName() + "\"", e); VelocityCore.getLogger().log(Level.SEVERE, "Could not upload schem \"" + name + "\" for user \"" + user.getUserName() + "\"", e);
sender.system("DC_SCHEMUPLOAD_ERROR", name); sender.system("DC_SCHEMUPLOAD_ERROR", name);
} }
} }

Datei anzeigen

@ -19,9 +19,9 @@
package de.steamwar.bungeecore.discord.listeners; package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.channels.InteractionReply; import de.steamwar.bungeecore.discord.channels.InteractionReply;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.sql.Event; import de.steamwar.sql.Event;
import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
@ -29,9 +29,11 @@ import org.jetbrains.annotations.NotNull;
public class DiscordTeamEvent extends ListenerAdapter { public class DiscordTeamEvent extends ListenerAdapter {
private final String eventsChannel = DiscordBot.getInstance().getConfig().channel("events");
@Override @Override
public void onSelectionMenu(@NotNull SelectionMenuEvent event) { public void onSelectionMenu(@NotNull SelectionMenuEvent event) {
if(!event.getChannel().getId().equals(DiscordConfig.EVENTS_CHANNEL)) if(!event.getChannel().getId().equals(eventsChannel))
return; return;
if(event.getSelectedOptions().isEmpty()) { if(event.getSelectedOptions().isEmpty()) {
@ -59,7 +61,7 @@ public class DiscordTeamEvent extends ListenerAdapter {
return; return;
} }
BungeeCore.get().getTeamCommand().event(reply, tournament); VelocityCore.get().getTeamCommand().event(reply, tournament);
}); });
} }
} }

Datei anzeigen

@ -19,13 +19,13 @@
package de.steamwar.bungeecore.discord.listeners; package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.messages.Message; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.DiscordTicketType;
import de.steamwar.bungeecore.discord.channels.DiscordChannel; import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.bungeecore.discord.channels.InteractionReply; import de.steamwar.bungeecore.discord.channels.InteractionReply;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.bungeecore.discord.config.DiscordTicketType;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup; import de.steamwar.messages.ChatterGroup;
import de.steamwar.messages.Message;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
@ -38,7 +38,7 @@ import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
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.chat.ClickEvent; import net.kyori.adventure.text.event.ClickEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.awt.*; import java.awt.*;
@ -48,11 +48,15 @@ import java.util.stream.Collectors;
public class DiscordTicketHandler extends ListenerAdapter { public class DiscordTicketHandler extends ListenerAdapter {
private static final String TICKET_CATEGORY = DiscordBot.getInstance().getConfig().getTicketcategory();
private static final String TICKET_LOG = DiscordBot.getInstance().getConfig().channel("ticketlog");
private static final String TICKET_CHANNEL = DiscordBot.getInstance().getConfig().channel("ticket");
public static void openTicket(GenericComponentInteractionCreateEvent event) { public static void openTicket(GenericComponentInteractionCreateEvent event) {
DiscordTicketType ticketType = DiscordTicketType.valueOf(event.getComponentId().toUpperCase()); DiscordTicketType ticketType = DiscordTicketType.valueOf(event.getComponentId().toUpperCase());
SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong()); SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong());
TextChannel ticketChannel = event.getGuild().getCategoryById(DiscordConfig.TICKET_CATEGORY).createTextChannel((user == null ? event.getUser().getName() : user.getUserName()) + "-" + event.getComponentId() + "-" + System.currentTimeMillis() % 1000).complete(); TextChannel ticketChannel = event.getGuild().getCategoryById(TICKET_CATEGORY).createTextChannel((user == null ? event.getUser().getName() : user.getUserName()) + "-" + event.getComponentId() + "-" + System.currentTimeMillis() % 1000).complete();
ticketChannel.createPermissionOverride(event.getMember()).setAllow( ticketChannel.createPermissionOverride(event.getMember()).setAllow(
Permission.VIEW_CHANNEL, Permission.VIEW_CHANNEL,
Permission.MESSAGE_WRITE, Permission.MESSAGE_WRITE,
@ -79,7 +83,7 @@ public class DiscordTicketHandler extends ListenerAdapter {
@Override @Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) { public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
TextChannel channel = event.getTextChannel(); TextChannel channel = event.getTextChannel();
if(channel.getParent() != null && channel.getParent().getId().equals(DiscordConfig.TICKET_CATEGORY) && event.getComponentId().startsWith("close-")) { if(channel.getParent() != null && channel.getParent().getId().equals(TICKET_CATEGORY) && event.getComponentId().startsWith("close-")) {
LinkedList<StringBuilder> messages = channel.getIterableHistory().complete().stream() LinkedList<StringBuilder> messages = channel.getIterableHistory().complete().stream()
.filter(message -> !message.getAuthor().isSystem() && !message.getAuthor().isBot()) .filter(message -> !message.getAuthor().isSystem() && !message.getAuthor().isBot())
.map(message -> { .map(message -> {
@ -124,7 +128,7 @@ public class DiscordTicketHandler extends ListenerAdapter {
embedBuilder.setAuthor(user.getName(), null, user.getAvatarUrl()); embedBuilder.setAuthor(user.getName(), null, user.getAvatarUrl());
} }
TextChannel logChannel = event.getGuild().getTextChannelById(DiscordConfig.TICKET_LOG); TextChannel logChannel = event.getGuild().getTextChannelById(TICKET_LOG);
messageBuilders.forEach(stringBuilder -> logChannel.sendMessage(new MessageBuilder().setEmbeds(embedBuilder.setDescription(stringBuilder.toString()).build()).build()).queue()); messageBuilders.forEach(stringBuilder -> logChannel.sendMessage(new MessageBuilder().setEmbeds(embedBuilder.setDescription(stringBuilder.toString()).build()).build()).queue());
Chatter.serverteam().prefixless("DISCORD_TICKET_CLOSED", channel.getName()); Chatter.serverteam().prefixless("DISCORD_TICKET_CLOSED", channel.getName());
@ -137,9 +141,9 @@ public class DiscordTicketHandler extends ListenerAdapter {
TextChannel channel = event.getChannel(); TextChannel channel = event.getChannel();
if( if(
channel.getParent() != null && channel.getParent() != null &&
channel.getParent().getId().equals(DiscordConfig.TICKET_CATEGORY) && channel.getParent().getId().equals(TICKET_CATEGORY) &&
!channel.getId().equals(DiscordConfig.TICKET_CHANNEL) && !channel.getId().equals(TICKET_CHANNEL) &&
!channel.getId().equals(DiscordConfig.TICKET_LOG) !channel.getId().equals(TICKET_LOG)
) { ) {
if(event.getAuthor().isBot()) if(event.getAuthor().isBot())
return; return;
@ -151,7 +155,7 @@ public class DiscordTicketHandler extends ListenerAdapter {
//ignored //ignored
} }
receivers.system("DISCORD_TICKET_MESSAGE", new Message("DISCORD_TICKET_HOVER"), new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw()); receivers.system("DISCORD_TICKET_MESSAGE", new Message("DISCORD_TICKET_HOVER"), ClickEvent.openUrl(event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw());
} }
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.discord.util; package de.steamwar.bungeecore.discord.util;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.discord.channels.DiscordChannel; import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
@ -50,8 +50,8 @@ public class AuthManager {
String code = Base64.getEncoder().encodeToString(randBytes); String code = Base64.getEncoder().encodeToString(randBytes);
TOKENS.put(code, user); TOKENS.put(code, user);
BungeeCore.get().getLogger().log(Level.INFO, "Created Discord Auth-Token: " + code + " for: " + user.getAsTag()); VelocityCore.getLogger().log(Level.INFO, "Created Discord Auth-Token: " + code + " for: " + user.getAsTag());
BungeeCore.get().getProxy().getScheduler().schedule(BungeeCore.get(), () -> TOKENS.remove(code), 10, TimeUnit.MINUTES); VelocityCore.schedule(() -> TOKENS.remove(code)).delay(10, TimeUnit.MINUTES).schedule();
return code; return code;
} }

Datei anzeigen

@ -20,7 +20,7 @@
package de.steamwar.bungeecore.discord.util; package de.steamwar.bungeecore.discord.util;
import de.steamwar.bungeecore.discord.DiscordBot; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.config.DiscordConfig; import de.steamwar.bungeecore.discord.DiscordConfig;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.commands.PunishmentCommand; import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.bungeecore.commands.WebpasswordCommand; import de.steamwar.bungeecore.commands.WebpasswordCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
@ -43,8 +43,8 @@ public class BanListener extends BasicListener {
@EventHandler @EventHandler
public void onLogin(LoginEvent event) { public void onLogin(LoginEvent event) {
event.registerIntent(BungeeCore.get()); event.registerIntent(VelocityCore.get());
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().runAsync(VelocityCore.get(), () -> {
PendingConnection connection = event.getConnection(); PendingConnection connection = event.getConnection();
SteamwarUser user = SteamwarUser.getOrCreate(connection.getUniqueId(), connection.getName(), ConnectionListener::newPlayer, WebpasswordCommand::changeUsername); SteamwarUser user = SteamwarUser.getOrCreate(connection.getUniqueId(), connection.getName(), ConnectionListener::newPlayer, WebpasswordCommand::changeUsername);
String ip = IPSanitizer.getTrueAddress(connection).getHostAddress(); String ip = IPSanitizer.getTrueAddress(connection).getHostAddress();
@ -52,7 +52,7 @@ public class BanListener extends BasicListener {
event.setCancelled(true); event.setCancelled(true);
BannedUserIPs.banIP(user.getId(), ip); BannedUserIPs.banIP(user.getId(), ip);
Chatter.of(event).system(PunishmentCommand.punishmentMessage(user, Punishment.PunishmentType.Ban)); Chatter.of(event).system(PunishmentCommand.punishmentMessage(user, Punishment.PunishmentType.Ban));
event.completeIntent(BungeeCore.get()); event.completeIntent(VelocityCore.get());
return; return;
} }
@ -89,7 +89,7 @@ public class BanListener extends BasicListener {
); );
} }
event.completeIntent(BungeeCore.get()); event.completeIntent(VelocityCore.get());
}); });
} }
} }

Datei anzeigen

@ -19,13 +19,13 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Listener;
public abstract class BasicListener implements Listener { public abstract class BasicListener implements Listener {
protected BasicListener(){ protected BasicListener(){
ProxyServer.getInstance().getPluginManager().registerListener(BungeeCore.get(), this); ProxyServer.getInstance().getPluginManager().registerListener(VelocityCore.get(), this);
} }
} }

Datei anzeigen

@ -20,7 +20,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.ArenaMode; import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.commands.PunishmentCommand; import de.steamwar.bungeecore.commands.PunishmentCommand;
@ -63,7 +63,7 @@ public class ChatListener extends BasicListener {
if (message.contains("jndi:ldap")) { if (message.contains("jndi:ldap")) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId()); SteamwarUser user = SteamwarUser.get(player.getUniqueId());
PunishmentCommand.ban(user, Punishment.PERMA_TIME, "Versuchte Exploit-Ausnutzung", SteamwarUser.get(-1), true); PunishmentCommand.ban(user, Punishment.PERMA_TIME, "Versuchte Exploit-Ausnutzung", SteamwarUser.get(-1), true);
BungeeCore.get().getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen jndi:ldap gebannt."); VelocityCore.getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen jndi:ldap gebannt.");
return; return;
} }
@ -172,7 +172,7 @@ public class ChatListener extends BasicListener {
private static void chatToReciever(Chatter receiver, Chatter msgReceiver, SteamwarUser sender, String format, String message) { private static void chatToReciever(Chatter receiver, Chatter msgReceiver, SteamwarUser sender, String format, String message) {
UserPerm.Prefix prefix = sender.prefix(); UserPerm.Prefix prefix = sender.prefix();
String chatColorCode = sender.hasPerm(UserPerm.TEAM) ? "§f" : "§7"; String chatColorCode = sender.hasPerm(UserPerm.TEAM) ? "§f" : "§7";
receiver.chat(new Message(format, receiver.prefixless(format,
sender, sender,
msgReceiver == null ? receiver : msgReceiver, msgReceiver == null ? receiver : msgReceiver,
highlightMentions(message, chatColorCode, receiver), highlightMentions(message, chatColorCode, receiver),
@ -180,7 +180,7 @@ public class ChatListener extends BasicListener {
UserElo.getEmblem(sender, rankedModes), UserElo.getEmblem(sender, rankedModes),
prefix.getColorCode(), prefix.getColorCode(),
prefix.getChatPrefix().length() == 0 ? "§f" : prefix.getChatPrefix() + " ", prefix.getChatPrefix().length() == 0 ? "§f" : prefix.getChatPrefix() + " ",
chatColorCode)); chatColorCode);
} }
private static boolean filteredCommand(Chatter sender, String message) { private static boolean filteredCommand(Chatter sender, String message) {
@ -197,7 +197,7 @@ public class ChatListener extends BasicListener {
TaskScheduler scheduler = ProxyServer.getInstance().getScheduler(); TaskScheduler scheduler = ProxyServer.getInstance().getScheduler();
for(int i = 0; i < delay.length; i++) { for(int i = 0; i < delay.length; i++) {
int finalI = i; int finalI = i;
scheduler.schedule(BungeeCore.get(), () -> sender.prefixless("CHAT_MSG", name, sender.user(), new Message(baseMessage + (finalI+1))), delay[i], TimeUnit.SECONDS); scheduler.schedule(VelocityCore.get(), () -> sender.prefixless("CHAT_MSG", name, sender.user(), new Message(baseMessage + (finalI+1))), delay[i], TimeUnit.SECONDS);
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
@ -144,7 +144,7 @@ public class ConnectionListener extends BasicListener {
} }
} }
ServerInfo kickTo = ProxyServer.getInstance().getServerInfo(BungeeCore.LOBBY_SERVER); ServerInfo kickTo = ProxyServer.getInstance().getServerInfo(VelocityCore.get().getConfig().getLobbyserver());
if (kickedFrom != null && kickedFrom.equals(kickTo)) { if (kickedFrom != null && kickedFrom.equals(kickTo)) {
return; return;

Datei anzeigen

@ -19,7 +19,8 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.VelocityCore;
import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.event.LoginEvent; import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.connection.InitialHandler; import net.md_5.bungee.connection.InitialHandler;
@ -51,8 +52,8 @@ public class IPSanitizer extends BasicListener {
} }
} }
public static InetAddress getTrueAddress(PendingConnection connection) { public static InetAddress getTrueAddress(Player player) {
return ((InetSocketAddress) getChannelWrapper(connection).getHandle().remoteAddress()).getAddress(); return player.getRemoteAddress().getAddress();
} }
@ -60,7 +61,7 @@ public class IPSanitizer extends BasicListener {
@EventHandler @EventHandler
public void loginEvent(LoginEvent e) { public void loginEvent(LoginEvent e) {
BungeeCore.get().getLogger().log(Level.INFO, e.getConnection().getSocketAddress() + " has logged in with user name " + e.getConnection().getName()); VelocityCore.getLogger().log(Level.INFO, e.getConnection().getSocketAddress() + " has logged in with user name " + e.getConnection().getName());
getChannelWrapper(e.getConnection()).setRemoteAddress(sanitized); getChannelWrapper(e.getConnection()).setRemoteAddress(sanitized);
} }
} }

Datei anzeigen

@ -20,7 +20,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import com.lunarclient.apollo.ApolloManager; import com.lunarclient.apollo.ApolloManager;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.bungeecore.commands.TeamCommand; import de.steamwar.bungeecore.commands.TeamCommand;
import de.steamwar.bungeecore.mods.*; import de.steamwar.bungeecore.mods.*;
@ -86,7 +86,7 @@ public class PluginMessage extends BasicListener {
void accept(DataOutputStream out) throws IOException; void accept(DataOutputStream out) throws IOException;
} }
private static final Parser UNKNOWN = event -> BungeeCore.get().getLogger().log(Level.WARNING, () -> "Undefined PluginMessage on channel " + event.getTag() + " from " + event.getSender() + " received.\n" + new String(event.getData()) + "\n" + Arrays.toString(event.getData())); private static final Parser UNKNOWN = event -> VelocityCore.getLogger().log(Level.WARNING, () -> "Undefined PluginMessage on channel " + event.getTag() + " from " + event.getSender() + " received.\n" + new String(event.getData()) + "\n" + Arrays.toString(event.getData()));
private static final Parser PASS_THROUGH = event -> event.setCancelled(false); private static final Parser PASS_THROUGH = event -> event.setCancelled(false);
private static final Parser DROP = event -> {}; private static final Parser DROP = event -> {};
@ -254,7 +254,7 @@ public class PluginMessage extends BasicListener {
ProxiedPlayer player = (ProxiedPlayer) event.getSender(); ProxiedPlayer player = (ProxiedPlayer) event.getSender();
for(String channel : new String(event.getData()).split("\0")) { for(String channel : new String(event.getData()).split("\0")) {
channelRegisterHandlers.getOrDefault(channel, p -> BungeeCore.get().getLogger().log(Level.WARNING, () -> p.getName() + " registered unknown channel " + channel)).accept(player); channelRegisterHandlers.getOrDefault(channel, p -> VelocityCore.getLogger().log(Level.WARNING, () -> p.getName() + " registered unknown channel " + channel)).accept(player);
} }
PASS_THROUGH.handle(event); PASS_THROUGH.handle(event);
@ -274,7 +274,7 @@ public class PluginMessage extends BasicListener {
String brand = DefinedPacket.readString(buf); String brand = DefinedPacket.readString(buf);
boolean lunarclient = brand.startsWith("lunarclient:"); boolean lunarclient = brand.startsWith("lunarclient:");
BungeeCore.get().getLogger().log(knownBrands.contains(brand) || lunarclient ? Level.INFO : Level.WARNING, () -> player.getName() + " joins with brand: " + brand); VelocityCore.getLogger().log(knownBrands.contains(brand) || lunarclient ? Level.INFO : Level.WARNING, () -> player.getName() + " joins with brand: " + brand);
if(lunarclient) if(lunarclient)
lunar.sendRestrictions(player); lunar.sendRestrictions(player);
@ -313,7 +313,7 @@ public class PluginMessage extends BasicListener {
} }
private Parser async(Parser parser) { private Parser async(Parser parser) {
return event -> ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> parser.handle(event)); return event -> ProxyServer.getInstance().getScheduler().runAsync(VelocityCore.get(), () -> parser.handle(event));
} }
private interface Parser { private interface Parser {

Datei anzeigen

@ -19,6 +19,8 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.Config;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.command.TypeValidator; import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
@ -27,24 +29,26 @@ import net.md_5.bungee.api.chat.ClickEvent;
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;
import java.util.Collections;
import java.util.List; import java.util.List;
public class PollSystem extends BasicListener { public class PollSystem extends BasicListener {
private static String question; public static void init() {
private static List<String> answers; poll = VelocityCore.get().getConfig().getPoll();
if(poll == null)
public static void init(String question, List<String> answers){ return;
PollSystem.question = question;
PollSystem.answers = answers;
if(noCurrentPoll()) if(noCurrentPoll())
return; return;
PollAnswer.setCurrentPoll(question); PollAnswer.setCurrentPoll(poll.getQuestion());
new PollSystem(); new PollSystem();
} }
private static Config.Poll poll = null;
@EventHandler @EventHandler
public void onPostLogin(PostLoginEvent event){ public void onPostLogin(PostLoginEvent event){
Chatter player = Chatter.of(event.getPlayer()); Chatter player = Chatter.of(event.getPlayer());
@ -59,15 +63,15 @@ public class PollSystem extends BasicListener {
public static void sendPoll(Chatter player) { public static void sendPoll(Chatter player) {
player.system("POLL_HEADER"); player.system("POLL_HEADER");
player.prefixless("POLL_HEADER2"); player.prefixless("POLL_HEADER2");
player.prefixless("POLL_QUESTION", question); player.prefixless("POLL_QUESTION", poll.getQuestion());
for(int i = 1; i <= answers.size(); i++) { for(int i = 1; i <= poll.getAnswers().size(); i++) {
player.prefixless("POLL_ANSWER", new Message("POLL_ANSWER_HOVER", answers.get(i-1)), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/poll " + i), answers.get(i-1)); player.prefixless("POLL_ANSWER", new Message("POLL_ANSWER_HOVER", poll.getAnswers().get(i-1)), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/poll " + i), poll.getAnswers().get(i-1));
} }
} }
public static boolean noCurrentPoll(){ private static boolean noCurrentPoll(){
return question == null || question.isEmpty(); return poll == null;
} }
public static TypeValidator<Chatter> noPoll() { public static TypeValidator<Chatter> noPoll() {
@ -81,10 +85,10 @@ public class PollSystem extends BasicListener {
} }
public static int answers(){ public static int answers(){
return answers.size(); return poll.getAnswers().size();
} }
public static String getAnswer(int i) { public static String getAnswer(int i) {
return answers.get(i); return poll.getAnswers().get(i);
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.sql.Session; import de.steamwar.sql.Session;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
@ -43,7 +43,7 @@ public class SessionManager extends BasicListener {
public void onDisconnect(PlayerDisconnectEvent e){ public void onDisconnect(PlayerDisconnectEvent e){
Timestamp timestamp = sessions.remove(e.getPlayer()); Timestamp timestamp = sessions.remove(e.getPlayer());
if(timestamp != null) { if(timestamp != null) {
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> Session.insertSession(SteamwarUser.get(e.getPlayer().getUniqueId()).getId(), timestamp)); ProxyServer.getInstance().getScheduler().runAsync(VelocityCore.get(), () -> Session.insertSession(SteamwarUser.get(e.getPlayer().getUniqueId()).getId(), timestamp));
} }
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.listeners; package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.network.NetworkSender; import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.network.packets.server.LocaleInvalidationPacket; import de.steamwar.network.packets.server.LocaleInvalidationPacket;
@ -32,7 +32,7 @@ public class SettingsChangedListener extends BasicListener {
@EventHandler @EventHandler
public void onSettingsChanged(SettingsChangedEvent event) { public void onSettingsChanged(SettingsChangedEvent event) {
BungeeCord.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> { BungeeCord.getInstance().getScheduler().runAsync(VelocityCore.get(), () -> {
ProxiedPlayer player = event.getPlayer(); ProxiedPlayer player = event.getPlayer();
SteamwarUser user = SteamwarUser.get(player.getUniqueId()); SteamwarUser user = SteamwarUser.get(player.getUniqueId());
user.setLocale(player.getLocale(), false); user.setLocale(player.getLocale(), false);

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.mods; package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.sql.Mod; import de.steamwar.sql.Mod;
@ -88,7 +88,7 @@ public class FML extends BasicListener {
unlocked.add(p.getUniqueId()); unlocked.add(p.getUniqueId());
} }
Chatter.disconnect(p).system("MODS_CHECKED"); Chatter.disconnect(p).system("MODS_CHECKED");
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { ProxyServer.getInstance().getScheduler().schedule(VelocityCore.get(), () -> {
synchronized (unlocked) { synchronized (unlocked) {
unlocked.remove(p.getUniqueId()); unlocked.remove(p.getUniqueId());
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.mods; package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import de.steamwar.bungeecore.listeners.IPSanitizer; import de.steamwar.bungeecore.listeners.IPSanitizer;
import de.steamwar.bungeecore.listeners.PluginMessage; import de.steamwar.bungeecore.listeners.PluginMessage;
@ -81,7 +81,7 @@ public class FML2 extends BasicListener {
IPSanitizer.getChannelWrapper(connection).getHandle().pipeline().get(HandlerBoss.class).setHandler(new FML2LoginHandler(event)); IPSanitizer.getChannelWrapper(connection).getHandle().pipeline().get(HandlerBoss.class).setHandler(new FML2LoginHandler(event));
event.registerIntent(BungeeCore.get()); event.registerIntent(VelocityCore.get());
if(forge) if(forge)
connection.unsafe().sendPacket(new LoginPayloadRequest(1, "forge:login", forgeModListPacket)); connection.unsafe().sendPacket(new LoginPayloadRequest(1, "forge:login", forgeModListPacket));
else else
@ -170,14 +170,14 @@ public class FML2 extends BasicListener {
if(!ModUtils.handleMods(event.getConnection().getUniqueId(), Locale.getDefault(), event::setReason, mods)) if(!ModUtils.handleMods(event.getConnection().getUniqueId(), Locale.getDefault(), event::setReason, mods))
event.setCancelled(true); event.setCancelled(true);
event.completeIntent(BungeeCore.get()); event.completeIntent(VelocityCore.get());
} }
private void abort(LoginPayloadResponse response, String error) { private void abort(LoginPayloadResponse response, String error) {
event.setReason(TextComponent.fromLegacy(error)); event.setReason(TextComponent.fromLegacy(error));
event.setCancelled(true); event.setCancelled(true);
event.completeIntent(BungeeCore.get()); event.completeIntent(VelocityCore.get());
BungeeCore.get().getLogger().log(Level.SEVERE, () -> error + "\n" + response); VelocityCore.getLogger().log(Level.SEVERE, () -> error + "\n" + response);
} }
} }
} }

Datei anzeigen

@ -22,7 +22,7 @@ package de.steamwar.bungeecore.mods;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.Storage; import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import de.steamwar.sql.Mod; import de.steamwar.sql.Mod;
@ -55,7 +55,7 @@ public class FabricModSender extends BasicListener {
neededFabricMods.add("fabricloader"); neededFabricMods.add("fabricloader");
neededQuiltMods.add("quilt_loader"); neededQuiltMods.add("quilt_loader");
BungeeCord.getInstance().getScheduler().schedule(BungeeCore.get(), () -> { BungeeCord.getInstance().getScheduler().schedule(VelocityCore.get(), () -> {
synchronized (Storage.fabricExpectPluginMessage) { synchronized (Storage.fabricExpectPluginMessage) {
for (Map.Entry<ProxiedPlayer, Long> entry : Storage.fabricExpectPluginMessage.entrySet()) { for (Map.Entry<ProxiedPlayer, Long> entry : Storage.fabricExpectPluginMessage.entrySet()) {
if (!Storage.fabricCheckedPlayers.containsKey(entry.getKey())) { if (!Storage.fabricCheckedPlayers.containsKey(entry.getKey())) {

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.mods; package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import net.md_5.bungee.api.event.PlayerHandshakeEvent; import net.md_5.bungee.api.event.PlayerHandshakeEvent;
import net.md_5.bungee.connection.InitialHandler; import net.md_5.bungee.connection.InitialHandler;
@ -58,9 +58,9 @@ public class Hostname extends BasicListener {
String hostname = event.getHandshake().getHost().toLowerCase(); String hostname = event.getHandshake().getHost().toLowerCase();
String extraDataInHandshake = ((InitialHandler) event.getConnection()).getExtraDataInHandshake(); String extraDataInHandshake = ((InitialHandler) event.getConnection()).getExtraDataInHandshake();
if (!knownHostnames.contains(hostname) && !hostname.endsWith(".steamwar.de")) { if (!knownHostnames.contains(hostname) && !hostname.endsWith(".steamwar.de")) {
BungeeCore.get().getLogger().log(Level.WARNING, () -> event.getConnection().getSocketAddress() + " connected with unknown hostname " + event.getHandshake() + " " + extraDataInHandshake); VelocityCore.getLogger().log(Level.WARNING, () -> event.getConnection().getSocketAddress() + " connected with unknown hostname " + event.getHandshake() + " " + extraDataInHandshake);
} else if (!knownExtraData.contains(extraDataInHandshake)) { } else if (!knownExtraData.contains(extraDataInHandshake)) {
BungeeCore.get().getLogger().log(Level.WARNING, () -> event.getConnection().getSocketAddress() + " connected with unknown extra data " + event.getHandshake() + " " + extraDataInHandshake); VelocityCore.getLogger().log(Level.WARNING, () -> event.getConnection().getSocketAddress() + " connected with unknown extra data " + event.getHandshake() + " " + extraDataInHandshake);
} }
} }
} }

Datei anzeigen

@ -22,7 +22,7 @@ package de.steamwar.bungeecore.mods;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.PluginMessage; import de.steamwar.bungeecore.listeners.PluginMessage;
import de.steamwar.sql.Mod; import de.steamwar.sql.Mod;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@ -74,7 +74,7 @@ public class LabyMod {
} }
if(message.has("mods")) { if(message.has("mods")) {
BungeeCore.get().getLogger().log(Level.WARNING, () -> "LabyMod External Mods for debugging: " + message.getAsJsonArray("mods")); VelocityCore.getLogger().log(Level.WARNING, () -> "LabyMod External Mods for debugging: " + message.getAsJsonArray("mods"));
for(JsonElement element : message.getAsJsonArray("mods")) { for(JsonElement element : message.getAsJsonArray("mods")) {
JsonObject addon = element.getAsJsonObject(); JsonObject addon = element.getAsJsonObject();
//TODO observe: FORGE and FABRIC mods available, do they always and with .jar? (would equal new mod platform) //TODO observe: FORGE and FABRIC mods available, do they always and with .jar? (would equal new mod platform)

Datei anzeigen

@ -32,7 +32,7 @@ import com.lunarclient.apollo.option.Options;
import com.lunarclient.apollo.player.AbstractApolloPlayer; import com.lunarclient.apollo.player.AbstractApolloPlayer;
import com.lunarclient.apollo.player.v1.ModMessage; import com.lunarclient.apollo.player.v1.ModMessage;
import com.lunarclient.apollo.player.v1.PlayerHandshakeMessage; import com.lunarclient.apollo.player.v1.PlayerHandshakeMessage;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.sql.Mod; import de.steamwar.sql.Mod;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -94,7 +94,7 @@ public class Lunar {
case TYPE_UNSPECIFIED: case TYPE_UNSPECIFIED:
case UNRECOGNIZED: case UNRECOGNIZED:
default: default:
BungeeCore.get().getLogger().log(Level.INFO, () -> player.getName() + " uses Lunar mod with unknown type " + mod); VelocityCore.getLogger().log(Level.INFO, () -> player.getName() + " uses Lunar mod with unknown type " + mod);
break; break;
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.mods; package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.commands.PunishmentCommand; import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.sql.Mod; import de.steamwar.sql.Mod;
@ -54,7 +54,7 @@ public class ModUtils {
Chatter sender = Chatter.of(uuid); Chatter sender = Chatter.of(uuid);
SteamwarUser user = sender.user(); SteamwarUser user = sender.user();
playerModMap.put(uuid,new ArrayList<>(mods)); playerModMap.put(uuid,new ArrayList<>(mods));
BungeeCore.get().getLogger().log(Level.INFO, user.getUserName() + " declares mods: " + mods.stream().map(mod -> mod.getPlatform() + ":" + mod.getModName()).collect(Collectors.joining(" "))); VelocityCore.getLogger().log(Level.INFO, user.getUserName() + " declares mods: " + mods.stream().map(mod -> mod.getPlatform() + ":" + mod.getModName()).collect(Collectors.joining(" ")));
ModType max = ModType.YELLOW; ModType max = ModType.YELLOW;
Iterator<Mod> it = mods.iterator(); Iterator<Mod> it = mods.iterator();
@ -83,7 +83,7 @@ public class ModUtils {
if(max == ModType.RED) { if(max == ModType.RED) {
PunishmentCommand.ban(user, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), message, SteamwarUser.get(-1), false); PunishmentCommand.ban(user, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), message, SteamwarUser.get(-1), false);
BungeeCore.get().getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + modList + " gebannt."); VelocityCore.getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + modList + " gebannt.");
} }
disconnect.accept(TextComponent.fromLegacy(message)); disconnect.accept(TextComponent.fromLegacy(message));

Datei anzeigen

@ -21,7 +21,7 @@ package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.Bauserver; import de.steamwar.bungeecore.Bauserver;
import de.steamwar.bungeecore.Builderserver; import de.steamwar.bungeecore.Builderserver;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.listeners.BasicListener; import de.steamwar.bungeecore.listeners.BasicListener;
import de.steamwar.bungeecore.listeners.PluginMessage; import de.steamwar.bungeecore.listeners.PluginMessage;
@ -55,7 +55,7 @@ public class ReplayMod extends BasicListener {
public void onPlayerJoin(ServerSwitchEvent event) { public void onPlayerJoin(ServerSwitchEvent event) {
ProxiedPlayer player = event.getPlayer(); ProxiedPlayer player = event.getPlayer();
ServerInfo server = player.getServer().getInfo(); ServerInfo server = player.getServer().getInfo();
if(ProxyServer.getInstance().getServerInfo(BungeeCore.LOBBY_SERVER) == server) if(ProxyServer.getInstance().getServerInfo(VelocityCore.get().getConfig().getLobbyserver()) == server)
return; return;
Subserver subserver = Subserver.getSubserver(server); Subserver subserver = Subserver.getSubserver(server);

Datei anzeigen

@ -19,22 +19,25 @@
package de.steamwar.bungeecore.network; package de.steamwar.bungeecore.network;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.network.packets.NetworkPacket; import de.steamwar.network.packets.NetworkPacket;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@UtilityClass @UtilityClass
public class NetworkSender { public class NetworkSender {
private static final ChannelIdentifier swBridge = MinecraftChannelIdentifier.create("sw", "bridge");
@SneakyThrows @SneakyThrows
public static void send(ProxiedPlayer player, NetworkPacket packet) { public static void send(Player player, NetworkPacket packet) {
player.getServer().sendData("sw:bridge", packet.serialize()); player.getCurrentServer().map(server -> server.sendPluginMessage(swBridge, packet.serialize()));
} }
public static void send(ServerInfo serverInfo, NetworkPacket packet) { public static void send(RegisteredServer server, NetworkPacket packet) {
ProxiedPlayer player = serverInfo.getPlayers().iterator().next(); server.sendPluginMessage(swBridge, packet.serialize());
send(player, packet);
} }
} }

Datei anzeigen

@ -19,14 +19,14 @@
package de.steamwar.bungeecore.network; package de.steamwar.bungeecore.network;
import com.velocitypowered.api.proxy.ServerConnection;
import de.steamwar.network.packets.MetaInfos; import de.steamwar.network.packets.MetaInfos;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import net.md_5.bungee.api.config.ServerInfo;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public class ServerMetaInfo implements MetaInfos { public class ServerMetaInfo implements MetaInfos {
private final ServerInfo sender; private final ServerConnection sender;
} }

Datei anzeigen

@ -19,22 +19,20 @@
package de.steamwar.bungeecore.network.handlers; package de.steamwar.bungeecore.network.handlers;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.ArenaMode; import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.network.packets.PacketHandler; import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.common.FightEndsPacket; import de.steamwar.network.packets.common.FightEndsPacket;
import de.steamwar.sql.SchematicType; import de.steamwar.sql.SchematicType;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserElo; import de.steamwar.sql.UserElo;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.md_5.bungee.BungeeTitle; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.ProxyServer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.md_5.bungee.api.Title; import net.kyori.adventure.title.Title;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.scheduler.TaskScheduler;
import java.time.Duration;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.IntFunction; import java.util.function.IntFunction;
@ -171,7 +169,10 @@ public class EloPlayerHandler extends PacketHandler {
} }
} }
private void animate(ProxiedPlayer player, String oldEmblem, String newEmblem, String arrowColor, int eloGain) { private void animate(Player player, String oldEmblem, String newEmblem, String arrowColor, int eloGain) {
if (player == null)
return;
String finalOldEmblem = (oldEmblem.isEmpty() ? "/" : oldEmblem).trim(); String finalOldEmblem = (oldEmblem.isEmpty() ? "/" : oldEmblem).trim();
String finalNewEmblem = (newEmblem.isEmpty() ? "/" : newEmblem).trim(); String finalNewEmblem = (newEmblem.isEmpty() ? "/" : newEmblem).trim();
@ -186,22 +187,20 @@ public class EloPlayerHandler extends PacketHandler {
String color = ((eloGain > 0) ? "§a+" : (eloGain == 0 ? "§7" : "§c")); String color = ((eloGain > 0) ? "§a+" : (eloGain == 0 ? "§7" : "§c"));
TaskScheduler scheduler = ProxyServer.getInstance().getScheduler();
double eloStep = eloGain / 40.0; double eloStep = eloGain / 40.0;
for (int i = 0; i < 40; i++) { for (int i = 0; i < 40; i++) {
BaseComponent eloGainComponent = TextComponent.fromLegacy(color + (int) (eloStep * (i + 1))); Component eloGainComponent = LegacyComponentSerializer.legacySection().deserialize(color + (int) (eloStep * (i + 1)));
int finalI = i; int finalI = i;
scheduler.schedule(BungeeCore.get(), () -> { VelocityCore.schedule(() -> player.showTitle(Title.title(
if (player == null) return; LegacyComponentSerializer.legacySection().deserialize(getRankup.apply(finalI)),
if (!player.isConnected()) return; eloGainComponent,
Title title = new BungeeTitle().title(TextComponent.fromLegacy(getRankup.apply(finalI))).subTitle(eloGainComponent).fadeIn(finalI == 0 ? 5 : 0).stay(40).fadeOut(finalI == 39 ? 5 : 0); Title.Times.times(Duration.ofMillis(finalI == 0 ? 250 : 0), Duration.ofSeconds(2), Duration.ofMillis(finalI == 39 ? 250 : 0))
title.send(player); ))).delay(i * 50L, TimeUnit.MILLISECONDS).schedule();
}, i * 50L, TimeUnit.MILLISECONDS);
} }
} }
private ProxiedPlayer player(int userId) { private Player player(int userId) {
return ProxyServer.getInstance().getPlayer(SteamwarUser.get(userId).getUUID()); return VelocityCore.getProxy().getPlayer(SteamwarUser.get(userId).getUUID()).orElse(null);
} }
private double getTimeFactor(int duration) { private double getTimeFactor(int duration) {

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore.network.handlers; package de.steamwar.bungeecore.network.handlers;
import de.steamwar.sql.SteamwarUser; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.network.packets.PacketHandler; import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.client.ExecuteCommandPacket; import de.steamwar.network.packets.client.ExecuteCommandPacket;
import net.md_5.bungee.api.ProxyServer; import de.steamwar.sql.SteamwarUser;
public class ExecuteCommandHandler extends PacketHandler { public class ExecuteCommandHandler extends PacketHandler {
@ -31,6 +31,6 @@ public class ExecuteCommandHandler extends PacketHandler {
SteamwarUser target = SteamwarUser.get(packet.getPlayerId()); SteamwarUser target = SteamwarUser.get(packet.getPlayerId());
String command = packet.getCommand(); String command = packet.getCommand();
ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getPlayer(target.getUUID()), command); VelocityCore.getProxy().getCommandManager().executeAsync(VelocityCore.getProxy().getPlayer(target.getUUID()).orElse(null), command);
} }
} }

Datei anzeigen

@ -19,6 +19,8 @@
package de.steamwar.bungeecore.network.handlers; package de.steamwar.bungeecore.network.handlers;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.bungeecore.network.NetworkSender; import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.network.ServerMetaInfo; import de.steamwar.bungeecore.network.ServerMetaInfo;
import de.steamwar.bungeecore.tablist.TablistManager; import de.steamwar.bungeecore.tablist.TablistManager;
@ -33,14 +35,14 @@ import java.util.Set;
public class FightInfoHandler extends PacketHandler { public class FightInfoHandler extends PacketHandler {
private static final Set<ServerInfo> lobbys = new HashSet<>(); private static final Set<RegisteredServer> lobbys = new HashSet<>();
public static void addLobby(ServerInfo lobby) { public static void addLobby(RegisteredServer lobby) {
lobbys.add(lobby); lobbys.add(lobby);
} }
public static boolean onLobby(ProxiedPlayer player) { public static boolean onLobby(Player player) {
return lobbys.contains(player.getServer().getInfo()); return player.getCurrentServer().map(connection -> lobbys.contains(connection.getServer())).orElse(false);
} }
@Handler @Handler

Datei anzeigen

@ -27,6 +27,6 @@ public class ImALobbyHandler extends PacketHandler {
@Handler @Handler
public void handle(ImALobbyPacket packet) { public void handle(ImALobbyPacket packet) {
FightInfoHandler.addLobby(((ServerMetaInfo) packet.getMetaInfos()).getSender()); FightInfoHandler.addLobby(((ServerMetaInfo) packet.getMetaInfos()).getSender().getServer());
} }
} }

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore.network.handlers; package de.steamwar.bungeecore.network.handlers;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.inventory.InvCallback; import de.steamwar.bungeecore.inventory.InvCallback;
import de.steamwar.bungeecore.inventory.SWInventory; import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.network.NetworkSender; import de.steamwar.bungeecore.network.NetworkSender;
@ -43,7 +44,7 @@ public class InventoryCallbackHandler extends PacketHandler {
if(!inventoryHashMap.containsKey(owner.getId())) { if(!inventoryHashMap.containsKey(owner.getId())) {
Chatter.of(owner).system("UPDATE_INTERRUPTION"); Chatter.of(owner).system("UPDATE_INTERRUPTION");
if(type == InventoryCallbackPacket.CallbackType.CLICK) { if(type == InventoryCallbackPacket.CallbackType.CLICK) {
NetworkSender.send(((ServerMetaInfo) packet.getMetaInfos()).getSender(), new CloseInventoryPacket(owner.getId())); NetworkSender.send((Player) ((ServerMetaInfo) packet.getMetaInfos()).getSender(), new CloseInventoryPacket(owner.getId()));
} }
return; return;
} }

Datei anzeigen

@ -19,20 +19,21 @@
package de.steamwar.bungeecore.network.handlers; package de.steamwar.bungeecore.network.handlers;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.ArenaMode; import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.ServerStarter; import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.sql.SchematicType; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.network.packets.PacketHandler; import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.client.PrepareSchemPacket; import de.steamwar.network.packets.client.PrepareSchemPacket;
import de.steamwar.sql.SchematicType;
import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class PrepareSchemHandler extends PacketHandler { public class PrepareSchemHandler extends PacketHandler {
@Handler @Handler
public void handle(PrepareSchemPacket packet) { public void handle(PrepareSchemPacket packet) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(SteamwarUser.get(packet.getPlayer()).getUUID()); Player player = VelocityCore.getProxy().getPlayer(SteamwarUser.get(packet.getPlayer()).getUUID()).orElse(null);
int schematicID = packet.getSchem(); int schematicID = packet.getSchem();
ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(packet.getSchemType())); ArenaMode mode = ArenaMode.getBySchemType(SchematicType.fromDB(packet.getSchemType()));

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.tablist; package de.steamwar.bungeecore.tablist;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Storage; import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
@ -50,7 +50,7 @@ public class TablistManager extends BasicListener {
private int seconds = 0; private int seconds = 0;
public TablistManager() { public TablistManager() {
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), this::updateTablist, 1, 1, TimeUnit.SECONDS); ProxyServer.getInstance().getScheduler().schedule(VelocityCore.get(), this::updateTablist, 1, 1, TimeUnit.SECONDS);
synchronized (tablists) { synchronized (tablists) {
ProxyServer.getInstance().getPlayers().forEach(player -> tablists.put(player, new Tablist(player))); ProxyServer.getInstance().getPlayers().forEach(player -> tablists.put(player, new Tablist(player)));
} }

Datei anzeigen

@ -19,30 +19,13 @@
package de.steamwar.bungeecore.util; package de.steamwar.bungeecore.util;
import net.md_5.bungee.ServerConnection; import com.velocitypowered.api.proxy.Player;
import net.md_5.bungee.api.connection.ProxiedPlayer; import lombok.experimental.UtilityClass;
import net.md_5.bungee.protocol.ChatChain;
import net.md_5.bungee.protocol.ProtocolConstants;
import net.md_5.bungee.protocol.SeenMessages;
import net.md_5.bungee.protocol.packet.ClientChat;
import net.md_5.bungee.protocol.packet.ClientCommand;
import java.util.BitSet;
import java.util.Collections;
@UtilityClass
public class Chat19 { public class Chat19 {
private Chat19(){}
public static void chat(ProxiedPlayer p, String message) { public static void chat(Player p, String message) {
int version = p.getPendingConnection().getVersion(); p.spoofChatInput(message);
if(version >= ProtocolConstants.MINECRAFT_1_19) {
if(message.startsWith("/")) {
((ServerConnection) p.getServer()).getCh().write(new ClientCommand(message.substring(1), System.currentTimeMillis(), 0, Collections.emptyMap(), false, new ChatChain(Collections.emptyList(), null), new SeenMessages(0, new BitSet(0))));
} else {
((ServerConnection) p.getServer()).getCh().write(new ClientChat(message, System.currentTimeMillis(), 0, version < ProtocolConstants.MINECRAFT_1_19_3 ? new byte[0] : null, false, new ChatChain(Collections.emptyList(), null), new SeenMessages(0, new BitSet(0))));
}
} else {
p.chat(message);
}
} }
} }

Datei anzeigen

@ -19,16 +19,14 @@
package de.steamwar.command; package de.steamwar.command;
import de.steamwar.bungeecore.BungeeCore; import com.velocitypowered.api.command.SimpleCommand;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.messages.Message; import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.DiscordBot; import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import lombok.Getter; import lombok.Getter;
import net.md_5.bungee.api.CommandSender; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.TabExecutor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -43,9 +41,12 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
TypeUtils.init(); TypeUtils.init();
} }
private final String name;
@Getter @Getter
private final String permission; private final String permission;
private Command command; private final String[] aliases;
private SimpleCommand command;
private final List<String> defaultHelpMessages = new ArrayList<>(); private final List<String> defaultHelpMessages = new ArrayList<>();
@ -59,7 +60,9 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
protected SWCommand(String command, String permission, String... aliases) { protected SWCommand(String command, String permission, String... aliases) {
super(Chatter.class, command, aliases); super(Chatter.class, command, aliases);
this.name = command;
this.permission = permission; this.permission = permission;
this.aliases = aliases;
create = true; create = true;
createAndSafeCommand(command, aliases); createAndSafeCommand(command, aliases);
unregister(); unregister();
@ -75,54 +78,57 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
@Override @Override
protected void createAndSafeCommand(String command, String[] aliases) { protected void createAndSafeCommand(String command, String[] aliases) {
if (!create) return; if (!create) return;
this.command = new TabCompletableCommand(command, permission, aliases) { this.command = new SimpleCommand() {
@Override @Override
public void execute(CommandSender commandSender, String[] strings) { public void execute(Invocation invocation) {
SWCommand.this.execute(Chatter.of(commandSender), null, strings); SWCommand.this.execute(Chatter.of(invocation.source()), invocation.alias(), invocation.arguments());
} }
@Override @Override
public Iterable<String> onTabComplete(CommandSender commandSender, String[] strings) { public List<String> suggest(Invocation invocation) {
return SWCommand.this.tabComplete(Chatter.of(commandSender), null, strings); return SWCommand.this.tabComplete(Chatter.of(invocation.source()), invocation.alias(), invocation.arguments());
}
@Override
public boolean hasPermission(Invocation invocation) {
//TODO nicer solution?
return permission != null && Chatter.of(invocation.source()).user().perms().stream().noneMatch(perm -> Arrays.asList(ConnectionListener.getCommandPermissions().getOrDefault(perm, new String[0])).contains(permission));
} }
}; };
} }
private abstract static class TabCompletableCommand extends Command implements TabExecutor {
public TabCompletableCommand(String name, String permission, String... aliases) {
super(name, permission, aliases);
}
}
@Override @Override
public void unregister() { public void unregister() {
if (command == null) return; if (command == null)
ProxyServer.getInstance().getPluginManager().unregisterCommand(this.command); return;
DiscordBot.getCommands().remove(command.getName()); VelocityCore.getProxy().getCommandManager().unregister(name);
for(String alias : command.getAliases()) DiscordBot.getCommands().remove(name);
for(String alias : aliases)
DiscordBot.getCommands().remove(alias); DiscordBot.getCommands().remove(alias);
} }
@Override @Override
public void register() { public void register() {
if (command == null) return; if (command == null)
ProxyServer.getInstance().getPluginManager().registerCommand(BungeeCore.get(), this.command); return;
DiscordBot.getCommands().put(command.getName(), this); VelocityCore.getProxy().getCommandManager().register(name, command, aliases);
for(String alias : command.getAliases()) DiscordBot.getCommands().put(name, this);
for(String alias : aliases)
DiscordBot.getCommands().put(alias, this); DiscordBot.getCommands().put(alias, this);
} }
@Override @Override
protected void commandSystemError(Chatter sender, CommandFrameworkException e) { protected void commandSystemError(Chatter sender, CommandFrameworkException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, e.getMessage(), e); VelocityCore.getLogger().log(Level.SEVERE, e.getMessage(), e);
sender.prefixless("COMMAND_SYSTEM_ERROR"); sender.prefixless("COMMAND_SYSTEM_ERROR");
} }
@Override @Override
protected void commandSystemWarning(Supplier<String> message) { protected void commandSystemWarning(Supplier<String> message) {
BungeeCore.get().getLogger().log(Level.WARNING, message); VelocityCore.getLogger().log(Level.WARNING, message);
} }
public void addDefaultHelpMessage(String message) { public void addDefaultHelpMessage(String message) {
@ -137,10 +143,10 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
@Register(noTabComplete = true) @Register(noTabComplete = true)
public void internalHelp(Chatter sender, String... args) { public void internalHelp(Chatter sender, String... args) {
try { try {
sender.prefixless("COMMAND_HELP_HEAD", command.getName()); sender.prefixless("COMMAND_HELP_HEAD", name);
defaultHelpMessages.forEach(sender::prefixless); defaultHelpMessages.forEach(sender::prefixless);
} catch (Exception e) { } catch (Exception e) {
BungeeCore.get().getLogger().log(Level.WARNING, "Failed to send help message", e); VelocityCore.getLogger().log(Level.WARNING, "Failed to send help message", e);
return; return;
} }
AtomicInteger atomicInteger = new AtomicInteger(); AtomicInteger atomicInteger = new AtomicInteger();
@ -172,12 +178,11 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
private void send(Chatter chatter, SubCommand<Chatter> subCommand) { private void send(Chatter chatter, SubCommand<Chatter> subCommand) {
try { try {
for (String s : subCommand.description) { for (String s : subCommand.description) {
String hover = "§8/§e" + command.getName() + " " + String.join(" ", subCommand.subCommand); String hover = "§8/§e" + name + " " + String.join(" ", subCommand.subCommand);
String suggest = "/" + command.getName() + " " + String.join(" ", subCommand.subCommand); chatter.prefixless(s, new Message("PLAIN_STRING", hover), ClickEvent.suggestCommand("/" + name + " " + String.join(" ", subCommand.subCommand)));
chatter.prefixless(s, new Message("PLAIN_STRING", hover), new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggest));
} }
} catch (Exception e) { } catch (Exception e) {
BungeeCore.get().getLogger().log(Level.WARNING, "Failed to send description of registered method '" + subCommand.method + "' with description '" + Arrays.toString(subCommand.description) + "'", e); VelocityCore.getLogger().log(Level.WARNING, "Failed to send description of registered method '" + subCommand.method + "' with description '" + Arrays.toString(subCommand.description) + "'", e);
} }
} }
} }

Datei anzeigen

@ -19,14 +19,15 @@
package de.steamwar.command; package de.steamwar.command;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.ServerVersion; import de.steamwar.bungeecore.ServerVersion;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.commands.TypeMappers; import de.steamwar.bungeecore.commands.TypeMappers;
import de.steamwar.messages.Chatter; import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Team; import de.steamwar.sql.Team;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -37,19 +38,19 @@ import java.util.stream.Stream;
public class TypeUtils { public class TypeUtils {
static void init() { static void init() {
SWCommandUtils.addMapper(ProxiedPlayer.class, SWCommandUtils.createMapper(BungeeCord.getInstance()::getPlayer, s -> BungeeCord.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).collect(Collectors.toList()))); SWCommandUtils.addMapper(Player.class, SWCommandUtils.createMapper(s -> VelocityCore.getProxy().getPlayer(s).orElse(null), s -> VelocityCore.getProxy().getAllPlayers().stream().map(Player::getUsername).collect(Collectors.toList())));
SWCommandUtils.addMapper(SteamwarUser.class, SWCommandUtils.createMapper(SteamwarUser::get, s -> BungeeCord.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).collect(Collectors.toList()))); SWCommandUtils.addMapper(SteamwarUser.class, SWCommandUtils.createMapper(SteamwarUser::get, s -> VelocityCore.getProxy().getAllPlayers().stream().map(Player::getUsername).collect(Collectors.toList())));
SWCommandUtils.addMapper(ServerVersion.class, new TypeMapper<ServerVersion>() { SWCommandUtils.addMapper(ServerVersion.class, new TypeMapper<>() {
@Override @Override
public ServerVersion map(Chatter sender, PreviousArguments previousArguments, String s) { public ServerVersion map(Chatter sender, PreviousArguments previousArguments, String s) {
ProxiedPlayer player = sender.getPlayer(); Player player = sender.getPlayer();
if (player != null && s.isEmpty()) { if (player != null && s.isEmpty()) {
int version = player.getPendingConnection().getVersion(); ProtocolVersion version = player.getProtocolVersion();
if (version > 762) { // Version > 1.19.4 if (version.greaterThan(ProtocolVersion.MINECRAFT_1_19_4)) {
return ServerVersion.PAPER_20; return ServerVersion.PAPER_20;
} else if (version > 578) { // Version > 1.15.2 } else if (version.greaterThan(ProtocolVersion.MINECRAFT_1_15_2)) {
return ServerVersion.PAPER_19; return ServerVersion.PAPER_19;
} else if (version > 340) { // Version > 1.12.2 } else if (version.greaterThan(ProtocolVersion.MINECRAFT_1_12_2)) {
return ServerVersion.SPIGOT_15; return ServerVersion.SPIGOT_15;
} else { } else {
return ServerVersion.SPIGOT_12; return ServerVersion.SPIGOT_12;

Datei anzeigen

@ -19,21 +19,20 @@
package de.steamwar.messages; package de.steamwar.messages;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.bungeecore.Servertype; import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver; import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm; import de.steamwar.sql.UserPerm;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.CommandSender; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.ProxyServer; import net.kyori.adventure.text.event.HoverEvent;
import net.md_5.bungee.api.chat.BaseComponent; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.md_5.bungee.api.chat.ClickEvent; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.hover.content.Text;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.command.ConsoleCommandSender;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.MessageFormat; import java.text.MessageFormat;
@ -48,8 +47,8 @@ import java.util.stream.Stream;
public interface Chatter { public interface Chatter {
static Stream<ProxiedPlayer> allPlayers() { static Stream<Player> allPlayers() {
return ProxyServer.getInstance().getPlayers().stream(); return VelocityCore.getProxy().getAllPlayers().stream();
} }
static Stream<Chatter> allStream() { static Stream<Chatter> allStream() {
@ -63,7 +62,7 @@ public interface Chatter {
static ChatterGroup globalChat() { static ChatterGroup globalChat() {
return new ChatterGroup(Stream.concat(Stream.of(Chatter.console()), allPlayers().filter(player -> { return new ChatterGroup(Stream.concat(Stream.of(Chatter.console()), allPlayers().filter(player -> {
Subserver subserver = Subserver.getSubserver(player); Subserver subserver = Subserver.getSubserver(player);
return subserver == null || !(subserver.getType() == Servertype.ARENA && subserver.getServer() == player.getServer().getInfo()); return subserver == null || !(subserver.getType() == Servertype.ARENA && subserver.getServer() == player.getCurrentServer().get().getServerInfo());
}).map(Chatter::of))); }).map(Chatter::of)));
} }
@ -75,41 +74,37 @@ public interface Chatter {
Locale getLocale(); Locale getLocale();
boolean chatShown(); boolean chatShown();
void sendMessage(ChatMessageType type, BaseComponent msg); void sendMessage(Component msg);
ProxiedPlayer getPlayer(); Player getPlayer();
default <T> T withPlayerOrOffline(Function<ProxiedPlayer, T> withPlayer, Supplier<T> withOffline) { default <T> T withPlayerOrOffline(Function<Player, T> withPlayer, Supplier<T> withOffline) {
ProxiedPlayer player = getPlayer(); Player player = getPlayer();
if(player == null) if(player == null)
return withOffline.get(); return withOffline.get();
else else
return withPlayer.apply(player); return withPlayer.apply(player);
} }
default void withPlayerOrOffline(Consumer<ProxiedPlayer> withPlayer, Runnable withOffline) { default void withPlayerOrOffline(Consumer<Player> withPlayer, Runnable withOffline) {
ProxiedPlayer player = getPlayer(); Player player = getPlayer();
if(player == null) if(player == null)
withOffline.run(); withOffline.run();
else else
withPlayer.accept(player); withPlayer.accept(player);
} }
default void withPlayer(Consumer<ProxiedPlayer> function) { default void withPlayer(Consumer<Player> function) {
withPlayerOrOffline(function, () -> {}); withPlayerOrOffline(function, () -> {});
} }
default void chat(Message message) {
send(false, ChatMessageType.CHAT, null, null, message);
}
default void system(String format, Object... params) { default void system(String format, Object... params) {
system(new Message(format, params)); system(new Message(format, params));
} }
default void system(Message message) { default void system(Message message) {
send(true, ChatMessageType.SYSTEM, null, null, message); send(true, null, null, message);
} }
default void system(String format, Message onHover, ClickEvent onClick, Object... params) { default void system(String format, Message onHover, ClickEvent onClick, Object... params) {
send(true, ChatMessageType.SYSTEM, onHover, onClick, new Message(format, params)); send(true, onHover, onClick, new Message(format, params));
} }
default void prefixless(String format, Object... params) { default void prefixless(String format, Object... params) {
@ -117,16 +112,16 @@ public interface Chatter {
} }
default void prefixless(String format, Message onHover, ClickEvent onClick, Object... params) { default void prefixless(String format, Message onHover, ClickEvent onClick, Object... params) {
send(false, ChatMessageType.SYSTEM, onHover, onClick, new Message(format, params)); send(false, onHover, onClick, new Message(format, params));
} }
default void send(boolean prefixed, ChatMessageType type, Message onHover, ClickEvent onClick, Message message) { default void send(boolean prefixed, Message onHover, ClickEvent onClick, Message message) {
BaseComponent msg = parse(prefixed, message); Component msg = parse(prefixed, message);
if(onHover != null) if(onHover != null)
msg.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(parse(false, onHover)))); msg = msg.hoverEvent(HoverEvent.showText(parse(false, onHover)));
if(onClick != null) if(onClick != null)
msg.setClickEvent(onClick); msg = msg.clickEvent(onClick);
sendMessage(type, msg); sendMessage(msg);
} }
default String parseToPlain(String format, Object... params) { default String parseToPlain(String format, Object... params) {
@ -134,7 +129,7 @@ public interface Chatter {
} }
default String parseToPlain(Message message) { default String parseToPlain(Message message) {
return parse(message).toPlainText(); return PlainTextComponentSerializer.plainText().serialize(parse(message));
} }
default String parseToLegacy(String format, Object... params) { default String parseToLegacy(String format, Object... params) {
@ -142,22 +137,22 @@ public interface Chatter {
} }
default String parseToLegacy(Message message) { default String parseToLegacy(Message message) {
return parse(message).toLegacyText(); return LegacyComponentSerializer.legacySection().serialize(parse(message));
} }
default BaseComponent parse(String format, Object... params) { default Component parse(String format, Object... params) {
return parse(false, new Message(format, params)); return parse(false, new Message(format, params));
} }
default BaseComponent parse(Message message) { default Component parse(Message message) {
return parse(false, message); return parse(false, message);
} }
default BaseComponent parse(boolean prefixed, String format, Object... params) { default Component parse(boolean prefixed, String format, Object... params) {
return parse(prefixed, new Message(format, params)); return parse(prefixed, new Message(format, params));
} }
default BaseComponent parse(boolean prefixed, Message message) { default Component parse(boolean prefixed, Message message) {
Locale locale = getLocale(); Locale locale = getLocale();
ResourceBundle resourceBundle = SteamwarResourceBundle.getResourceBundle(locale); ResourceBundle resourceBundle = SteamwarResourceBundle.getResourceBundle(locale);
String pattern = ""; String pattern = "";
@ -174,28 +169,28 @@ public interface Chatter {
params[i] = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale).format((Date) params[i]); params[i] = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale).format((Date) params[i]);
} else if(params[i] instanceof SteamwarUser) { } else if(params[i] instanceof SteamwarUser) {
params[i] = ((SteamwarUser) params[i]).getUserName(); params[i] = ((SteamwarUser) params[i]).getUserName();
} else if(params[i] instanceof ProxiedPlayer) { } else if(params[i] instanceof Player) {
params[i] = ((ProxiedPlayer) params[i]).getName(); params[i] = ((Player) params[i]).getUsername();
} else if(params[i] instanceof Chatter) { } else if(params[i] instanceof Chatter) {
params[i] = ((Chatter) params[i]).user().getUserName(); params[i] = ((Chatter) params[i]).user().getUserName();
} else if(params[i] instanceof Function) { } else if(params[i] instanceof Function) {
params[i] = ((Function) params[i]).apply(this); params[i] = ((Function) params[i]).apply(this);
} }
} }
return TextComponent.fromLegacy(format.format(params)); return LegacyComponentSerializer.legacySection().deserialize(format.format(params));
} }
static PlayerChatter of(ProxiedPlayer player) { static PlayerChatter of(Player player) {
return new PlayerChatter(player, player::sendMessage); return new PlayerChatter(player, player::sendMessage);
} }
static PlayerChatter disconnect(ProxiedPlayer player) { static PlayerChatter disconnect(Player player) {
return new PlayerChatter(player, (type, msg) -> player.disconnect(msg)); return new PlayerChatter(player, player::disconnect);
} }
static Chatter of(CommandSender sender) { static Chatter of(CommandSource sender) {
if(sender instanceof ProxiedPlayer) if(sender instanceof Player player)
return of((ProxiedPlayer) sender); return of(player);
//Console //Console
return new PlayerlessChatter() { return new PlayerlessChatter() {
@ -210,7 +205,7 @@ public interface Chatter {
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
sender.sendMessage(msg); sender.sendMessage(msg);
} }
}; };
@ -221,7 +216,7 @@ public interface Chatter {
} }
static Chatter of(UUID uuid) { static Chatter of(UUID uuid) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid); Player player = VelocityCore.getProxy().getPlayer(uuid).orElse(null);
if(player != null) if(player != null)
return Chatter.of(player); return Chatter.of(player);
@ -237,21 +232,21 @@ public interface Chatter {
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
// Nowhere to send // Nowhere to send
} }
}; };
} }
static Chatter console() { static Chatter console() {
return of(ConsoleCommandSender.getInstance()); return of(VelocityCore.getProxy().getConsoleCommandSource());
} }
static Chatter of(LoginEvent event) { static Chatter of(LoginEvent event) {
return new PlayerlessChatter() { return new PlayerlessChatter() {
@Override @Override
public SteamwarUser user() { public SteamwarUser user() {
return SteamwarUser.get(event.getConnection().getUniqueId()); return SteamwarUser.get(event.getPlayer().getUniqueId());
} }
@Override @Override
@ -260,9 +255,8 @@ public interface Chatter {
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
event.setReason(msg); event.setResult(ResultedEvent.ComponentResult.denied(msg));
event.setCancelled(true);
} }
}; };
} }
@ -274,8 +268,8 @@ public interface Chatter {
} }
@Override @Override
public ProxiedPlayer getPlayer() { public Player getPlayer() {
return ProxyServer.getInstance().getPlayer(user().getUUID()); return VelocityCore.getProxy().getPlayer(user().getUUID()).orElse(null);
} }
} }
} }

Datei anzeigen

@ -21,9 +21,8 @@ package de.steamwar.messages;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import lombok.Getter; import lombok.Getter;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.chat.BaseComponent; import net.kyori.adventure.text.event.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent;
import java.util.Arrays; import java.util.Arrays;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -47,9 +46,9 @@ public class ChatterGroup extends Chatter.PlayerlessChatter {
} }
@Override @Override
public void send(boolean prefixed, ChatMessageType type, Message onHover, ClickEvent onClick, Message message) { public void send(boolean prefixed, Message onHover, ClickEvent onClick, Message message) {
for(Chatter sender : chatters) for(Chatter sender : chatters)
sender.send(prefixed, type, onHover, onClick, message); sender.send(prefixed, onHover, onClick, message);
} }
@Override @Override
@ -58,7 +57,7 @@ public class ChatterGroup extends Chatter.PlayerlessChatter {
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

Datei anzeigen

@ -19,20 +19,20 @@
package de.steamwar.messages; package de.steamwar.messages;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.player.PlayerSettings;
import de.steamwar.sql.SteamwarUser; import de.steamwar.sql.SteamwarUser;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import net.md_5.bungee.api.ChatMessageType; import net.kyori.adventure.text.Component;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Locale; import java.util.Locale;
import java.util.function.BiConsumer; import java.util.function.Consumer;
@AllArgsConstructor @AllArgsConstructor
public class PlayerChatter implements Chatter { public class PlayerChatter implements Chatter {
private final ProxiedPlayer player; private final Player player;
private final BiConsumer<ChatMessageType, BaseComponent> sendMessage; private final Consumer<Component> sendMessage;
@Override @Override
public SteamwarUser user() { public SteamwarUser user() {
@ -46,16 +46,19 @@ public class PlayerChatter implements Chatter {
@Override @Override
public boolean chatShown() { public boolean chatShown() {
return player.getChatMode() == ProxiedPlayer.ChatMode.SHOWN; if(!player.hasSentPlayerSettings())
return false;
return player.getPlayerSettings().getChatMode() == PlayerSettings.ChatMode.SHOWN;
} }
@Override @Override
public void sendMessage(ChatMessageType type, BaseComponent msg) { public void sendMessage(Component msg) {
sendMessage.accept(type, msg); sendMessage.accept(msg);
} }
@Override @Override
public ProxiedPlayer getPlayer() { public Player getPlayer() {
return player; return player;
} }
} }

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.sql; package de.steamwar.sql;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.sql.internal.SQLConfig; import de.steamwar.sql.internal.SQLConfig;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -27,7 +27,7 @@ import java.util.logging.Logger;
public class SQLConfigImpl implements SQLConfig { public class SQLConfigImpl implements SQLConfig {
@Override @Override
public Logger getLogger() { public Logger getLogger() {
return BungeeCore.get().getLogger(); return VelocityCore.getLogger();
} }
@Override @Override

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.sql; package de.steamwar.sql;
import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.VelocityCore;
import de.steamwar.bungeecore.commands.CheckCommand; import de.steamwar.bungeecore.commands.CheckCommand;
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;
@ -54,7 +54,7 @@ public class SQLWrapperImpl implements SQLWrapper {
@Override @Override
public void loadSchemTypes(List<SchematicType> tmpTypes, Map<String, SchematicType> tmpFromDB) { public void loadSchemTypes(List<SchematicType> tmpTypes, Map<String, SchematicType> tmpFromDB) {
File folder = new File(BungeeCore.get().getDataFolder().getParentFile(), "FightSystem"); File folder = new File(VelocityCore.get().getDataFolder().getParentFile(), "FightSystem");
if(folder.exists()) { if(folder.exists()) {
for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) { for(File configFile : Arrays.stream(folder.listFiles((file, name) -> name.endsWith(".yml") && !name.endsWith(".kits.yml"))).sorted().collect(Collectors.toList())) {
Configuration config; Configuration config;

Datei anzeigen

@ -1,6 +0,0 @@
name: BungeeCore
main: de.steamwar.bungeecore.BungeeCore
version: 1.0
author: Lixfel
depends:
- PersistentBungeeCore