feat: Implement Plugin Configuration

This commit is contained in:
Adrian3d04 2022-08-05 22:27:09 +00:00
parent 23faeb5ab4
commit 9453b8a925
19 changed files with 349 additions and 248 deletions

View File

@ -1,3 +1,11 @@
dependencies { dependencies {
compileOnly("io.papermc.paper:paper-api:1.19.1-R0.1-SNAPSHOT") compileOnly("io.papermc.paper:paper-api:1.19.1-R0.1-SNAPSHOT")
} }
tasks {
compileJava {
options.release.set(17)
}
}
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))

10
common/build.gradle.kts Normal file
View File

@ -0,0 +1,10 @@
repositories {
maven("https://repo.alessiodp.com/releases/")
}
dependencies {
compileOnly("space.arim.dazzleconf:dazzleconf-core:1.3.0-M1")
compileOnly("space.arim.dazzleconf:dazzleconf-ext-snakeyaml:1.3.0-M1")
compileOnly("org.slf4j:slf4j-api:1.7.36")
compileOnly("net.byteflux:libby-core:1.1.5")
}

View File

@ -0,0 +1,7 @@
package me.adrianed.authmevelocity.common;
//TODO: Abstract Class
public interface LibsManager {
void registerRepositories();
void loadLibraries();
}

View File

@ -1,5 +1,65 @@
package me.adrianed.authmevelocity.common.configuration; package me.adrianed.authmevelocity.common.configuration;
public class Loader { import org.slf4j.Logger;
import space.arim.dazzleconf.ConfigurationFactory;
import space.arim.dazzleconf.ConfigurationOptions;
import space.arim.dazzleconf.error.ConfigFormatSyntaxException;
import space.arim.dazzleconf.error.InvalidConfigException;
import space.arim.dazzleconf.ext.snakeyaml.CommentMode;
import space.arim.dazzleconf.ext.snakeyaml.SnakeYamlConfigurationFactory;
import space.arim.dazzleconf.ext.snakeyaml.SnakeYamlOptions;
import space.arim.dazzleconf.helper.ConfigurationHelper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
public class Loader<C> {
private final ConfigurationHelper<C> configHelper;
private volatile C configData;
private final Logger logger;
private Loader(ConfigurationHelper<C> configHelper, Logger logger) {
this.configHelper = configHelper;
this.logger = logger;
}
public static <C> Loader<C> create(Path configFolder, String fileName, Class<C> configClass, Logger logger) {
SnakeYamlOptions yamlOptions = new SnakeYamlOptions.Builder()
.commentMode(CommentMode.alternativeWriter())
.build();
ConfigurationFactory<C> configFactory = SnakeYamlConfigurationFactory.create(
configClass,
ConfigurationOptions.defaults(),
yamlOptions);
return new Loader<>(new ConfigurationHelper<>(configFolder, fileName, configFactory), logger);
}
public boolean reloadConfig() {
try {
configData = configHelper.reloadConfigData();
return true;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
} catch (ConfigFormatSyntaxException ex) {
configData = configHelper.getFactory().loadDefaults();
logger.error("The yaml syntax in your configuration is invalid. "
+ "Check your YAML syntax with a tool such as https://yaml-online-parser.appspot.com/", ex);
return false;
} catch (InvalidConfigException ex) {
configData = configHelper.getFactory().loadDefaults();
logger.error("One of the values in your configuration is not valid. "
+ "Check to make sure you have specified the right data types.", ex);
return false;
}
}
public C getConfig() {
C configData = this.configData;
if (configData == null) {
throw new IllegalStateException("Configuration has not been loaded yet");
}
return configData;
}
} }

View File

@ -1,5 +1,5 @@
package me.adrianed.authmevelocity.common.configuration; package me.adrianed.authmevelocity.common.configuration;
public class PaperConfiguration { public interface PaperConfiguration {
boolean debug();
} }

View File

@ -1,5 +1,66 @@
package me.adrianed.authmevelocity.common.configuration; package me.adrianed.authmevelocity.common.configuration;
public class ProxyConfiguration { import java.util.List;
import space.arim.dazzleconf.annote.ConfDefault;
import space.arim.dazzleconf.annote.ConfComments;
public interface ProxyConfiguration {
@ConfDefault.DefaultStrings({
"auth1", "auth2"
})
@ConfComments({
"List of login/registration servers"
})
List<String> authServers();
@ConfDefault.DefaultObject("defaultSendOnLogin")
SendOnLogin sendOnLogin();
@ConfDefault.DefaultObject("defaultCommands")
Commands commands();
@ConfDefault.DefaultObject("defaultEnsureAuth")
EnsureAuthServer ensureAuthServer();
public interface SendOnLogin {
@ConfComments({
"Send logged in players to another server?"
})
@ConfDefault.DefaultBoolean(false)
boolean sendToServerOnLogin();
@ConfComments({
"List of servers to send",
"One of these servers will be chosen at random"
})
@ConfDefault.DefaultStrings({
"lobby1", "lobby2"
})
List<String> teleportServers();
}
public interface Commands {
@ConfComments({
"Sets the commands that users who have not yet logged in can execute"
})
@ConfDefault.DefaultStrings({
"login", "register", "l", "reg", "email", "captcha"
})
List<String> allowedCommands();
@ConfComments({
"Sets the message to send in case a non-logged-in player executes an unauthorized command",
"To deactivate the message, leave it empty"
})
@ConfDefault.DefaultString("<red>You cannot execute commands if you are not logged in yet")
String blockedCommandMessage();
}
public interface EnsureAuthServer {
@ConfComments({
"Ensure that the first server to which players connect is an auth server"
})
@ConfDefault.DefaultBoolean(false)
boolean ensureFirstServerIsAuthServer();
}
} }

View File

@ -1,4 +1,5 @@
module me.adrianed.authmevelocity.common { module me.adrianed.authmevelocity.common {
requires transitive space.arim.dazzleconf.ext.snakeyaml;
exports me.adrianed.authmevelocity.common; exports me.adrianed.authmevelocity.common;
exports me.adrianed.authmevelocity.common.configuration; exports me.adrianed.authmevelocity.common.configuration;
} }

View File

@ -30,6 +30,7 @@ bukkit {
depend = listOf("AuthMe") depend = listOf("AuthMe")
version = "4.0.0" version = "4.0.0"
} }
tasks { tasks {
shadowJar { shadowJar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE duplicatesStrategy = DuplicatesStrategy.EXCLUDE

View File

@ -0,0 +1,51 @@
package me.adrianed.authmevelocity.paper;
import me.adrianed.authmevelocity.common.LibsManager;
import net.byteflux.libby.BukkitLibraryManager;
import net.byteflux.libby.Library;
import net.byteflux.libby.relocation.Relocation;
public class PaperLibraries implements LibsManager {
private final BukkitLibraryManager manager;
public PaperLibraries(AuthMeVelocityPlugin plugin) {
this.manager = new BukkitLibraryManager(plugin);
}
@Override
public void registerRepositories() {
manager.addMavenCentral();
}
@Override
public void loadLibraries() {
final Relocation dazzleRelocation
= new Relocation("space.arim.dazzleconf", "me.adrianed.authmevelocity.libs.dazzleconf");
final Relocation snakeYamlRelocation
= new Relocation("pattern", "me.adrianed.authmevelocity.libs.snake");
final Library dazzleConf = Library.builder()
.groupId("space.arim.dazzleconf")
.artifactId("dazzleconf-ext-snakeyaml")
.version("1.3.0-M1")
.relocate(dazzleRelocation)
.build();
final Library dazzleYaml = Library.builder()
.groupId("space.arim.dazzleconf")
.artifactId("dazzleconf-ext-snakeyaml")
.version("1.3.0-M1")
.relocate(dazzleRelocation)
.relocate(snakeYamlRelocation)
.build();
final Library snakeYaml = Library.builder()
.groupId("org.yaml")
.artifactId("snakeyaml")
.version("1.30")
.relocate(dazzleRelocation)
.relocate(snakeYamlRelocation)
.build();
manager.loadLibrary(snakeYaml);
manager.loadLibrary(dazzleConf);
manager.loadLibrary(dazzleYaml);
}
}

View File

@ -18,10 +18,16 @@ dependencies {
compileOnly(project(":authmevelocity-api-velocity")) compileOnly(project(":authmevelocity-api-velocity"))
} }
tasks.compileJava { tasks {
compileJava {
options.encoding = Charsets.UTF_8.name() options.encoding = Charsets.UTF_8.name()
options.release.set(17) options.release.set(17)
}
build {
dependsOn(shadowJar)
}
} }
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17)) java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))

View File

@ -1,12 +1,13 @@
package me.adrianed.authmevelocity.velocity; package me.adrianed.authmevelocity.velocity;
import me.adrianed.authmevelocity.velocity.commands.AuthmeCommand; import me.adrianed.authmevelocity.velocity.commands.AuthmeCommand;
import me.adrianed.authmevelocity.velocity.config.AuthMeConfig;
import me.adrianed.authmevelocity.velocity.listener.ConnectListener; import me.adrianed.authmevelocity.velocity.listener.ConnectListener;
import me.adrianed.authmevelocity.velocity.listener.FastLoginListener; import me.adrianed.authmevelocity.velocity.listener.FastLoginListener;
import me.adrianed.authmevelocity.velocity.listener.PluginMessageListener; import me.adrianed.authmevelocity.velocity.listener.PluginMessageListener;
import me.adrianed.authmevelocity.velocity.listener.ProxyListener; import me.adrianed.authmevelocity.velocity.listener.ProxyListener;
import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI; import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI;
import me.adrianed.authmevelocity.common.configuration.Loader;
import me.adrianed.authmevelocity.common.configuration.ProxyConfiguration;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.moandjiezana.toml.Toml; import com.moandjiezana.toml.Toml;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
@ -33,7 +34,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.concurrent.ConcurrentHashMap;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@ -61,10 +62,10 @@ public final class AuthMeVelocityPlugin implements AuthMeVelocityAPI {
private final ProxyServer proxy; private final ProxyServer proxy;
private final Logger logger; private final Logger logger;
private final Path pluginDirectory; private final Path pluginDirectory;
private AuthMeConfig config; private Loader<ProxyConfiguration> config;
private final List<Object> listeners = new ArrayList<>(3); private final List<Object> listeners = new ArrayList<>(3);
protected final Set<UUID> loggedPlayers = Collections.synchronizedSet(new HashSet<>()); protected final Set<UUID> loggedPlayers = ConcurrentHashMap.newKeySet();
@Inject @Inject
public AuthMeVelocityPlugin(ProxyServer proxy, Logger logger, @DataDirectory Path dataDirectory) { public AuthMeVelocityPlugin(ProxyServer proxy, Logger logger, @DataDirectory Path dataDirectory) {
@ -75,13 +76,26 @@ public final class AuthMeVelocityPlugin implements AuthMeVelocityAPI {
@Subscribe @Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) { public void onProxyInitialization(ProxyInitializeEvent event) {
if (!this.reload()) { final VelocityLibraries libraries
logger.warn("Failed to load config.toml. Shutting down."); = new VelocityLibraries(logger, pluginDirectory, proxy.getPluginManager(), this);
return; libraries.registerRepositories();
} libraries.loadLibraries();
this.config = Loader.create(pluginDirectory, "config.yml", ProxyConfiguration.class, logger);
proxy.getChannelRegistrar().register(AUTHMEVELOCITY_CHANNEL); proxy.getChannelRegistrar().register(AUTHMEVELOCITY_CHANNEL);
List.of(
new ProxyListener(this),
new ConnectListener(this, proxy, logger),
new PluginMessageListener(proxy, logger, this)
).forEach(listener ->
proxy.getEventManager().register(this, listener));
if (proxy.getPluginManager().isLoaded("fastlogin")) {
proxy.getEventManager().register(this, new FastLoginListener(proxy, this));
}
if (proxy.getPluginManager().isLoaded("miniplaceholders")) { if (proxy.getPluginManager().isLoaded("miniplaceholders")) {
AuthMePlaceholders.getExpansion(this).register(); AuthMePlaceholders.getExpansion(this).register();
} }
@ -95,64 +109,22 @@ public final class AuthMeVelocityPlugin implements AuthMeVelocityAPI {
return this.proxy; return this.proxy;
} }
private Toml loadConfig(Path path){
try {
if (Files.notExists(path)) {
Files.createDirectory(path);
}
Path configPath = path.resolve("config.toml");
if (Files.notExists(configPath)) {
try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.toml")) {
Files.copy(Objects.requireNonNull(in, "The configuration does not exists"), configPath);
}
}
return new Toml().read(Files.newInputStream(configPath));
} catch (IOException ex) {
logger.error("An error ocurred on configuration initialization", ex);
return null;
} catch(IllegalStateException ex) {
logger.error("Invalid configuration provided", ex);
return null;
}
}
public boolean reload() {
Toml toml = this.loadConfig(pluginDirectory);
if (toml == null) {
return false;
}
this.config = new AuthMeConfig(toml);
listeners.forEach(listener -> proxy.getEventManager().unregisterListener(this, listener));
listeners.clear();
listeners.add(new ProxyListener(config, this));
listeners.add(new ConnectListener(config, this, proxy, logger));
listeners.add(new PluginMessageListener(proxy, logger, config, this));
if (proxy.getPluginManager().isLoaded("fastlogin")) {
listeners.add(new FastLoginListener(proxy, this));
}
listeners.forEach(listener -> proxy.getEventManager().register(this, listener));
return true;
}
public void sendInfoMessage() { public void sendInfoMessage() {
CommandSource source = proxy.getConsoleCommandSource(); CommandSource source = proxy.getConsoleCommandSource();
source.sendMessage(MiniMessage.miniMessage().deserialize( source.sendMessage(MiniMessage.miniMessage().deserialize(
" <gray>--- <aqua>AuthMeVelocity</aqua> ---")); " <gray>--- <aqua>AuthMeVelocity</aqua> ---"));
source.sendMessage(MiniMessage.miniMessage().deserialize( source.sendMessage(MiniMessage.miniMessage().deserialize(
"<gray>AuthServers: <green>" + config.getAuthServers())); "<gray>AuthServers: <green>" + config.getConfig().authServers()));
if (config.getToServerOptions().sendToServer()) { if (config.getConfig().sendOnLogin().sendToServerOnLogin()) {
source.sendMessage(MiniMessage.miniMessage().deserialize( source.sendMessage(MiniMessage.miniMessage().deserialize(
"<gray>LobbyServers: <green>" + config.getToServerOptions().getTeleportServers())); "<gray>LobbyServers: <green>" + config.getConfig().sendOnLogin().teleportServers()));
} }
} }
public Loader<ProxyConfiguration> config() {
return this.config;
}
@Override @Override
public boolean isLogged(Player player){ public boolean isLogged(Player player){
return loggedPlayers.contains(player.getUniqueId()); return loggedPlayers.contains(player.getUniqueId());
@ -185,16 +157,16 @@ public final class AuthMeVelocityPlugin implements AuthMeVelocityAPI {
@Override @Override
public boolean isAuthServer(RegisteredServer server){ public boolean isAuthServer(RegisteredServer server){
return config.getAuthServers().contains(server.getServerInfo().getName()); return config.getConfig().authServers().contains(server.getServerInfo().getName());
} }
@Override @Override
public boolean isAuthServer(ServerConnection connection){ public boolean isAuthServer(ServerConnection connection){
return config.getAuthServers().contains(connection.getServerInfo().getName()); return config.getConfig().authServers().contains(connection.getServerInfo().getName());
} }
@Override @Override
public boolean isAuthServer(String server){ public boolean isAuthServer(String server){
return config.getAuthServers().contains(server); return config.getConfig().authServers().contains(server);
} }
} }

View File

@ -0,0 +1,57 @@
package me.adrianed.authmevelocity.velocity;
import java.nio.file.Path;
import org.slf4j.Logger;
import com.velocitypowered.api.plugin.PluginManager;
import me.adrianed.authmevelocity.common.LibsManager;
import net.byteflux.libby.Library;
import net.byteflux.libby.VelocityLibraryManager;
import net.byteflux.libby.relocation.Relocation;
public class VelocityLibraries implements LibsManager {
private final VelocityLibraryManager<AuthMeVelocityPlugin> manager;
public VelocityLibraries(Logger logger, Path dataDirectory, PluginManager pluginManager, AuthMeVelocityPlugin plugin) {
this.manager = new VelocityLibraryManager<AuthMeVelocityPlugin>(
logger, dataDirectory, pluginManager, plugin);
}
@Override
public void registerRepositories() {
manager.addMavenCentral();
}
@Override
public void loadLibraries() {
final Relocation dazzleRelocation
= new Relocation("space.arim.dazzleconf", "me.adrianed.authmevelocity.libs.dazzleconf");
final Relocation snakeYamlRelocation
= new Relocation("pattern", "me.adrianed.authmevelocity.libs.snake");
final Library dazzleConf = Library.builder()
.groupId("space.arim.dazzleconf")
.artifactId("dazzleconf-ext-snakeyaml")
.version("1.3.0-M1")
.relocate(dazzleRelocation)
.build();
final Library dazzleYaml = Library.builder()
.groupId("space.arim.dazzleconf")
.artifactId("dazzleconf-ext-snakeyaml")
.version("1.3.0-M1")
.relocate(dazzleRelocation)
.relocate(snakeYamlRelocation)
.build();
final Library snakeYaml = Library.builder()
.groupId("org.yaml")
.artifactId("snakeyaml")
.version("1.30")
.relocate(dazzleRelocation)
.relocate(snakeYamlRelocation)
.build();
manager.loadLibrary(snakeYaml);
manager.loadLibrary(dazzleConf);
manager.loadLibrary(dazzleYaml);
}
}

View File

@ -20,7 +20,7 @@ public class AuthmeCommand {
.then(LiteralArgumentBuilder.<CommandSource>literal("reload") .then(LiteralArgumentBuilder.<CommandSource>literal("reload")
.executes(cmd -> { .executes(cmd -> {
CommandSource source = cmd.getSource(); CommandSource source = cmd.getSource();
if (plugin.reload()) { if (plugin.config().reloadConfig()) {
plugin.sendInfoMessage(); plugin.sendInfoMessage();
source.sendMessage(MiniMessage.miniMessage().deserialize( source.sendMessage(MiniMessage.miniMessage().deserialize(
"<aqua>AuthmeVelocity <green>has been successfully reloaded")); "<aqua>AuthmeVelocity <green>has been successfully reloaded"));

View File

@ -1,91 +0,0 @@
package me.adrianed.authmevelocity.velocity.config;
import java.util.List;
import java.util.Set;
import com.moandjiezana.toml.Toml;
import org.jetbrains.annotations.NotNull;
public final class AuthMeConfig {
private final List<String> authServers;
private final ServerOnLogin serverOnLogin;
private final Commands commands;
private final EnsureAuthServer ensure;
public AuthMeConfig(@NotNull Toml toml){
this.authServers = ConfigUtils.listOrElse(toml, "authServers",
() -> List.of("auth1", "auth2"));
this.serverOnLogin = ConfigUtils.getObjectOrElse(toml, "SendOnLogin", ServerOnLogin.class,
() -> new ServerOnLogin(false, List.of("lobby1", "lobby2")));
this.commands = ConfigUtils.getObjectOrElse(toml, "Commands", Commands.class,
() -> new Commands(Set.of("login", "register", "l", "reg", "email", "captcha"), "<red>You cannot execute commands if you are not logged in yet"));
this.ensure = ConfigUtils.getObjectOrElse(toml, "EnsureAuthServer", EnsureAuthServer.class,
() -> new EnsureAuthServer(false));
}
public static class ServerOnLogin {
private final boolean sendToServerOnLogin;
private final List<String> teleportServers;
public ServerOnLogin(boolean sendToServerOnLogin, List<String> teleportServers){
this.sendToServerOnLogin = sendToServerOnLogin;
this.teleportServers = teleportServers;
}
public boolean sendToServer(){
return this.sendToServerOnLogin;
}
public @NotNull List<String> getTeleportServers(){
return this.teleportServers;
}
}
public static class Commands {
private final Set<String> allowedCommands;
private final String blockedCommandMessage;
public Commands(Set<String> allowedCommands, String blockedCommandMessage){
this.allowedCommands = allowedCommands;
this.blockedCommandMessage = blockedCommandMessage;
}
public @NotNull Set<String> getAllowedCommands(){
return this.allowedCommands;
}
public @NotNull String getBlockedMessage() {
return this.blockedCommandMessage;
}
}
public static class EnsureAuthServer {
private final boolean ensureFirstServerIsAuthServer;
public EnsureAuthServer(boolean ensureFirstServerIsAuthServer){
this.ensureFirstServerIsAuthServer = ensureFirstServerIsAuthServer;
}
public boolean ensureAuthServer(){
return this.ensureFirstServerIsAuthServer;
}
}
public @NotNull Commands getCommandsConfig(){
return this.commands;
}
public @NotNull ServerOnLogin getToServerOptions(){
return this.serverOnLogin;
}
public @NotNull EnsureAuthServer getEnsureOptions(){
return this.ensure;
}
public @NotNull List<String> getAuthServers(){
return this.authServers;
}
}

View File

@ -1,40 +0,0 @@
package me.adrianed.authmevelocity.velocity.config;
import java.util.List;
import java.util.function.Supplier;
import java.lang.reflect.ParameterizedType;
import com.moandjiezana.toml.Toml;
import com.velocitypowered.api.proxy.Player;
import net.kyori.adventure.text.minimessage.MiniMessage;
public final class ConfigUtils {
public static final MiniMessage MINIMESSAGE = MiniMessage.miniMessage();
public static void sendBlockedMessage(Player player, AuthMeConfig config){
String blockedMessage = config.getCommandsConfig().getBlockedMessage();
if(!blockedMessage.isBlank()){
player.sendMessage(MINIMESSAGE.deserialize(blockedMessage));
}
}
@SuppressWarnings("unchecked")
static <T>T getObjectOrElse(Toml config, String key, Supplier<T> defaultValue){
Toml configTable = config.getTable(key);
return configTable == null ? defaultValue.get() : (T)configTable.to((Class<T>)((ParameterizedType)defaultValue.getClass()
.getGenericInterfaces()[0]).getActualTypeArguments()[0]);
}
static <T>T getObjectOrElse(Toml config, String key, Class<T> clazz, Supplier<T> defaultValue){
Toml configTable = config.getTable(key);
return configTable == null ? defaultValue.get() : configTable.to(clazz);
}
static List<String> listOrElse(Toml config, String key, Supplier<List<String>> defaultList){
List<String> list = config.getList(key);
return list != null ? list : defaultList.get();
}
private ConfigUtils(){}
}

View File

@ -5,7 +5,6 @@ import java.util.Optional;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
import me.adrianed.authmevelocity.velocity.config.AuthMeConfig;
import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.Continuation; import com.velocitypowered.api.event.Continuation;
@ -24,25 +23,23 @@ import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI;
public class ConnectListener { public class ConnectListener {
private final ProxyServer proxy; private final ProxyServer proxy;
private final Logger logger; private final Logger logger;
private final AuthMeConfig config; private final AuthMeVelocityPlugin plugin;
private final AuthMeVelocityAPI api;
public ConnectListener(AuthMeConfig config, AuthMeVelocityAPI api, ProxyServer proxy, Logger logger) { public ConnectListener(AuthMeVelocityPlugin plugin, ProxyServer proxy, Logger logger) {
this.config = config; this.plugin = plugin;
this.api = api;
this.logger = logger; this.logger = logger;
this.proxy = proxy; this.proxy = proxy;
} }
@Subscribe(order = PostOrder.LATE) @Subscribe(order = PostOrder.LATE)
public void onInitialServer(PlayerChooseInitialServerEvent event, Continuation continuation){ public void onInitialServer(PlayerChooseInitialServerEvent event, Continuation continuation){
if(!config.getEnsureOptions().ensureAuthServer()) { if(!plugin.config().getConfig().ensureAuthServer().ensureFirstServerIsAuthServer()) {
continuation.resume(); continuation.resume();
return; return;
} }
Optional<RegisteredServer> optionalSV = event.getInitialServer(); Optional<RegisteredServer> optionalSV = event.getInitialServer();
if(optionalSV.isPresent() && api.isAuthServer(optionalSV.get())){ if(optionalSV.isPresent() && plugin.isAuthServer(optionalSV.get())){
continuation.resume(); continuation.resume();
return; return;
} }
@ -58,13 +55,13 @@ public class ConnectListener {
@Subscribe @Subscribe
public void onServerPreConnect(ServerPreConnectEvent event, Continuation continuation) { public void onServerPreConnect(ServerPreConnectEvent event, Continuation continuation) {
if (!event.getResult().isAllowed() && api.isLogged(event.getPlayer())) { if (!event.getResult().isAllowed() && plugin.isLogged(event.getPlayer())) {
continuation.resume(); continuation.resume();
return; return;
} }
// this should be present, "event.getResult().isAllowed()" is the "isPresent" check // this should be present, "event.getResult().isAllowed()" is the "isPresent" check
if(!api.isAuthServer(event.getResult().getServer().get())) { if(!plugin.isAuthServer(event.getResult().getServer().get())) {
event.setResult(ServerPreConnectEvent.ServerResult.denied()); event.setResult(ServerPreConnectEvent.ServerResult.denied());
} }
continuation.resume(); continuation.resume();
@ -73,7 +70,7 @@ public class ConnectListener {
@Subscribe @Subscribe
public void onServerPostConnect(ServerPostConnectEvent event) { public void onServerPostConnect(ServerPostConnectEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (api.isLogged(player) && api.isInAuthServer(player)) { if (plugin.isLogged(player) && plugin.isInAuthServer(player)) {
ByteArrayDataOutput buf = ByteStreams.newDataOutput(); ByteArrayDataOutput buf = ByteStreams.newDataOutput();
buf.writeUTF("LOGIN"); buf.writeUTF("LOGIN");
player.getCurrentServer().ifPresent(sv -> player.getCurrentServer().ifPresent(sv ->
@ -83,7 +80,7 @@ public class ConnectListener {
// TODO: Implement #40 // TODO: Implement #40
private @Nullable RegisteredServer getAvailableServer() { private @Nullable RegisteredServer getAvailableServer() {
for(String sv : config.getAuthServers()){ for(String sv : plugin.config().getConfig().authServers()){
Optional<RegisteredServer> opt = proxy.getServer(sv); Optional<RegisteredServer> opt = proxy.getServer(sv);
if (opt.isPresent()) return opt.get(); if (opt.isPresent()) return opt.get();
} }

View File

@ -7,14 +7,15 @@ import com.velocitypowered.api.proxy.ProxyServer;
import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI; import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI;
public class FastLoginListener { public class FastLoginListener {
private final ProxyServer server; private final ProxyServer proxy;
private final AuthMeVelocityAPI api; private final AuthMeVelocityAPI api;
public FastLoginListener(ProxyServer server, AuthMeVelocityAPI api){ public FastLoginListener(ProxyServer proxy, AuthMeVelocityAPI api){
this.server = server; this.proxy = proxy;
this.api = api; this.api = api;
} }
@Subscribe @Subscribe
public void onAutoLogin(VelocityFastLoginAutoLoginEvent event){ public void onAutoLogin(VelocityFastLoginAutoLoginEvent event){
server.getPlayer(event.getProfile().getName()).ifPresent(api::addPlayer); proxy.getPlayer(event.getProfile().getName())
.ifPresent(api::addPlayer);
} }
} }

View File

@ -3,7 +3,6 @@ package me.adrianed.authmevelocity.velocity.listener;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import me.adrianed.authmevelocity.velocity.config.AuthMeConfig;
import me.adrianed.authmevelocity.api.velocity.event.PreSendOnLoginEvent; import me.adrianed.authmevelocity.api.velocity.event.PreSendOnLoginEvent;
import me.adrianed.authmevelocity.api.velocity.event.ProxyForcedUnregisterEvent; import me.adrianed.authmevelocity.api.velocity.event.ProxyForcedUnregisterEvent;
import me.adrianed.authmevelocity.api.velocity.event.ProxyLoginEvent; import me.adrianed.authmevelocity.api.velocity.event.ProxyLoginEvent;
@ -22,7 +21,6 @@ import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import me.adrianed.authmevelocity.velocity.AuthMeVelocityPlugin; import me.adrianed.authmevelocity.velocity.AuthMeVelocityPlugin;
import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -32,15 +30,13 @@ public class PluginMessageListener {
private final ProxyServer proxy; private final ProxyServer proxy;
private final Logger logger; private final Logger logger;
private final Random rm; private final Random rm;
private final AuthMeConfig config; private final AuthMeVelocityPlugin plugin;
private final AuthMeVelocityAPI api;
public PluginMessageListener(@NotNull ProxyServer proxy, @NotNull Logger logger, @NotNull AuthMeConfig config, AuthMeVelocityAPI api) { public PluginMessageListener(@NotNull ProxyServer proxy, @NotNull Logger logger, AuthMeVelocityPlugin plugin) {
this.proxy = proxy; this.proxy = proxy;
this.logger = logger; this.logger = logger;
this.rm = new Random(); this.rm = new Random();
this.config = config; this.plugin = plugin;
this.api = api;
} }
@Subscribe @Subscribe
@ -62,13 +58,13 @@ public class PluginMessageListener {
final @Nullable Player loggedPlayer = proxy.getPlayer(playername).orElse(null); final @Nullable Player loggedPlayer = proxy.getPlayer(playername).orElse(null);
switch (sChannel) { switch (sChannel) {
case "LOGIN" : case "LOGIN" :
if (loggedPlayer != null && api.addPlayer(loggedPlayer)){ if (loggedPlayer != null && plugin.addPlayer(loggedPlayer)){
proxy.getEventManager().fireAndForget(new ProxyLoginEvent(loggedPlayer)); proxy.getEventManager().fireAndForget(new ProxyLoginEvent(loggedPlayer));
this.createServerConnectionRequest(loggedPlayer, connection); this.createServerConnectionRequest(loggedPlayer, connection);
} }
break; break;
case "LOGOUT": case "LOGOUT":
if (loggedPlayer != null && api.removePlayer(loggedPlayer)){ if (loggedPlayer != null && plugin.removePlayer(loggedPlayer)){
proxy.getEventManager().fireAndForget(new ProxyLogoutEvent(loggedPlayer)); proxy.getEventManager().fireAndForget(new ProxyLogoutEvent(loggedPlayer));
} }
break; break;
@ -89,7 +85,7 @@ public class PluginMessageListener {
} }
private void createServerConnectionRequest(Player player, ServerConnection connection){ private void createServerConnectionRequest(Player player, ServerConnection connection){
if (!config.getToServerOptions().sendToServer()) { if (!plugin.config().getConfig().sendOnLogin().sendToServerOnLogin()) {
return; return;
} }
@ -119,7 +115,7 @@ public class PluginMessageListener {
} }
private String getRandomServer() { private String getRandomServer() {
final List<String> serverList = config.getToServerOptions().getTeleportServers(); final List<String> serverList = plugin.config().getConfig().sendOnLogin().teleportServers();
return serverList.get(rm.nextInt(serverList.size())); return serverList.get(rm.nextInt(serverList.size()));
} }
} }

View File

@ -1,8 +1,7 @@
package me.adrianed.authmevelocity.velocity.listener; package me.adrianed.authmevelocity.velocity.listener;
import me.adrianed.authmevelocity.velocity.config.AuthMeConfig;
import me.adrianed.authmevelocity.velocity.config.ConfigUtils;
import me.adrianed.authmevelocity.velocity.utils.AuthmeUtils; import me.adrianed.authmevelocity.velocity.utils.AuthmeUtils;
import me.adrianed.authmevelocity.velocity.AuthMeVelocityPlugin;
import com.velocitypowered.api.event.Continuation; import com.velocitypowered.api.event.Continuation;
import com.velocitypowered.api.event.EventTask; import com.velocitypowered.api.event.EventTask;
import com.velocitypowered.api.event.PostOrder; import com.velocitypowered.api.event.PostOrder;
@ -13,22 +12,20 @@ import com.velocitypowered.api.event.player.PlayerChatEvent;
import com.velocitypowered.api.event.player.TabCompleteEvent; import com.velocitypowered.api.event.player.TabCompleteEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import me.adrianed.authmevelocity.api.velocity.AuthMeVelocityAPI;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public final class ProxyListener { import net.kyori.adventure.text.minimessage.MiniMessage;
private final AuthMeConfig config;
private final AuthMeVelocityAPI api;
public ProxyListener(@NotNull AuthMeConfig config, AuthMeVelocityAPI api) { public final class ProxyListener {
this.config = config; private final AuthMeVelocityPlugin plugin;
this.api = api;
public ProxyListener(AuthMeVelocityPlugin plugin) {
this.plugin = plugin;
} }
@Subscribe @Subscribe
public EventTask onDisconnect(final DisconnectEvent event) { public EventTask onDisconnect(final DisconnectEvent event) {
return EventTask.async(() -> api.removePlayer(event.getPlayer())); return EventTask.async(() -> plugin.removePlayer(event.getPlayer()));
} }
@Subscribe(order = PostOrder.FIRST) @Subscribe(order = PostOrder.FIRST)
@ -40,19 +37,19 @@ public final class ProxyListener {
Player player = (Player)event.getCommandSource(); Player player = (Player)event.getCommandSource();
if (api.isLogged(player)) { if (plugin.isLogged(player)) {
continuation.resume(); continuation.resume();
return; return;
} }
if (api.isInAuthServer(player)) { if (plugin.isInAuthServer(player)) {
String command = AuthmeUtils.getFirstArgument(event.getCommand()); String command = AuthmeUtils.getFirstArgument(event.getCommand());
if (!config.getCommandsConfig().getAllowedCommands().contains(command)) { if (!plugin.config().getConfig().commands().allowedCommands().contains(command)) {
ConfigUtils.sendBlockedMessage(player, config); sendBlockedMessage(player);
event.setResult(CommandExecuteEvent.CommandResult.denied()); event.setResult(CommandExecuteEvent.CommandResult.denied());
} }
} else { } else {
ConfigUtils.sendBlockedMessage(player, config); sendBlockedMessage(player);
event.setResult(CommandExecuteEvent.CommandResult.denied()); event.setResult(CommandExecuteEvent.CommandResult.denied());
} }
continuation.resume(); continuation.resume();
@ -60,19 +57,19 @@ public final class ProxyListener {
@Subscribe(order = PostOrder.FIRST) @Subscribe(order = PostOrder.FIRST)
public void onPlayerChat(final PlayerChatEvent event) { public void onPlayerChat(final PlayerChatEvent event) {
if (api.isNotLogged(event.getPlayer())) { if (plugin.isNotLogged(event.getPlayer())) {
event.setResult(PlayerChatEvent.ChatResult.denied()); event.setResult(PlayerChatEvent.ChatResult.denied());
} }
} }
@Subscribe(order = PostOrder.FIRST) @Subscribe(order = PostOrder.FIRST)
public void onTabComplete(TabCompleteEvent event){ public void onTabComplete(TabCompleteEvent event){
if (api.isLogged(event.getPlayer())) { if (plugin.isLogged(event.getPlayer())) {
return; return;
} }
final String command = event.getPartialMessage(); final String command = event.getPartialMessage();
for (final String allowed : config.getCommandsConfig().getAllowedCommands()) { for (final String allowed : plugin.config().getConfig().commands().allowedCommands()) {
if (allowed.startsWith(command)) { if (allowed.startsWith(command)) {
return; return;
} }
@ -81,4 +78,11 @@ public final class ProxyListener {
event.getSuggestions().clear(); event.getSuggestions().clear();
} }
void sendBlockedMessage(Player player){
String blockedMessage = plugin.config().getConfig().commands().blockedCommandMessage();
if (!blockedMessage.isBlank()){
player.sendMessage(MiniMessage.miniMessage().deserialize(blockedMessage));
}
}
} }