From ce9db9ec10fa210996a1c486f9c5fee923aee961 Mon Sep 17 00:00:00 2001 From: Jaime Martinez Rincon Date: Sun, 10 Sep 2017 23:01:02 +0200 Subject: [PATCH] Some progress --- README.md | 19 +- pom.xml | 56 +---- .../playerbalancer/PlayerBalancer.java | 157 +++++++++----- .../commands/FallbackCommand.java | 148 +++++++------ .../commands/ManageCommand.java | 62 +++--- .../connection/ConnectionIntent.java | 44 ++-- .../connection/ProviderType.java | 14 +- .../listener/PlayerDisconnectListener.java | 14 +- .../listener/PluginMessageListener.java | 37 ++-- .../listener/ServerConnectListener.java | 96 ++++----- .../listener/ServerKickListener.java | 204 +++++++++--------- .../manager/NetworkManager.java | 23 +- .../playerbalancer/manager/PasteHelper.java | 18 +- .../playerbalancer/ping/ServerStatus.java | 10 +- .../playerbalancer/ping/StatusManager.java | 29 ++- .../section/SectionCommand.java | 53 ++--- .../section/SectionManager.java | 82 +++++-- .../playerbalancer/section/ServerSection.java | 185 +++++++++------- .../playerbalancer/settings/MainSettings.java | 110 ++++++++++ .../playerbalancer/settings/Settings.java | 12 -- .../settings/SettingsProvider.java | 44 ---- .../settings/beans/CommandData.java | 41 ---- .../settings/beans/SectionData.java | 71 ------ .../settings/props/FallbackCommandProps.java | 92 ++++++++ .../settings/props/GeneralProps.java | 108 ++++++++++ .../settings/props/KickHandlerProps.java | 127 +++++++++++ .../settings/props/MessagesProps.java | 134 ++++++++++++ .../settings/props/ServerCheckerProps.java | 99 +++++++++ .../serializers/SectionSerializer.java | 19 ++ .../settings/shared/CommandProps.java | 46 ++++ .../settings/shared/SectionProps.java | 100 +++++++++ .../settings/types/CheckerProperties.java | 27 --- .../settings/types/CommandProperties.java | 27 --- .../settings/types/GeneralProperties.java | 22 -- .../settings/types/MessageProperties.java | 28 --- .../settings/types/ReconnectorProperties.java | 30 --- .../settings/types/SectionsHolder.java | 50 ----- .../playerbalancer/utils/GuestPaste.java | 54 ++++- src/main/resources/default.conf | 1 + 39 files changed, 1537 insertions(+), 956 deletions(-) create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/MainSettings.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/Settings.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/SettingsProvider.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/beans/CommandData.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/beans/SectionData.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/props/FallbackCommandProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/props/GeneralProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/props/KickHandlerProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/props/MessagesProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/props/ServerCheckerProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/serializers/SectionSerializer.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/shared/CommandProps.java create mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/shared/SectionProps.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/CheckerProperties.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/CommandProperties.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/GeneralProperties.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/MessageProperties.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/ReconnectorProperties.java delete mode 100644 src/main/java/com/jaimemartz/playerbalancer/settings/types/SectionsHolder.java create mode 100644 src/main/resources/default.conf diff --git a/README.md b/README.md index 71b228a..a639fad 100644 --- a/README.md +++ b/README.md @@ -4,23 +4,20 @@ [![Build Status](https://travis-ci.com/Jamezrin/PlayerBalancer.svg?token=2yUi9WpA9QzSbJx9eTmy&branch=master)](https://travis-ci.com/Jamezrin/PlayerBalancer) ### Things to do: -- [x] Get dummy sections able to have already registered servers on other sections -- [x] Add a new message for when a player gets connected to a server and repurpose the connecting one +- [x] Get dummy sections able to have already registered serverEntries on other sections +- [x] Add a new message for when a player gets connected to a serverName and repurpose the connecting one - [ ] Add support for wildcards, contains, equalsIgnoreCase and regex at the same time -- [ ] Add option to force joining a specific section -- [x] Add tooltip when you hover over a server in /section info +- [ ] Add option to force joining a specific section (to the command) +- [x] Add tooltip when you hover over a serverName in /section info - [ ] Stop using inventivetalent's deprecated bungee-update - [ ] Create a spigot addon that adds connector signs and placeholders - [x] Separate the types of connections in classes instead of being in ConnectionIntent - [ ] Make the plugin API be not so dependent on a instance of PlayerBalancer - [ ] Separate connection providers in classes instead of being hardcoded in an enum -- [x] Make the feature `marker-descs` work per section -- [ ] Add a identifier to get the servers of a section (auto complete) +- [ ] Make the feature `marker-descs` work per section +- [ ] Add a identifier to get the serverEntries of a section (auto complete) - [ ] Implement fast connect (dimension change) - [ ] Implement a way to redirect premium players to a section and cracked ones to other section (not sure how this works) -- [ ] Unify the code that loads server into a section (duplicated at SectionManager and ServerSection) +- [ ] Unify the code that loads serverName into a section (duplicated at SectionManager and ServerSection) - [ ] Unify some of the code used in the FallbackCommand and SectionCommand -- [ ] (!) Make the section initialization work in stages instead of being hardcoded -- [ ] (!) Ditch the faucet dependency and use [ConfigMe](https://github.com/AuthMe/ConfigMe) and [DependencyInjector](https://github.com/ljacqu/DependencyInjector) instead -- [ ] Use a separate file for configuring the sections, must be done alongside the previous item -- [ ] Make this repository public \ No newline at end of file +- [ ] Make the section initialization work in stages instead of being hardcoded \ No newline at end of file diff --git a/pom.xml b/pom.xml index fa83bd8..477e777 100644 --- a/pom.xml +++ b/pom.xml @@ -68,21 +68,6 @@ - @@ -98,59 +83,30 @@ 1.11-SNAPSHOT provided - - - ch.jalu - configme - 0.6-SNAPSHOT - compile - - - - org.yaml - snakeyaml - - - - - - ch.jalu - injector - 0.5-SNAPSHOT - compile - - - org.inventivetalent.update bungee 1.0.1 compile - - com.imaginarycode.minecraft RedisBungee 0.3.8-SNAPSHOT provided - - + + ninja.leaping.configurate + configurate-hocon + 3.3 + compile + org.bstats bstats-bungeecord 1.2 compile - - - org.projectlombok - lombok - 1.16.16 - provided - - junit junit diff --git a/src/main/java/com/jaimemartz/playerbalancer/PlayerBalancer.java b/src/main/java/com/jaimemartz/playerbalancer/PlayerBalancer.java index 20d4fb2..b91bd29 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/PlayerBalancer.java +++ b/src/main/java/com/jaimemartz/playerbalancer/PlayerBalancer.java @@ -1,57 +1,91 @@ package com.jaimemartz.playerbalancer; -import ch.jalu.injector.Injector; -import ch.jalu.injector.InjectorBuilder; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.SettingsProvider; -import lombok.Getter; -import net.md_5.bungee.api.ProxyServer; +import com.google.common.reflect.TypeToken; +import com.jaimemartz.playerbalancer.commands.FallbackCommand; +import com.jaimemartz.playerbalancer.commands.MainCommand; +import com.jaimemartz.playerbalancer.commands.ManageCommand; +import com.jaimemartz.playerbalancer.connection.ServerAssignRegistry; +import com.jaimemartz.playerbalancer.listener.*; +import com.jaimemartz.playerbalancer.manager.NetworkManager; +import com.jaimemartz.playerbalancer.manager.PasteHelper; +import com.jaimemartz.playerbalancer.manager.PlayerLocker; +import com.jaimemartz.playerbalancer.ping.StatusManager; +import com.jaimemartz.playerbalancer.section.SectionManager; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.settings.MainSettings; +import com.jaimemartz.playerbalancer.settings.serializers.SectionSerializer; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; +import ninja.leaping.configurate.ConfigurationOptions; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; import org.bstats.bungeecord.Metrics; +import org.inventivetalent.update.bungee.BungeeUpdater; + +import java.io.File; +import java.io.IOException; +import java.util.logging.Level; public class PlayerBalancer extends Plugin { - @Getter private boolean failed = false; - - private Injector injector; - private Settings settings; - + private boolean failed = false; + private StatusManager statusManager; + private MainSettings mainSettings; + private ConfigurationLoader loader; + private SectionManager sectionManager; + private NetworkManager networkManager; private Command fallbackCommand, mainCommand, manageCommand; private Listener connectListener, kickListener, messageListener, reloadListener; @Override public void onEnable() { - injector = new InjectorBuilder() - .addDefaultHandlers(getClass().getPackage().getName()) - .create(); - - injector.register(PlayerBalancer.class, this); - injector.register(ProxyServer.class, this.getProxy()); - - injector.registerProvider(Settings.class, SettingsProvider.class); - - settings = injector.getSingleton(Settings.class); - Metrics metrics = new Metrics(this); + metrics.addCustomChart(new Metrics.SingleLineChart("configured_sections", () -> sectionManager.getSections().size())); - if (this.enable()) { - //metrics.addCustomChart(new Metrics.SingleLineChart("configured_sections", () -> s.size())); - } + this.enable(); } - private boolean enable() { - /* + private void enable() { + if (!getDataFolder().exists()) + getDataFolder().mkdir(); + + File file = new File(getDataFolder(), "default.conf"); + + if (loader == null) { + TypeSerializerCollection serializers = TypeSerializers.getDefaultSerializers().newChild(); + serializers.registerType(TypeToken.of(ServerSection.class), new SectionSerializer()); + ConfigurationOptions options = ConfigurationOptions.defaults().setSerializers(serializers); + //options.setMapFactory(MapFactories.insertionOrdered()); + loader = HoconConfigurationLoader.builder().setFile(file).setDefaultOptions(options).build(); + } + + try { + CommentedConfigurationNode node = loader.load(); + + if (!file.exists()) { + mainSettings = new MainSettings()._defaults(); + node.setValue(TypeToken.of(MainSettings.class), mainSettings); + loader.save(node); + } else { + mainSettings = node.getValue(TypeToken.of(MainSettings.class)); + } + } catch (Exception e) { + e.printStackTrace(); + } + mainCommand = new MainCommand(this); getProxy().getPluginManager().registerCommand(this, mainCommand); - if (settings.getProperty(GeneralProperties.ENABLED)) { - if (settings.getProperty(GeneralProperties.SILENT)) { + if (mainSettings.getGeneralProps().isActive()) { + if (mainSettings.getGeneralProps().isSilent()) { getLogger().setLevel(Level.WARNING); } - if (settings.getProperty(GeneralProperties.AUTO_RELOAD)) { - reloadListener = injector.getSingleton(ProxyReloadListener.class); + if (mainSettings.getGeneralProps().isAutoReload()) { + reloadListener = new ProxyReloadListener(this); getProxy().getPluginManager().registerListener(this, reloadListener); } @@ -61,43 +95,43 @@ public class PlayerBalancer extends Plugin { e.printStackTrace(); } + networkManager = new NetworkManager(this); sectionManager = new SectionManager(this); try { sectionManager.load(); - statusManager = new StatusManager(); - if (settings.getProperty(CheckerProperties.ENABLED)) { - statusManager.start(this); + statusManager = new StatusManager(this); + if (mainSettings.getServerCheckerProps().isActive()) { + statusManager.start(); } - if (settings.getProperty(CommandProperties.ENABLED)) { - fallbackCommand = injector.getSingleton(FallbackCommand.class); + if (mainSettings.getFallbackCommandProps().isActive()) { + fallbackCommand = new FallbackCommand(this, mainSettings.getFallbackCommandProps().getCommand()); getProxy().getPluginManager().registerCommand(this, fallbackCommand); } - connectListener = injector.getSingleton(ServerConnectListener.class); + connectListener = new ServerConnectListener(this); getProxy().getPluginManager().registerListener(this, connectListener); - messageListener = injector.getSingleton(PluginMessageListener.class); + messageListener = new PluginMessageListener(this); getProxy().getPluginManager().registerListener(this, messageListener); - manageCommand = injector.getSingleton(ManageCommand.class); + manageCommand = new ManageCommand(this); getProxy().getPluginManager().registerCommand(this, manageCommand); - getProxy().getPluginManager().registerListener(this, injector.getSingleton(PlayerDisconnectListener.class)); + getProxy().getPluginManager().registerListener(this, new PlayerDisconnectListener(this)); getProxy().registerChannel("PlayerBalancer"); - Stream.of(PasteHelper.values()).forEach(a -> a.setUrl(null)); + PasteHelper.reset(); - if (settings.getProperty(ReconnectorProperties.ENABLED)) { - kickListener = injector.getSingleton(ServerKickListener.class); + if (mainSettings.getKickHandlerProps().isActive()) { + kickListener = new ServerKickListener(this); getProxy().getPluginManager().registerListener(this, kickListener); } getLogger().info("The plugin has finished loading without any problems"); - return true; } catch (RuntimeException e) { this.failed = true; getLogger().severe("The plugin could not continue loading due to an unexpected exception"); @@ -109,8 +143,6 @@ public class PlayerBalancer extends Plugin { getLogger().warning("Nothing is going to work until you do that, you can reload me by using the /balancer command"); getLogger().warning("-----------------------------------------------------"); } - */ - return false; } @Override @@ -119,24 +151,23 @@ public class PlayerBalancer extends Plugin { } private void disable() { - /* getProxy().getPluginManager().unregisterCommand(mainCommand); mainCommand = null; - if (settings.getProperty(GeneralProperties.ENABLED)) { + if (mainSettings.getGeneralProps().isActive()) { //Do not try to do anything if the plugin has not loaded correctly - if (isFailed()) return; + if (failed) return; - if (settings.getProperty(GeneralProperties.AUTO_RELOAD)) { + if (mainSettings.getGeneralProps().isAutoReload()) { getProxy().getPluginManager().unregisterListener(reloadListener); reloadListener = null; } - if (settings.getProperty(CheckerProperties.ENABLED)) { + if (mainSettings.getServerCheckerProps().isActive()) { statusManager.stop(); } - if (settings.getProperty(CommandProperties.ENABLED)) { + if (mainSettings.getFallbackCommandProps().isActive()) { getProxy().getPluginManager().unregisterCommand(fallbackCommand); fallbackCommand = null; } @@ -150,21 +181,20 @@ public class PlayerBalancer extends Plugin { getProxy().getPluginManager().unregisterCommand(manageCommand); manageCommand = null; - if (settings.getProperty(ReconnectorProperties.ENABLED)) { + if (mainSettings.getKickHandlerProps().isActive()) { getProxy().getPluginManager().unregisterListener(kickListener); kickListener = null; } sectionManager.flush(); - if (settings.getProperty(GeneralProperties.ASSIGN_TARGETS)) { + if (mainSettings.getGeneralProps().isAssignTargets()) { ServerAssignRegistry.getTable().clear(); } } PlayerLocker.flush(); failed = false; - */ } public boolean reloadPlugin() { @@ -172,7 +202,6 @@ public class PlayerBalancer extends Plugin { long starting = System.currentTimeMillis(); this.disable(); - settings.reload(); this.enable(); long ending = System.currentTimeMillis() - starting; @@ -180,4 +209,20 @@ public class PlayerBalancer extends Plugin { return !failed; } + + public MainSettings getSettings() { + return mainSettings; + } + + public SectionManager getSectionManager() { + return sectionManager; + } + + public StatusManager getStatusManager() { + return statusManager; + } + + public NetworkManager getNetworkManager() { + return networkManager; + } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/commands/FallbackCommand.java b/src/main/java/com/jaimemartz/playerbalancer/commands/FallbackCommand.java index dbc45e0..cb8dd9e 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/commands/FallbackCommand.java +++ b/src/main/java/com/jaimemartz/playerbalancer/commands/FallbackCommand.java @@ -1,101 +1,97 @@ package com.jaimemartz.playerbalancer.commands; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.types.CommandProperties; -import com.jaimemartz.playerbalancer.settings.types.SectionsHolder; +import com.jaimemartz.playerbalancer.PlayerBalancer; +import com.jaimemartz.playerbalancer.connection.ConnectionIntent; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.settings.MainSettings; +import com.jaimemartz.playerbalancer.settings.props.MessagesProps; +import com.jaimemartz.playerbalancer.settings.shared.CommandProps; +import com.jaimemartz.playerbalancer.utils.MessageUtils; +import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import javax.inject.Inject; - public class FallbackCommand extends Command { - @Inject - private Settings settings; + protected final PlayerBalancer plugin; + protected final MessagesProps messages; + protected final MainSettings settings; - @Inject - private SectionsHolder holder; - - @Inject //todo maybe make this job of the main class (initializer) - public FallbackCommand(Settings settings) { - super( - settings.getProperty(CommandProperties.COMMAND).getName(), - settings.getProperty(CommandProperties.COMMAND).getPermission(), - settings.getProperty(CommandProperties.COMMAND).getAliases() - ); + public FallbackCommand(PlayerBalancer plugin, CommandProps props) { + super(props.getName(), props.getPermission(), props.getAliasesArray()); + this.settings = plugin.getSettings(); + this.messages = settings.getMessagesProps(); + this.plugin = plugin; } @Override public void execute(CommandSender sender, String[] args) { - /* if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; + ServerSection target = this.getSection(player); - Callable callable = () -> { - ServerSection current = holder.getByPlayer(player); - - if (current != null) { - if (settings.getProperty(CommandProperties.IGNORED_SECTIONS).contains(current.getName())) { - MessageUtils.send(player, settings.getProperty(MessageProperties.UNAVAILABLE_SERVER)); - return null; - } - - MapBean rules = settings.getProperty(CommandProperties.RULES); - String bind = rules.getMap().get(current.getName()); - ServerSection target = holder.getByName(bind); - - if (target == null) { - if (current.getParent() != null) { - target = current.getParent(); + if (target != null) { + if (args.length == 1) { + try { + int number = Integer.parseInt(args[0]); + if (number <= 0) { + MessageUtils.send(player, messages.getInvalidInputMessage()); + } else if (number > target.getMappedServers().size()) { + MessageUtils.send(player, messages.getFailureMessage()); } else { - MessageUtils.send(player, settings.getProperty(MessageProperties.UNAVAILABLE_SERVER)); - return null; + ServerInfo server = target.getSortedServers().get(number - 1); + ConnectionIntent.direct(plugin, player, server, (response, throwable) -> { + }); } + } catch (NumberFormatException e) { + MessageUtils.send(player, messages.getInvalidInputMessage()); } - - if (settings.getProperty(CommandProperties.RESTRICTED)) { - if (current.getPosition() >= 0 && target.getPosition() < 0) { - MessageUtils.send(player, settings.getProperty(MessageProperties.UNAVAILABLE_SERVER)); - return null; - } - } - - return target; } else { - if (settings.getProperty(GeneralProperties.FALLBACK_PRINCIPAL)) { - return holder.getPrincipal(); - } + ConnectionIntent.simple(plugin, player, target); } - - return null; - }; - - try { - ServerSection target = callable.call(); - if (target != null) { - if (args.length == 1) { - try { - int number = Integer.parseInt(args[0]); - if (number <= 0) { - MessageUtils.send(player, settings.getProperty(MessageProperties.INVALID_INPUT)); - } else if (number > target.getServers().size()) { - MessageUtils.send(player, settings.getProperty(MessageProperties.MISC_FAILURE)); - } else { - ServerInfo server = target.getSortedServers().get(number - 1); - ConnectionIntent.direct(plugin, player, server, (response, throwable) -> {}); - } - } catch (NumberFormatException e) { - MessageUtils.send(player, settings.getProperty(MessageProperties.INVALID_INPUT)); - } - } else { - ConnectionIntent.simple(plugin, player, target); - } - } - } catch (Exception e) { - //Nothing to do } } else { sender.sendMessage(new ComponentBuilder("This command can only be executed by a player").color(ChatColor.RED).create()); } - */ + } + + public ServerSection getSection(ProxiedPlayer player) { + ServerSection current = plugin.getSectionManager().getByPlayer(player); + + if (current != null) { + if (settings.getFallbackCommandProps().getExcludedSections().contains(current.getName())) { + MessageUtils.send(player, messages.getUnavailableServerMessage()); + return null; + } + + String bind = settings.getFallbackCommandProps().getRules().get(current.getName()); + ServerSection target = plugin.getSectionManager().getByName(bind); + + if (target == null) { + if (current.getParent() != null) { + target = current.getParent(); + } else { + MessageUtils.send(player, messages.getUnavailableServerMessage()); + return null; + } + } + + if (settings.getFallbackCommandProps().isRestrictive()) { + if (current.getPosition() >= 0 && target.getPosition() < 0) { + MessageUtils.send(player, messages.getUnavailableServerMessage()); + return null; + } + } + + return target; + } else { + if (settings.getGeneralProps().isFallbackPrincipal()) { + return plugin.getSectionManager().getPrincipal(); + } + } + + return null; } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/commands/ManageCommand.java b/src/main/java/com/jaimemartz/playerbalancer/commands/ManageCommand.java index 71ea649..06c0102 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/commands/ManageCommand.java +++ b/src/main/java/com/jaimemartz/playerbalancer/commands/ManageCommand.java @@ -1,37 +1,38 @@ package com.jaimemartz.playerbalancer.commands; +import com.google.common.base.Strings; import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.ping.StatusManager; -import com.jaimemartz.playerbalancer.settings.Settings; +import com.jaimemartz.playerbalancer.connection.ConnectionIntent; +import com.jaimemartz.playerbalancer.ping.ServerStatus; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.utils.MessageUtils; +import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; -import javax.inject.Inject; +import java.util.Arrays; public class ManageCommand extends Command { - @Inject - private PlayerBalancer plugin; + private final PlayerBalancer plugin; - @Inject - private StatusManager checker; - - @Inject - private Settings settings; - - public ManageCommand() { + public ManageCommand(PlayerBalancer plugin) { super("section"); + this.plugin = plugin; } @Override public void execute(CommandSender sender, String[] args) { - /* if (sender.hasPermission("playerbalancer.admin")) { if (args.length != 0) { switch (args[0].toLowerCase()) { case "connect": { if (args.length >= 2) { String input = args[1]; - ServerSection section = holder.getByName(input); + ServerSection section = plugin.getSectionManager().getByName(input); if (section != null) { if (args.length == 3) { ProxiedPlayer player = plugin.getProxy().getPlayer(args[2]); @@ -48,7 +49,7 @@ public class ManageCommand extends Command { } } } else { - MessageUtils.send(sender, settings.getProperty(MessageProperties.UNKNOWN_SECTION)); + MessageUtils.send(sender, plugin.getSettings().getMessagesProps().getUnknownSectionMessage()); } } else { sender.sendMessage(new ComponentBuilder("Usage: /balancer connect
[player]").color(ChatColor.RED).create()); @@ -59,7 +60,7 @@ public class ManageCommand extends Command { case "info": { if (args.length == 2) { String input = args[1]; - ServerSection section = holder.getByName(input); + ServerSection section = plugin.getSectionManager().getByName(input); if (section != null) { sender.sendMessage(new ComponentBuilder(Strings.repeat("-", 53)).strikethrough(true).color(ChatColor.GRAY).create()); @@ -71,8 +72,8 @@ public class ManageCommand extends Command { sender.sendMessage(new ComponentBuilder("Principal: ") .color(ChatColor.GRAY) - .append(section.isPrincipal() ? "yes" : "no") - .color(section.isPrincipal() ? ChatColor.GREEN : ChatColor.RED) + .append(section.getProps().isPrincipal() ? "yes" : "no") + .color(section.getProps().isPrincipal() ? ChatColor.GREEN : ChatColor.RED) .create()); if (section.getParent() != null) { @@ -100,7 +101,7 @@ public class ManageCommand extends Command { sender.sendMessage(new ComponentBuilder("Provider: ") .color(ChatColor.GRAY) - .append(section.getProvider().name()) + .append(section.getEffectiveProvider().name()) .color(ChatColor.AQUA) .append(String.format(" (%s)", section.isInherited() ? "Inherited" : "Specified")) .color(ChatColor.GRAY) @@ -109,8 +110,8 @@ public class ManageCommand extends Command { sender.sendMessage(new ComponentBuilder("Dummy: ") .color(ChatColor.GRAY) - .append(section.isDummy() ? "yes" : "no") - .color(section.isDummy() ? ChatColor.GREEN : ChatColor.RED) + .append(section.getProps().isDummy() ? "yes" : "no") + .color(section.getProps().isDummy() ? ChatColor.GREEN : ChatColor.RED) .create() ); @@ -156,14 +157,14 @@ public class ManageCommand extends Command { ); } - if (!section.getServers().isEmpty()) { + if (!section.getMappedServers().isEmpty()) { sender.sendMessage(new ComponentBuilder("Section Servers: ") .color(ChatColor.GRAY) .create() ); - section.getServers().forEach(server -> { - ServerStatus status = checker.getStatus(server); + section.getMappedServers().forEach(server -> { + ServerStatus status = plugin.getStatusManager().getStatus(server); sender.sendMessage(new ComponentBuilder("\u2022 Server: ") .color(ChatColor.GRAY) .append(server.getName()) @@ -171,8 +172,8 @@ public class ManageCommand extends Command { .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Accessible: ") .color(ChatColor.GRAY) - .append(status.isAccessible() ? "yes" : "no") - .color(status.isAccessible() ? ChatColor.GREEN : ChatColor.RED) + .append(status.isAccessible(plugin, null) ? "yes" : "no") + .color(status.isAccessible(plugin, null) ? ChatColor.GREEN : ChatColor.RED) .append("\nDescription: ") .color(ChatColor.GRAY) .append("\"") @@ -200,7 +201,7 @@ public class ManageCommand extends Command { sender.sendMessage(new ComponentBuilder(Strings.repeat("-", 53)).strikethrough(true).color(ChatColor.GRAY).create()); } else { - MessageUtils.send(sender, settings.getProperty(MessageProperties.UNKNOWN_SECTION)); + MessageUtils.send(sender, plugin.getSettings().getMessagesProps().getUnknownSectionMessage()); } } else { sender.sendMessage(new ComponentBuilder("Usage: /balancer info
").color(ChatColor.RED).create()); @@ -209,12 +210,10 @@ public class ManageCommand extends Command { } case "list": { - Map sections = sections.getSections(); - - if (!sections.isEmpty()) { + if (!plugin.getSectionManager().getSections().isEmpty()) { sender.sendMessage(new ComponentBuilder("These are the registered sections: ").color(ChatColor.GRAY).create()); - sections.forEach((name, section) -> { + plugin.getSectionManager().getSections().forEach((name, section) -> { sender.sendMessage(new ComponentBuilder("\u2022 Section: ") .color(ChatColor.GRAY) .event(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.format("/section info %s", name))) @@ -246,6 +245,5 @@ public class ManageCommand extends Command { } else { sender.sendMessage(new ComponentBuilder("You do not have permission to execute this command!").color(ChatColor.RED).create()); } - */ } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/connection/ConnectionIntent.java b/src/main/java/com/jaimemartz/playerbalancer/connection/ConnectionIntent.java index c94fe29..7a77db8 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/connection/ConnectionIntent.java +++ b/src/main/java/com/jaimemartz/playerbalancer/connection/ConnectionIntent.java @@ -1,7 +1,20 @@ package com.jaimemartz.playerbalancer.connection; +import com.jaimemartz.playerbalancer.PlayerBalancer; +import com.jaimemartz.playerbalancer.manager.PlayerLocker; +import com.jaimemartz.playerbalancer.ping.ServerStatus; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.utils.MessageUtils; +import net.md_5.bungee.api.Callback; +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.List; +import java.util.concurrent.TimeUnit; + public abstract class ConnectionIntent { - /* protected final PlayerBalancer plugin; protected final ProxiedPlayer player; protected final ServerSection section; @@ -11,56 +24,56 @@ public abstract class ConnectionIntent { this.player = player; this.section = section; - MessageUtils.send(player, ConfigEntries.CONNECTING_MESSAGE.get(), + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getConnectedMessage(), (str) -> str.replace("{section}", section.getName()) ); - if (servers == section.getServers()) { + if (servers == section.getMappedServers()) { throw new IllegalStateException("The servers list parameter is the same reference, this cannot happen"); } Server current = player.getServer(); if (current != null) { - if (section.getServers().contains(current.getInfo())) { - MessageUtils.send(player, ConfigEntries.SAME_SECTION.get()); + if (section.getMappedServers().contains(current.getInfo())) { + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getSameSectionMessage()); return; } } - if (section.getProvider() != ProviderType.NONE) { + if (section.getEffectiveProvider() != ProviderType.NONE) { ServerInfo target = this.fetchServer(plugin, player, section, provider, servers); if (target != null) { this.connect(target, (response, throwable) -> { if (response) { //only if the connect has been executed correctly - MessageUtils.send(player, ConfigEntries.CONNECTED_MESSAGE.get(), + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getConnectedMessage(), (str) -> str.replace("{server}", target.getName()) ); } }); } else { - MessageUtils.send(player, ConfigEntries.FAILURE_MESSAGE.get()); + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getFailureMessage()); } } } public ConnectionIntent(PlayerBalancer plugin, ProxiedPlayer player, ServerSection section) { - this(plugin, player, section.getProvider(), section); + this(plugin, player, section.getEffectiveProvider(), section); } public ConnectionIntent(PlayerBalancer plugin, ProxiedPlayer player, ProviderType type, ServerSection section) { - this(plugin, player, type, section, new ArrayList<>(section.getServers())); + this(plugin, player, type, section, new ArrayList<>(section.getMappedServers())); } public ConnectionIntent(PlayerBalancer plugin, ProxiedPlayer player, ServerSection section, List servers) { - this(plugin, player, section.getProvider(), section, servers); + this(plugin, player, section.getEffectiveProvider(), section, servers); } private ServerInfo fetchServer(PlayerBalancer plugin, ProxiedPlayer player, ServerSection section, ProviderType provider, List servers) { - if (ConfigEntries.ASSIGN_TARGETS_ENABLED.get()) { + if (plugin.getSettings().getGeneralProps().isAssignTargets()) { if (ServerAssignRegistry.hasAssignedServer(player, section)) { ServerInfo target = ServerAssignRegistry.getAssignedServer(player, section); ServerStatus status = plugin.getStatusManager().getStatus(target); - if (status.isAccessible()) { + if (status.isAccessible(plugin, player)) { return target; } else { ServerAssignRegistry.revokeTarget(player, section); @@ -68,7 +81,7 @@ public abstract class ConnectionIntent { } } - int intents = ConfigEntries.SERVER_CHECK_ATTEMPTS.get(); + int intents = plugin.getSettings().getServerCheckerProps().getAttempts(); for (int intent = 1; intent <= intents; intent++) { if (servers.size() == 0) return null; @@ -76,7 +89,7 @@ public abstract class ConnectionIntent { if (target == null) continue; ServerStatus status = plugin.getStatusManager().getStatus(target); - if (status.isAccessible()) { + if (status.isAccessible(plugin, player)) { return target; } else { servers.remove(target); @@ -108,5 +121,4 @@ public abstract class ConnectionIntent { callback.done(result, throwable); }); } - */ } \ No newline at end of file diff --git a/src/main/java/com/jaimemartz/playerbalancer/connection/ProviderType.java b/src/main/java/com/jaimemartz/playerbalancer/connection/ProviderType.java index 7f9465b..792f89c 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/connection/ProviderType.java +++ b/src/main/java/com/jaimemartz/playerbalancer/connection/ProviderType.java @@ -1,7 +1,7 @@ package com.jaimemartz.playerbalancer.connection; import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.manager.NetworkManager; +import com.jaimemartz.playerbalancer.ping.ServerStatus; import com.jaimemartz.playerbalancer.section.ServerSection; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -24,7 +24,7 @@ public enum ProviderType { ServerInfo target = null; for (ServerInfo server : list) { - int count = NetworkManager.getPlayers(server).size(); + int count = plugin.getNetworkManager().getPlayers(server); if (count < min) { min = count; @@ -46,30 +46,26 @@ public enum ProviderType { PROGRESSIVE { @Override public ServerInfo requestTarget(PlayerBalancer plugin, ServerSection section, List list, ProxiedPlayer player) { - /* for (ServerInfo server : list) { ServerStatus status = plugin.getStatusManager().getStatus(server); - if (NetworkManager.getPlayers(server).size() < status.getMaximum()) { + if (plugin.getNetworkManager().getPlayers(server) < status.getMaximum()) { return server; } } return list.get(ThreadLocalRandom.current().nextInt(list.size())); - */ - return null; } }, FILLER { @Override public ServerInfo requestTarget(PlayerBalancer plugin, ServerSection section, List list, ProxiedPlayer player) { - /* int max = Integer.MIN_VALUE; ServerInfo target = null; for (ServerInfo server : list) { ServerStatus status = plugin.getStatusManager().getStatus(server); - int count = NetworkManager.getPlayers(server).size(); + int count = plugin.getNetworkManager().getPlayers(server); if (count > max && count <= status.getMaximum()) { max = count; @@ -78,8 +74,6 @@ public enum ProviderType { } return target; - */ - return null; } }; diff --git a/src/main/java/com/jaimemartz/playerbalancer/listener/PlayerDisconnectListener.java b/src/main/java/com/jaimemartz/playerbalancer/listener/PlayerDisconnectListener.java index 30fd7fc..e438e76 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/listener/PlayerDisconnectListener.java +++ b/src/main/java/com/jaimemartz/playerbalancer/listener/PlayerDisconnectListener.java @@ -1,20 +1,20 @@ package com.jaimemartz.playerbalancer.listener; +import com.jaimemartz.playerbalancer.PlayerBalancer; import com.jaimemartz.playerbalancer.connection.ServerAssignRegistry; import com.jaimemartz.playerbalancer.manager.PlayerLocker; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.types.GeneralProperties; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; -import javax.inject.Inject; - public class PlayerDisconnectListener implements Listener { - @Inject - private Settings settings; + private final PlayerBalancer plugin; + + public PlayerDisconnectListener(PlayerBalancer plugin) { + this.plugin = plugin; + } @EventHandler(priority = EventPriority.HIGHEST) public void onDisconnect(PlayerDisconnectEvent event) { @@ -22,7 +22,7 @@ public class PlayerDisconnectListener implements Listener { PlayerLocker.unlock(player); //Delete this if we want to keep assigned groups even when leaving - if (settings.getProperty(GeneralProperties.ASSIGN_TARGETS)) { + if (plugin.getSettings().getGeneralProps().isAssignTargets()) { ServerAssignRegistry.clearAsssignedServers(player); } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/listener/PluginMessageListener.java b/src/main/java/com/jaimemartz/playerbalancer/listener/PluginMessageListener.java index 7529988..5b7e2ff 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/listener/PluginMessageListener.java +++ b/src/main/java/com/jaimemartz/playerbalancer/listener/PluginMessageListener.java @@ -1,29 +1,30 @@ package com.jaimemartz.playerbalancer.listener; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.types.SectionsHolder; +import com.jaimemartz.playerbalancer.connection.ConnectionIntent; +import com.jaimemartz.playerbalancer.section.ServerSection; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.event.PluginMessageEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; -import javax.inject.Inject; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; public class PluginMessageListener implements Listener { - @Inject - private PlayerBalancer plugin; - - @Inject - private Settings settings; - - @Inject - private SectionsHolder holder; - + private final PlayerBalancer plugin; private final Gson gson; - public PluginMessageListener() { + public PluginMessageListener(PlayerBalancer plugin) { + this.plugin = plugin; + GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.excludeFieldsWithoutExposeAnnotation(); @@ -32,7 +33,6 @@ public class PluginMessageListener implements Listener { @EventHandler public void onPluginMessage(PluginMessageEvent event) { - /* if (event.getTag().equals("PlayerBalancer") && event.getSender() instanceof Server) { ByteArrayDataInput in = ByteStreams.newDataInput(event.getData()); String request = in.readUTF(); @@ -41,7 +41,7 @@ public class PluginMessageListener implements Listener { case "Connect": { if (event.getReceiver() instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) event.getReceiver(); - ServerSection section = holder.getByName(in.readUTF()); + ServerSection section = plugin.getSectionManager().getByName(in.readUTF()); if (section == null) { return; @@ -58,7 +58,7 @@ public class PluginMessageListener implements Listener { return; } - ServerSection section = holder.getByName(in.readUTF()); + ServerSection section = plugin.getSectionManager().getByName(in.readUTF()); if (section == null) { return; } @@ -71,7 +71,7 @@ public class PluginMessageListener implements Listener { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(stream); - ServerSection section = holder.getByName(in.readUTF()); + ServerSection section = plugin.getSectionManager().getByName(in.readUTF()); if (section == null) { return; } @@ -96,7 +96,7 @@ public class PluginMessageListener implements Listener { return; } - ServerSection section = holder.getByServer(server); + ServerSection section = plugin.getSectionManager().getByServer(server); if (section == null) { return; } @@ -113,6 +113,5 @@ public class PluginMessageListener implements Listener { } } } - */ } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/listener/ServerConnectListener.java b/src/main/java/com/jaimemartz/playerbalancer/listener/ServerConnectListener.java index 7b47a75..cd0cb18 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/listener/ServerConnectListener.java +++ b/src/main/java/com/jaimemartz/playerbalancer/listener/ServerConnectListener.java @@ -1,22 +1,20 @@ package com.jaimemartz.playerbalancer.listener; import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.types.SectionsHolder; +import com.jaimemartz.playerbalancer.connection.ConnectionIntent; +import com.jaimemartz.playerbalancer.connection.ServerAssignRegistry; +import com.jaimemartz.playerbalancer.manager.PlayerLocker; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.utils.MessageUtils; +import net.md_5.bungee.api.Callback; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.ServerConnectEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; -import javax.inject.Inject; - public class ServerConnectListener implements Listener { - @Inject - private Settings settings; - - @Inject - private SectionsHolder holder; - private final PlayerBalancer plugin; public ServerConnectListener(PlayerBalancer plugin) { @@ -25,59 +23,53 @@ public class ServerConnectListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onConnect(ServerConnectEvent event) { - /* ProxiedPlayer player = event.getPlayer(); ServerInfo target = event.getTarget(); - Callable callable = () -> { - ServerSection section = holder.getByServer(target); + ServerSection section = getSection(player, target); + if (section != null) { + new ConnectionIntent(plugin, player, section) { + @Override + public void connect(ServerInfo server, Callback callback) { + if (plugin.getSettings().getGeneralProps().isAssignTargets()) { + ServerAssignRegistry.assignTarget(player, section, server); + } - if (section != null) { - if (PlayerLocker.isLocked(player)) { + event.setTarget(server); + callback.done(true, null); + } + }; + } + } + + private ServerSection getSection(ProxiedPlayer player, ServerInfo target) { + ServerSection section = plugin.getSectionManager().getByServer(target); + + if (section != null) { + if (PlayerLocker.isLocked(player)) { + return null; + } + + //Checks only for servers (not the section server) + if (section.getMappedServers().contains(target)) { + if (section.getProps().isDummy()) { return null; } - //Checks only for servers (not the section server) - if (section.getServers().contains(target)) { - if (section.isDummy()) { - return null; - } + if (player.hasPermission("playerbalancer.bypass")) { + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getBypassMessage()); + return null; + } - if (player.hasPermission("playerbalancer.bypass")) { - MessageUtils.send(player, settings.getProperty(MessageProperties.PLAYER_BYPASS)); - return null; - } - - if (player.getServer() != null && section.getServers().contains(player.getServer().getInfo())) { - if (settings.getProperty(GeneralProperties.ASSIGN_TARGETS)) { - ServerAssignRegistry.assignTarget(player, section, target); - } - return null; + if (player.getServer() != null && section.getMappedServers().contains(player.getServer().getInfo())) { + if (plugin.getSettings().getGeneralProps().isAssignTargets()) { + ServerAssignRegistry.assignTarget(player, section, target); } + return null; } } - - return section; - }; - - try { - ServerSection section = callable.call(); - if (section != null) { - new ConnectionIntent(plugin, player, section) { - @Override - public void connect(ServerInfo server, Callback callback) { - if (settings.getProperty(GeneralProperties.ASSIGN_TARGETS)) { - ServerAssignRegistry.assignTarget(player, section, server); - } - - event.setTarget(server); - callback.done(true, null); - } - }; - } - } catch (Exception e) { - //Nothing to do } - */ + + return section; } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/listener/ServerKickListener.java b/src/main/java/com/jaimemartz/playerbalancer/listener/ServerKickListener.java index ac7bbb0..be75264 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/listener/ServerKickListener.java +++ b/src/main/java/com/jaimemartz/playerbalancer/listener/ServerKickListener.java @@ -1,127 +1,123 @@ package com.jaimemartz.playerbalancer.listener; import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.settings.Settings; -import com.jaimemartz.playerbalancer.settings.types.SectionsHolder; +import com.jaimemartz.playerbalancer.connection.ConnectionIntent; +import com.jaimemartz.playerbalancer.manager.PlayerLocker; +import com.jaimemartz.playerbalancer.section.ServerSection; +import com.jaimemartz.playerbalancer.utils.MessageUtils; +import net.md_5.bungee.api.Callback; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.ServerKickEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; -import javax.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; public class ServerKickListener implements Listener { - @Inject - private Settings settings; + private final PlayerBalancer plugin; - @Inject - private SectionsHolder holder; - - @Inject - private PlayerBalancer plugin; + public ServerKickListener(PlayerBalancer plugin) { + this.plugin = plugin; + } @EventHandler(priority = EventPriority.HIGHEST) public void onKick(ServerKickEvent event) { - /* ProxiedPlayer player = event.getPlayer(); ServerInfo from = event.getKickedFrom(); - //Section the player is going to be reconnected - Callable callable = () -> { - if (player.getServer() == null) { - if (settings.getProperty(ReconnectorProperties.FORCE_PRINCIPAL)) { - return holder.getPrincipal(); - } else { - return null; - } - } + ServerSection section = getSection(player, from); - if (!player.getServer().getInfo().equals(from)) { + if (section != null) { + List servers = new ArrayList<>(); + servers.addAll(section.getMappedServers()); + servers.remove(from); + + new ConnectionIntent(plugin, player, section, servers) { + @Override + public void connect(ServerInfo server, Callback callback) { + PlayerLocker.lock(player); + MessageUtils.send(player, plugin.getSettings().getMessagesProps().getKickMessage(), + (str) -> str.replace("{from}", from.getName()) + .replace("{to}", server.getName()) + .replace("{reason}", event.getKickReason())); + event.setCancelled(true); + event.setCancelServer(server); + plugin.getProxy().getScheduler().schedule(plugin, () -> { + PlayerLocker.unlock(player); + }, 5, TimeUnit.SECONDS); + callback.done(true, null); + } + }; + } + } + + private ServerSection getSection(ProxiedPlayer player, ServerInfo from) { + if (player.getServer() == null) { + if (plugin.getSettings().getKickHandlerProps().isForcePrincipal()) { + return plugin.getSectionManager().getPrincipal(); + } else { return null; } - - ServerSection current = holder.getByServer(from); - - if (current != null) { - if (settings.getProperty(ReconnectorProperties.IGNORED_SECTIONS).contains(current.getName())) { - return null; - } - } - - AtomicBoolean matches = new AtomicBoolean(false); - String reason = TextComponent.toPlainText(event.getKickReasonComponent()); - - for (String string : settings.getProperty(ReconnectorProperties.REASONS)) { - if (reason.matches(string) || reason.contains(string)) { - matches.set(true); - break; - } - } - - if (settings.getProperty(ReconnectorProperties.INVERTED)) { - matches.set(!matches.get()); - } - - if (settings.getProperty(ReconnectorProperties.DEBUG)) { - plugin.getLogger().info(String.format("Kick Reason: \"%s\", Found Match: %s", TextComponent.toPlainText(event.getKickReasonComponent()), matches)); - } - - if (matches.get()) { - if (current != null) { - MapBean rules = settings.getProperty(CommandProperties.RULES); - String bind = rules.getMap().get(current.getName()); - ServerSection target = holder.getByName(bind); - - if (target == null) { - target = current.getParent(); - } - - if (settings.getProperty(ReconnectorProperties.RESTRICTED)) { - if (current.getPosition() >= 0 && target.getPosition() < 0) { - return null; - } - } - - return target; - } else { - if (settings.getProperty(GeneralProperties.FALLBACK_PRINCIPAL)) { - return holder.getPrincipal(); - } - } - } - return null; - }; - - try { - ServerSection section = callable.call(); - if (section != null) { - List servers = new ArrayList<>(); - servers.addAll(section.getServers()); - - if (ConfigEntries.RECONNECT_KICK_EXCLUDE_FROM.get()) { - servers.remove(from); - } - - new ConnectionIntent(plugin, player, section, servers) { - @Override - public void connect(ServerInfo server, Callback callback) { - PlayerLocker.lock(player); - MessageUtils.send(player, ConfigEntries.KICK_MESSAGE.get(), - (str) -> str.replace("{from}", from.getName()) - .replace("{to}", server.getName()) - .replace("{reason}", event.getKickReason())); - event.setCancelled(true); - event.setCancelServer(server); - plugin.getProxy().getScheduler().schedule(plugin, () -> { - PlayerLocker.unlock(player); - }, 5, TimeUnit.SECONDS); - callback.done(true, null); - } - }; - } - } catch (Exception e) { - //Nothing to do } - */ + + if (!player.getServer().getInfo().equals(from)) { + return null; + } + + ServerSection current = plugin.getSectionManager().getByServer(from); + + if (current != null) { + if (plugin.getSettings().getKickHandlerProps().getExcludedSections().contains(current.getName())) { + return null; + } + } + + boolean matches = false; + String reason = TextComponent.toPlainText(event.getKickReasonComponent()); + + for (String string : settings.getProperty(ReconnectorProperties.REASONS)) { + if (reason.matches(string) || reason.contains(string)) { + matches = true; + break; + } + } + + if (settings.getProperty(ReconnectorProperties.INVERTED)) { + matches.set(!matches.get()); + } + + if (settings.getProperty(ReconnectorProperties.DEBUG)) { + plugin.getLogger().info(String.format("Kick Reason: \"%s\", Found Match: %s", TextComponent.toPlainText(event.getKickReasonComponent()), matches)); + } + + if (matches.get()) { + if (current != null) { + MapBean rules = settings.getProperty(CommandProperties.RULES); + String bind = rules.getMap().get(current.getName()); + ServerSection target = holder.getByName(bind); + + if (target == null) { + target = current.getParentName(); + } + + if (settings.getProperty(ReconnectorProperties.RESTRICTED)) { + if (current.getPosition() >= 0 && target.getPosition() < 0) { + return null; + } + } + + return target; + } else { + if (settings.getProperty(GeneralProperties.FALLBACK_PRINCIPAL)) { + return holder.getPrincipal(); + } + } + } + return null; } } \ No newline at end of file diff --git a/src/main/java/com/jaimemartz/playerbalancer/manager/NetworkManager.java b/src/main/java/com/jaimemartz/playerbalancer/manager/NetworkManager.java index af851b2..e7ea166 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/manager/NetworkManager.java +++ b/src/main/java/com/jaimemartz/playerbalancer/manager/NetworkManager.java @@ -1,24 +1,25 @@ package com.jaimemartz.playerbalancer.manager; +import com.imaginarycode.minecraft.redisbungee.RedisBungee; +import com.jaimemartz.playerbalancer.PlayerBalancer; import net.md_5.bungee.api.config.ServerInfo; -import java.util.Set; -import java.util.UUID; - public class NetworkManager { - public static Set getPlayers(ServerInfo server) { - /* - if (settings.getProperty(GeneralProperties.REDIS_BUNGEE)) { //TODO false for now + private final PlayerBalancer plugin; + + public NetworkManager(PlayerBalancer plugin) { + this.plugin = plugin; + } + + public int getPlayers(ServerInfo server) { + if (plugin.getSettings().getGeneralProps().isRedisBungee()) { try { - return RedisBungee.getApi().getPlayersOnServer(server.getName()); + return RedisBungee.getApi().getPlayersOnServer(server.getName()).size(); } catch (Exception e) { e.printStackTrace(); } } - return server.getPlayers().stream().map(ProxiedPlayer::getUniqueId).collect(Collectors.toSet()); - */ - - return null; + return server.getPlayers().size(); } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/manager/PasteHelper.java b/src/main/java/com/jaimemartz/playerbalancer/manager/PasteHelper.java index a32a938..58618e8 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/manager/PasteHelper.java +++ b/src/main/java/com/jaimemartz/playerbalancer/manager/PasteHelper.java @@ -4,8 +4,6 @@ import com.google.common.io.CharStreams; import com.jaimemartz.playerbalancer.PlayerBalancer; import com.jaimemartz.playerbalancer.utils.GuestPaste; import com.jaimemartz.playerbalancer.utils.GuestPaste.PasteException; -import lombok.Getter; -import lombok.Setter; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.ClickEvent; @@ -32,7 +30,7 @@ public enum PasteHelper { }) { @Override public URL paste(PlayerBalancer plugin) throws Exception { - File file = new File(plugin.getDataFolder(), "config.yml"); + File file = new File(plugin.getDataFolder(), "plugin.conf"); try (FileInputStream stream = new FileInputStream(file)) { try (InputStreamReader reader = new InputStreamReader(stream, "UTF-8")) { String content = CharStreams.toString(reader); @@ -46,7 +44,7 @@ public enum PasteHelper { paste.setExpiration(GuestPaste.Expiration.ONE_MONTH); paste.setExposure(GuestPaste.Exposure.UNLISTED); - paste.setFormat("yaml"); + paste.setFormat("json"); return paste.paste(); } @@ -89,10 +87,10 @@ public enum PasteHelper { } }; - @Getter @Setter private URL url; private final BiConsumer consumer; + PasteHelper(BiConsumer consumer) { this.consumer = consumer; } @@ -128,5 +126,15 @@ public enum PasteHelper { } } + public URL getURL() { + return url; + } + public abstract URL paste(PlayerBalancer plugin) throws Exception; + + public static void reset() { + for (PasteHelper helper : values()) { + helper.url = null; + } + } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/ping/ServerStatus.java b/src/main/java/com/jaimemartz/playerbalancer/ping/ServerStatus.java index 8d95b43..acf98c9 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/ping/ServerStatus.java +++ b/src/main/java/com/jaimemartz/playerbalancer/ping/ServerStatus.java @@ -1,8 +1,10 @@ package com.jaimemartz.playerbalancer.ping; +import com.jaimemartz.playerbalancer.PlayerBalancer; import lombok.Getter; import lombok.Setter; import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; public final class ServerStatus { @Getter private final String description; @@ -23,19 +25,17 @@ public final class ServerStatus { this.maximum = maximum; } - //TODO improve this - public boolean isAccessible() { + //TODO improve this (set from the pinger if accessible or not) + public boolean isAccessible(PlayerBalancer plugin, ProxiedPlayer player) { if (maximum == 0) { return false; } - /* - for (String pattern : ConfigEntries.SERVER_CHECK_MARKER_DESCS.get()) { + for (String pattern : plugin.getSettings().getServerCheckerProps().getMarkerDescs()) { if (description.matches(pattern) || description.contains(pattern)) { return false; } } - */ return online < maximum; } diff --git a/src/main/java/com/jaimemartz/playerbalancer/ping/StatusManager.java b/src/main/java/com/jaimemartz/playerbalancer/ping/StatusManager.java index 1e0e82b..980d1e1 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/ping/StatusManager.java +++ b/src/main/java/com/jaimemartz/playerbalancer/ping/StatusManager.java @@ -1,43 +1,51 @@ package com.jaimemartz.playerbalancer.ping; +import com.jaimemartz.playerbalancer.PlayerBalancer; +import com.jaimemartz.playerbalancer.section.ServerSection; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.scheduler.ScheduledTask; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.TimeUnit; public class StatusManager { + private final PlayerBalancer plugin; private boolean stopped = true; private PingTactic tactic; private ScheduledTask task; private final Map storage = new HashMap<>(); - /* - public void start(PlayerBalancer plugin) { + public StatusManager(PlayerBalancer plugin) { + this.plugin = plugin; + } + + public void start() { if (task != null) { stop(); } stopped = false; - tactic = PingTactic.valueOf((ConfigEntries.SERVER_CHECK_MODE.get()).toUpperCase()); - plugin.getLogger().info(String.format("Starting the ping task, the interval is %s", ConfigEntries.SERVER_CHECK_INTERVAL.get())); + tactic = plugin.getSettings().getServerCheckerProps().getTactic(); + plugin.getLogger().info(String.format("Starting the ping task, the interval is %s", + plugin.getSettings().getServerCheckerProps().getInterval())); task = plugin.getProxy().getScheduler().schedule(plugin, () -> { storage.forEach((k, v) -> v.setOutdated(true)); for (ServerSection section : plugin.getSectionManager().getSections().values()) { - for (ServerInfo server : section.getServers()) { + for (ServerInfo server : section.getMappedServers()) { if (stopped) { break; } if (getStatus(server).isOutdated()) { - update(plugin, server); + update(server); } } } - }, 0L, ConfigEntries.SERVER_CHECK_INTERVAL.get(), TimeUnit.MILLISECONDS); + }, 0L, plugin.getSettings().getServerCheckerProps().getInterval(), TimeUnit.MILLISECONDS); } public void stop() { @@ -48,15 +56,15 @@ public class StatusManager { } } - private void update(PlayerBalancer plugin, ServerInfo server) { + private void update(ServerInfo server) { tactic.ping(server, (status, throwable) -> { if (status == null) { status = new ServerStatus(); } - if (ConfigEntries.SERVER_CHECK_PRINT_INFO.get()) { + if (plugin.getSettings().getServerCheckerProps().isDebug()) { plugin.getLogger().info(String.format("Updated server %s, status: [Description: \"%s\", Online Players: %s, Maximum Players: %s, Accessible: %s]", - server.getName(), status.getDescription(), status.getOnline(), status.getMaximum(), status.isAccessible() + server.getName(), status.getDescription(), status.getOnline(), status.getMaximum(), status.isAccessible(plugin, null) )); } @@ -74,5 +82,4 @@ public class StatusManager { return status; } } - */ } diff --git a/src/main/java/com/jaimemartz/playerbalancer/section/SectionCommand.java b/src/main/java/com/jaimemartz/playerbalancer/section/SectionCommand.java index 0afeb5d..50796dc 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/section/SectionCommand.java +++ b/src/main/java/com/jaimemartz/playerbalancer/section/SectionCommand.java @@ -1,53 +1,26 @@ package com.jaimemartz.playerbalancer.section; import com.jaimemartz.playerbalancer.PlayerBalancer; +import com.jaimemartz.playerbalancer.commands.FallbackCommand; +import com.jaimemartz.playerbalancer.settings.shared.CommandProps; import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.plugin.Command; +import net.md_5.bungee.api.connection.ProxiedPlayer; -import java.util.List; +public class SectionCommand extends FallbackCommand { + protected final ServerSection section; -public class SectionCommand extends Command { - private final PlayerBalancer plugin; - private final ServerSection section; - - public SectionCommand(PlayerBalancer plugin, String name, String permission, List aliases, ServerSection section) { - super(name, permission, aliases.toArray(new String[aliases.size()])); - this.plugin = plugin; + public SectionCommand(PlayerBalancer plugin, CommandProps props, ServerSection section) { + super(plugin, props); this.section = section; - plugin.getProxy().getPluginManager().registerCommand(plugin, this); } @Override public void execute(CommandSender sender, String[] args) { - /* - if (sender instanceof ProxiedPlayer) { - ProxiedPlayer player = (ProxiedPlayer) sender; - //todo share this code with the fallback command instead of having it duplicated - if (args.length == 1) { - try { - int number = Integer.parseInt(args[0]); - if (number <= 0) { - MessageUtils.send(sender, ConfigEntries.INVALID_INPUT_MESSAGE.get()); - } else if (number > section.getServers().size()) { - MessageUtils.send(sender, ConfigEntries.FAILURE_MESSAGE.get()); - } else { - ServerInfo server = section.getSortedServers().get(number - 1); - ConnectionIntent.direct(plugin, player, server, (response, throwable) -> {}); - } - } catch (NumberFormatException e) { - MessageUtils.send(sender, ConfigEntries.INVALID_INPUT_MESSAGE.get()); - } - } else { - ServerSection current = plugin.getSectionManager().getByPlayer(player); - if (current != section) { - ConnectionIntent.simple(plugin, player, section); - } else { - MessageUtils.send(player, ConfigEntries.SAME_SECTION.get()); - } - } - } else { - sender.sendMessage(new ComponentBuilder("This command can only be executed by a player").color(ChatColor.RED).create()); - } - */ + super.execute(sender, args); + } + + @Override + public ServerSection getSection(ProxiedPlayer player) { + return section; } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/section/SectionManager.java b/src/main/java/com/jaimemartz/playerbalancer/section/SectionManager.java index 2957026..3f74bc3 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/section/SectionManager.java +++ b/src/main/java/com/jaimemartz/playerbalancer/section/SectionManager.java @@ -1,12 +1,25 @@ package com.jaimemartz.playerbalancer.section; +import com.jaimemartz.playerbalancer.PlayerBalancer; +import net.md_5.bungee.api.config.ServerInfo; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.connection.Server; +import net.md_5.bungee.api.scheduler.ScheduledTask; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + public class SectionManager { - /* - private ScheduledTask updateTask; private final PlayerBalancer plugin; - @Getter @Setter private ServerSection principal; - @Getter private final Map sections = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - @Getter private final Map servers = new HashMap<>(); + private ScheduledTask updateTask; + private ServerSection principal; + + private final Map sections = new TreeMap<>( + String.CASE_INSENSITIVE_ORDER + ); + + private final Map servers = new HashMap<>(); public SectionManager(PlayerBalancer plugin) { this.plugin = plugin; @@ -16,13 +29,10 @@ public class SectionManager { plugin.getLogger().info("Loading sections from the config, this may take a while..."); long starting = System.currentTimeMillis(); - Configuration sections = plugin.getConfigHandle().getSection("sections"); - - sections.getKeys().forEach(name -> { + plugin.getSettings().getSections().forEach((name, prop) -> { plugin.getLogger().info(String.format("Construction of section with name \"%s\"", name)); - Configuration section = sections.getSection(name); - ServerSection object = new ServerSection(plugin, name, section); - this.sections.put(name, object); + ServerSection object = new ServerSection(name, prop); + sections.put(name, object); }); this.sections.forEach((name, section) -> { @@ -40,6 +50,7 @@ public class SectionManager { section.postInit(); }); + /* //todo unify loading code with SectionManager if (ConfigEntries.SERVERS_UPDATE.get()) { updateTask = plugin.getProxy().getScheduler().schedule(plugin, () -> { @@ -60,6 +71,7 @@ public class SectionManager { }); }, 1, 1, TimeUnit.MINUTES); } + */ long ending = System.currentTimeMillis() - starting; plugin.getLogger().info(String.format("A total of %s section(s) have been loaded in %sms", this.sections.size(), ending)); @@ -92,7 +104,7 @@ public class SectionManager { public void register(ServerInfo server, ServerSection section) { if (servers.containsKey(server)) { - if (section.isDummy()) { + if (section.getProps().isDummy()) { return; } @@ -134,5 +146,49 @@ public class SectionManager { return getByServer(server.getInfo()); } - */ + + public ServerSection getPrincipal() { + return principal; + } + + /** + * Calculates the position of a section in relation to other sections + * This is supposed to be called on section construction + * @param section the section we want to get the position of + * @param principal the principal section + * @return the position of {@param section} + */ + private int calculatePosition(ServerSection section, ServerSection principal) { + //Calculate above principal + int iterations = 0; + ServerSection current = section; + while (current != null) { + if (current.getProps().isPrincipal()) { + return iterations; + } + + current = current.getParent(); + iterations++; + } + + //Calculate below principal + if (principal != null) { + iterations = 0; + current = principal; + while (current != null) { + if (current.equals(section)) { + return iterations; + } + + current = current.getParent(); + iterations--; + } + } + + return iterations; + } + + public Map getSections() { + return sections; + } } diff --git a/src/main/java/com/jaimemartz/playerbalancer/section/ServerSection.java b/src/main/java/com/jaimemartz/playerbalancer/section/ServerSection.java index f8483e0..5e6b88d 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/section/ServerSection.java +++ b/src/main/java/com/jaimemartz/playerbalancer/section/ServerSection.java @@ -1,53 +1,35 @@ package com.jaimemartz.playerbalancer.section; -import lombok.Getter; -import lombok.Setter; +import com.jaimemartz.playerbalancer.connection.ProviderType; +import com.jaimemartz.playerbalancer.settings.shared.SectionProps; +import net.md_5.bungee.api.config.ServerInfo; + +import java.util.List; -@Getter -@Setter public class ServerSection { - /* - @Getter(AccessLevel.NONE) - private final PlayerBalancer plugin; + private final String name; + private int position; - private Configuration configuration; + private final SectionProps props; + + private boolean inherited = false; + private ServerSection parent; + + private ServerInfo server; + private SectionCommand command; + + private List mappedServers; private List sortedServers; - @Expose private final String name; - @Expose private boolean principal; - @Expose private int position; - @Expose private boolean dummy; - @Expose private ServerSection parent; - @Expose private boolean inherited = false; - @Expose private List servers; - @Expose private ProviderType provider; - @Expose private ServerInfo server; - @Expose private SectionCommand command; - @Expose private boolean valid = false; //todo delete this, not necessary - public ServerSection(PlayerBalancer plugin, String name, Configuration configuration) { - this.plugin = plugin; - this.name = name; - this.configuration = configuration; - this.servers = new ArrayList<>(); - } + private boolean valid = false; - public ServerSection(PlayerBalancer plugin, String name, boolean principal, int position, boolean dummy, ServerSection parent, boolean inherited, List servers, ProviderType provider, ServerInfo server, SectionCommand command, boolean valid) { - this.plugin = plugin; - this.configuration = null; + public ServerSection(String name, SectionProps props) { this.name = name; - this.principal = principal; - this.position = position; - this.dummy = dummy; - this.parent = parent; - this.inherited = inherited; - this.servers = servers; - this.provider = provider; - this.server = server; - this.command = command; - this.valid = valid; + this.props = props; } public void preInit() { + /* checkInit(); if (configuration == null) { @@ -98,12 +80,11 @@ public class ServerSection { } else { throw new IllegalArgumentException(String.format("The section \"%s\" does not have any servers set", name)); } - + */ } public void load() { - checkInit(); - + /* if (configuration == null) { throw new IllegalStateException("Tried to call an init method with null configuration section"); } @@ -123,49 +104,17 @@ public class ServerSection { throw new IllegalArgumentException(String.format("The principal section \"%s\" does not have a provider set", name)); } } + */ } public void postInit() { - checkInit(); - + /* if (configuration == null) { throw new IllegalStateException("Tried to call an init method with null configuration section"); } - Callable callable = () -> { - //Calculate above principal - int iterations = 0; - ServerSection current = this; - while (current != null) { - if (current.isPrincipal()) { - return iterations; - } - - current = current.getParent(); - iterations++; - } - - //Calculate below principal - ServerSection principal = plugin.getSectionManager().getPrincipal(); - if (principal != null) { - iterations = 0; - current = principal; - while (current != null) { - if (current.equals(this)) { - return iterations; - } - - current = current.getParent(); - iterations--; - } - } - - //Calculated iterations above parents - return iterations; - }; - try { - position = callable.call(); + position = calculatePosition(); } catch (Exception e) { e.printStackTrace(); } @@ -211,11 +160,87 @@ public class ServerSection { sortedServers.sort(new AlphanumComparator()); valid = true; + */ } - private void checkInit() { - if (!valid) return; - throw new IllegalStateException("Tried to init a section that is already valid"); + public String getName() { + return name; + } + + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + public SectionProps getProps() { + return props; + } + + public boolean isInherited() { + return inherited; + } + + public void setInherited(boolean inherited) { + this.inherited = inherited; + } + + public ServerSection getParent() { + return parent; + } + + public void setParent(ServerSection parent) { + this.parent = parent; + } + + public ProviderType getEffectiveProvider() { + return inherited ? parent.getEffectiveProvider() : props.getProvider(); + } + + public void setProvider(ProviderType provider) { + props.setProvider(provider); + inherited = false; + } + + public ServerInfo getServer() { + return server; + } + + public void setServer(ServerInfo server) { + this.server = server; + } + + public SectionCommand getCommand() { + return command; + } + + public void setCommand(SectionCommand command) { + this.command = command; + } + + public List getMappedServers() { + return mappedServers; + } + + public void setMappedServers(List mappedServers) { + this.mappedServers = mappedServers; + } + + public List getSortedServers() { + return sortedServers; + } + + public void setSortedServers(List sortedServers) { + this.sortedServers = sortedServers; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; } - */ } \ No newline at end of file diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/MainSettings.java b/src/main/java/com/jaimemartz/playerbalancer/settings/MainSettings.java new file mode 100644 index 0000000..bcf67a3 --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/MainSettings.java @@ -0,0 +1,110 @@ +package com.jaimemartz.playerbalancer.settings; + +import com.jaimemartz.playerbalancer.settings.props.*; +import com.jaimemartz.playerbalancer.settings.shared.SectionProps; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.HashMap; +import java.util.Map; + +@ConfigSerializable +public class MainSettings { + @Setting(value = "general") + private GeneralProps generalProps; + + @Setting(value = "server-checker") + private ServerCheckerProps serverCheckerProps; + + @Setting(value = "kick-handler") + private KickHandlerProps kickHandlerProps; + + @Setting(value = "fallback-command") + private FallbackCommandProps fallbackCommandProps; + + @Setting(value = "messages", comment = "Effectively remove (i.e comment) a message to disable it") + private MessagesProps messagesProps; + + @Setting + private Map sections; + + public MainSettings _defaults() { + this.generalProps = new GeneralProps()._defaults(); + this.serverCheckerProps = new ServerCheckerProps()._defaults(); + this.kickHandlerProps = new KickHandlerProps()._defaults(); + this.fallbackCommandProps = new FallbackCommandProps()._defaults(); + this.messagesProps = new MessagesProps()._defaults(); + this.sections = new HashMap<>(); + + SectionProps prop1 = new SectionProps(); + prop1.setDummy(true); + prop1.setPrincipal(true); + sections.put("test", prop1); + + SectionProps prop2 = new SectionProps(); + prop2.setDummy(false); + prop2.setPrincipal(false); + sections.put("other", prop2); + return this; + } + + public GeneralProps getGeneralProps() { + return generalProps; + } + + public void setGeneralProps(GeneralProps generalProps) { + this.generalProps = generalProps; + } + + public ServerCheckerProps getServerCheckerProps() { + return serverCheckerProps; + } + + public void setServerCheckerProps(ServerCheckerProps serverCheckerProps) { + this.serverCheckerProps = serverCheckerProps; + } + + public KickHandlerProps getKickHandlerProps() { + return kickHandlerProps; + } + + public void setKickHandlerProps(KickHandlerProps kickHandlerProps) { + this.kickHandlerProps = kickHandlerProps; + } + + public FallbackCommandProps getFallbackCommandProps() { + return fallbackCommandProps; + } + + public void setFallbackCommandProps(FallbackCommandProps fallbackCommandProps) { + this.fallbackCommandProps = fallbackCommandProps; + } + + public MessagesProps getMessagesProps() { + return messagesProps; + } + + public void setMessagesProps(MessagesProps messagesProps) { + this.messagesProps = messagesProps; + } + + public Map getSections() { + return sections; + } + + public void setSections(Map sections) { + this.sections = sections; + } + + @Override + public String toString() { + return "MainSettings{" + + "generalProps=" + generalProps + + ", serverCheckerProps=" + serverCheckerProps + + ", kickHandlerProps=" + kickHandlerProps + + ", fallbackCommandProps=" + fallbackCommandProps + + ", messagesProps=" + messagesProps + + ", sections=" + sections + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/Settings.java b/src/main/java/com/jaimemartz/playerbalancer/settings/Settings.java deleted file mode 100644 index 246e7fc..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/Settings.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jaimemartz.playerbalancer.settings; - -import ch.jalu.configme.SettingsManager; -import ch.jalu.configme.configurationdata.ConfigurationData; -import ch.jalu.configme.migration.MigrationService; -import ch.jalu.configme.resource.PropertyResource; - -public class Settings extends SettingsManager { - public Settings(PropertyResource resource, MigrationService migrationService, ConfigurationData configurationData) { - super(resource, migrationService, configurationData); - } -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/SettingsProvider.java b/src/main/java/com/jaimemartz/playerbalancer/settings/SettingsProvider.java deleted file mode 100644 index 1d70679..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/SettingsProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jaimemartz.playerbalancer.settings; - -import ch.jalu.configme.configurationdata.ConfigurationData; -import ch.jalu.configme.configurationdata.ConfigurationDataBuilder; -import ch.jalu.configme.migration.PlainMigrationService; -import ch.jalu.configme.resource.PropertyResource; -import ch.jalu.configme.resource.YamlFileResource; -import com.jaimemartz.playerbalancer.PlayerBalancer; -import com.jaimemartz.playerbalancer.settings.types.*; - -import javax.inject.Inject; -import javax.inject.Provider; -import java.io.File; -import java.io.IOException; - -public class SettingsProvider implements Provider { - @Inject - private PlayerBalancer plugin; - - @Override - public Settings get() { - plugin.getDataFolder().mkdir(); - - File configFile = new File(plugin.getDataFolder(), "config.yml"); - if (!configFile.exists()) { - try { - boolean result = configFile.createNewFile(); - if (!result) { - throw new IllegalStateException("Could not create a new file"); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - PropertyResource resource = new YamlFileResource(configFile); - ConfigurationData configurationData = ConfigurationDataBuilder.collectData( - GeneralProperties.class, CheckerProperties.class, ReconnectorProperties.class, - CommandProperties.class, MessageProperties.class, SectionsHolder.class - ); - - return new Settings(resource, new PlainMigrationService(), configurationData); - } -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/beans/CommandData.java b/src/main/java/com/jaimemartz/playerbalancer/settings/beans/CommandData.java deleted file mode 100644 index b37ab38..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/beans/CommandData.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.beans; - -public final class CommandData { - private String name; - private String permission; - private String[] aliases; - - public CommandData() { - - } - - public CommandData(String name, String permission, String... aliases) { - this.name = name; - this.permission = permission; - this.aliases = aliases; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPermission() { - return permission; - } - - public void setPermission(String permission) { - this.permission = permission; - } - - public String[] getAliases() { - return aliases; - } - - public void setAliases(String[] aliases) { - this.aliases = aliases; - } -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/beans/SectionData.java b/src/main/java/com/jaimemartz/playerbalancer/settings/beans/SectionData.java deleted file mode 100644 index b55ed1b..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/beans/SectionData.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.beans; - -import com.jaimemartz.playerbalancer.connection.ProviderType; - -import java.util.List; - -public class SectionData { - private Boolean principal = true; - private Boolean dummy; - private String parent; - private List servers; - private ProviderType provider; - private CommandData command; - private String server; - - public Boolean isPrincipal() { - return principal; - } - - public void setPrincipal(boolean principal) { - this.principal = principal; - } - - public Boolean isDummy() { - return dummy; - } - - public void setDummy(boolean dummy) { - this.dummy = dummy; - } - - public String getParent() { - return parent; - } - - public void setParent(String parent) { - this.parent = parent; - } - - public List getServers() { - return servers; - } - - public void setServers(List servers) { - this.servers = servers; - } - - public ProviderType getProvider() { - return provider; - } - - public void setProvider(ProviderType provider) { - this.provider = provider; - } - - public CommandData getCommand() { - return command; - } - - public void setCommand(CommandData command) { - this.command = command; - } - - public String getServer() { - return server; - } - - public void setServer(String server) { - this.server = server; - } -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/props/FallbackCommandProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/props/FallbackCommandProps.java new file mode 100644 index 0000000..ef959cb --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/props/FallbackCommandProps.java @@ -0,0 +1,92 @@ +package com.jaimemartz.playerbalancer.settings.props; + +import com.google.common.collect.ImmutableMap; +import com.jaimemartz.playerbalancer.settings.shared.CommandProps; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@ConfigSerializable +public class FallbackCommandProps { + @Setting + private boolean active; + + @Setting + private CommandProps command; + + @Setting("excluded-sections") + private List excludedSections; + + @Setting + private boolean restrictive; + + @Setting + private Map rules; + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public CommandProps getCommand() { + return command; + } + + public void setCommand(CommandProps command) { + this.command = command; + } + + public List getExcludedSections() { + return excludedSections; + } + + public void setExcludedSections(List excludedSections) { + this.excludedSections = excludedSections; + } + + public boolean isRestrictive() { + return restrictive; + } + + public void setRestrictive(boolean restrictive) { + this.restrictive = restrictive; + } + + public Map getRules() { + return rules; + } + + public void setRules(Map rules) { + this.rules = rules; + } + + public FallbackCommandProps _defaults() { + this.active = true; + this.command = new CommandProps(); + command.setName("fallback"); + command.setPermission(""); + command.setAliases(Arrays.asList("lobby", "hub", "back")); + this.excludedSections = Collections.emptyList(); + this.restrictive = true; + this.rules = ImmutableMap.of("section-from", "section-to"); + return this; + } + + @Override + public String toString() { + return "FallbackCommandProps{" + + "active=" + active + + ", command=" + command + + ", excludedSections=" + excludedSections + + ", restrictive=" + restrictive + + ", rules=" + rules + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/props/GeneralProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/props/GeneralProps.java new file mode 100644 index 0000000..3e2ed38 --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/props/GeneralProps.java @@ -0,0 +1,108 @@ +package com.jaimemartz.playerbalancer.settings.props; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +@ConfigSerializable +public class GeneralProps { + @Setting + private boolean active; + + @Setting + private boolean silent; + + @Setting(value = "auto-reload") + private boolean autoReload; + + @Setting(value = "redis-bungee") + private boolean redisBungee; + + @Setting(value = "assign-targets") + private boolean assignTargets; + + @Setting(value = "fallback-principal") + private boolean fallbackPrincipal; + + @Setting(value = "auto-refresh") + private boolean autoRefresh; + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public boolean isSilent() { + return silent; + } + + public void setSilent(boolean silent) { + this.silent = silent; + } + + public boolean isAutoReload() { + return autoReload; + } + + public void setAutoReload(boolean autoReload) { + this.autoReload = autoReload; + } + + public boolean isRedisBungee() { + return redisBungee; + } + + public void setRedisBungee(boolean redisBungee) { + this.redisBungee = redisBungee; + } + + public boolean isAssignTargets() { + return assignTargets; + } + + public void setAssignTargets(boolean assignTargets) { + this.assignTargets = assignTargets; + } + + public boolean isFallbackPrincipal() { + return fallbackPrincipal; + } + + public void setFallbackPrincipal(boolean fallbackPrincipal) { + this.fallbackPrincipal = fallbackPrincipal; + } + + public boolean isAutoRefresh() { + return autoRefresh; + } + + public void setAutoRefresh(boolean autoRefresh) { + this.autoRefresh = autoRefresh; + } + + public GeneralProps _defaults() { + this.active = false; + this.silent = false; + this.autoReload = true; + this.redisBungee = false; + this.assignTargets = false; + this.fallbackPrincipal = true; + this.autoRefresh = false; + return this; + } + + @Override + public String toString() { + return "GeneralProps{" + + "active=" + active + + ", silent=" + silent + + ", autoReload=" + autoReload + + ", redisBungee=" + redisBungee + + ", assignTargets=" + assignTargets + + ", fallbackPrincipal=" + fallbackPrincipal + + ", autoRefresh=" + autoRefresh + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/props/KickHandlerProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/props/KickHandlerProps.java new file mode 100644 index 0000000..a2fbce8 --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/props/KickHandlerProps.java @@ -0,0 +1,127 @@ +package com.jaimemartz.playerbalancer.settings.props; + +import com.google.common.collect.ImmutableMap; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@ConfigSerializable +public class KickHandlerProps { + @Setting + private boolean active; + + @Setting + private boolean inverted; + + @Setting + private List reasons; + + @Setting(value = "excluded-sections") + private List excludedSections; + + @Setting + private boolean restricted; + + @Setting(value = "force-principal") + private boolean forcePrincipal; + + @Setting + private Map rules; + + @Setting(value = "debug-info") + private boolean debug; + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public boolean isInverted() { + return inverted; + } + + public void setInverted(boolean inverted) { + this.inverted = inverted; + } + + public List getReasons() { + return reasons; + } + + public void setReasons(List reasons) { + this.reasons = reasons; + } + + public List getExcludedSections() { + return excludedSections; + } + + public void setExcludedSections(List excludedSections) { + this.excludedSections = excludedSections; + } + + public boolean isRestricted() { + return restricted; + } + + public void setRestricted(boolean restricted) { + this.restricted = restricted; + } + + public boolean isForcePrincipal() { + return forcePrincipal; + } + + public void setForcePrincipal(boolean forcePrincipal) { + this.forcePrincipal = forcePrincipal; + } + + public Map getRules() { + return rules; + } + + public void setRules(Map rules) { + this.rules = rules; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public KickHandlerProps _defaults() { + this.active = true; + this.inverted = true; + this.reasons = Arrays.asList("Banned", "Hacks"); + this.excludedSections = Collections.emptyList(); + this.restricted = true; + this.forcePrincipal = false; //maybe stop using this + this.rules = ImmutableMap.of("section-from", "section-to"); + this.debug = false; + return this; + } + + @Override + public String toString() { + return "KickHandlerProps{" + + "active=" + active + + ", inverted=" + inverted + + ", reasons=" + reasons + + ", excludedSections=" + excludedSections + + ", restricted=" + restricted + + ", forcePrincipal=" + forcePrincipal + + ", rules=" + rules + + ", debug=" + debug + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/props/MessagesProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/props/MessagesProps.java new file mode 100644 index 0000000..891300c --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/props/MessagesProps.java @@ -0,0 +1,134 @@ +package com.jaimemartz.playerbalancer.settings.props; + +import ninja.leaping.configurate.objectmapping.Setting; + +import java.util.Optional; + +public class MessagesProps { + @Setting("connecting-server") + private String connectingMessage; + + @Setting("connected-server") + private String connectedMessage; + + @Setting("misc-failure") + private String failureMessage; + + @Setting("unknown-section") + private String unknownSectionMessage; + + @Setting("invalid-input") + private String invalidInputMessage; + + @Setting("unavailable-server") + private String unavailableServerMessage; + + @Setting("player-kicked") + private String kickMessage; + + @Setting("player-bypass") + private String bypassMessage; + + @Setting("same-section") + private String sameSectionMessage; + + public MessagesProps _defaults() { + connectingMessage = "&aConnecting to a {section} server"; + connectedMessage = "&aConnected to {server}"; + failureMessage = "&cCould not find a server to get connected to"; + unknownSectionMessage = "&aCould not find a section with that name"; + invalidInputMessage = "&cThis is an invalid input type for this command"; + unavailableServerMessage = "&cThis command cannot be executed on this server"; + kickMessage = "&cYou have been kicked from &a{from} &cand you are being moved to &a{to}, reason: &a{reason}"; + bypassMessage = "&cYou have not been moved because you have the playerbalancer.bypass permission"; + sameSectionMessage = "&cYou are already connected to a server on this section!"; + return this; + } + + public Optional getConnectingMessage() { + return Optional.ofNullable(connectingMessage); + } + + public void setConnectingMessage(String connectingMessage) { + this.connectingMessage = connectingMessage; + } + + public Optional getConnectedMessage() { + return Optional.ofNullable(connectedMessage); + } + + public void setConnectedMessage(String connectedMessage) { + this.connectedMessage = connectedMessage; + } + + public Optional getFailureMessage() { + return Optional.ofNullable(failureMessage); + } + + public void setFailureMessage(String failureMessage) { + this.failureMessage = failureMessage; + } + + public Optional getUnknownSectionMessage() { + return Optional.ofNullable(unknownSectionMessage); + } + + public void setUnknownSectionMessage(String unknownSectionMessage) { + this.unknownSectionMessage = unknownSectionMessage; + } + + public Optional getInvalidInputMessage() { + return Optional.ofNullable(invalidInputMessage); + } + + public void setInvalidInputMessage(String invalidInputMessage) { + this.invalidInputMessage = invalidInputMessage; + } + + public Optional getUnavailableServerMessage() { + return Optional.ofNullable(unavailableServerMessage); + } + + public void setUnavailableServerMessage(String unavailableServerMessage) { + this.unavailableServerMessage = unavailableServerMessage; + } + + public Optional getKickMessage() { + return Optional.ofNullable(kickMessage); + } + + public void setKickMessage(String kickMessage) { + this.kickMessage = kickMessage; + } + + public Optional getBypassMessage() { + return Optional.ofNullable(bypassMessage); + } + + public void setBypassMessage(String bypassMessage) { + this.bypassMessage = bypassMessage; + } + + public Optional getSameSectionMessage() { + return Optional.ofNullable(sameSectionMessage); + } + + public void setSameSectionMessage(String sameSectionMessage) { + this.sameSectionMessage = sameSectionMessage; + } + + @Override + public String toString() { + return "MessagesProps{" + + "connectingMessage=" + connectingMessage + + ", connectedMessage=" + connectedMessage + + ", failureMessage=" + failureMessage + + ", unknownSectionMessage=" + unknownSectionMessage + + ", invalidInputMessage=" + invalidInputMessage + + ", unavailableServerMessage=" + unavailableServerMessage + + ", kickMessage=" + kickMessage + + ", bypassMessage=" + bypassMessage + + ", sameSectionMessage=" + sameSectionMessage + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/props/ServerCheckerProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/props/ServerCheckerProps.java new file mode 100644 index 0000000..26d4886 --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/props/ServerCheckerProps.java @@ -0,0 +1,99 @@ +package com.jaimemartz.playerbalancer.settings.props; + +import com.jaimemartz.playerbalancer.ping.PingTactic; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.Arrays; +import java.util.List; + +@ConfigSerializable +public class ServerCheckerProps { + @Setting + private boolean active; + + @Setting + private PingTactic tactic; + + @Setting + private int attempts; + + @Setting + private int interval; + + @Setting("marker-descs") + private List markerDescs; + + @Setting(value = "debug-info") + private boolean debug; + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public PingTactic getTactic() { + return tactic; + } + + public void setTactic(PingTactic tactic) { + this.tactic = tactic; + } + + public int getAttempts() { + return attempts; + } + + public void setAttempts(int attempts) { + this.attempts = attempts; + } + + public int getInterval() { + return interval; + } + + public void setInterval(int interval) { + this.interval = interval; + } + + public List getMarkerDescs() { + return markerDescs; + } + + public void setMarkerDescs(List markerDescs) { + this.markerDescs = markerDescs; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public ServerCheckerProps _defaults() { + this.active = true; + this.tactic = PingTactic.CUSTOM; + this.attempts = 5; + this.interval = 10000; + this.markerDescs = Arrays.asList("Server is not accessible", "Gamemode has already started"); + this.debug = false; + return this; + } + + @Override + public String toString() { + return "ServerCheckerProps{" + + "active=" + active + + ", tactic=" + tactic + + ", attempts=" + attempts + + ", interval=" + interval + + ", markerDescs=" + markerDescs + + ", debug=" + debug + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/serializers/SectionSerializer.java b/src/main/java/com/jaimemartz/playerbalancer/settings/serializers/SectionSerializer.java new file mode 100644 index 0000000..92bd45b --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/serializers/SectionSerializer.java @@ -0,0 +1,19 @@ +package com.jaimemartz.playerbalancer.settings.serializers; + +import com.google.common.reflect.TypeToken; +import com.jaimemartz.playerbalancer.section.ServerSection; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; + +public class SectionSerializer implements TypeSerializer { + @Override + public ServerSection deserialize(TypeToken typeToken, ConfigurationNode configurationNode) throws ObjectMappingException { + return null; + } + + @Override + public void serialize(TypeToken typeToken, ServerSection section, ConfigurationNode configurationNode) throws ObjectMappingException { + + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/shared/CommandProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/shared/CommandProps.java new file mode 100644 index 0000000..2b2e5a0 --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/shared/CommandProps.java @@ -0,0 +1,46 @@ +package com.jaimemartz.playerbalancer.settings.shared; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.List; + +@ConfigSerializable +public class CommandProps { + @Setting + private String name; + + @Setting + private String permission; + + @Setting + private List aliases; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPermission() { + return permission; + } + + public void setPermission(String permission) { + this.permission = permission; + } + + public List getAliases() { + return aliases; + } + + public String[] getAliasesArray() { + return aliases.toArray(new String[aliases.size()]); + } + + public void setAliases(List aliases) { + this.aliases = aliases; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/shared/SectionProps.java b/src/main/java/com/jaimemartz/playerbalancer/settings/shared/SectionProps.java new file mode 100644 index 0000000..9b454ea --- /dev/null +++ b/src/main/java/com/jaimemartz/playerbalancer/settings/shared/SectionProps.java @@ -0,0 +1,100 @@ +package com.jaimemartz.playerbalancer.settings.shared; + +import com.jaimemartz.playerbalancer.connection.ProviderType; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.List; + +@ConfigSerializable +public class SectionProps { + @Setting + private boolean principal; //move this to other place + + @Setting + private boolean dummy; //move this to other place + + @Setting + private ProviderType provider; + + @Setting("parent") + private String parentName; + + @Setting("servers") + private List serverEntries; + + @Setting + private CommandProps command; + + @Setting("server") + private String serverName; + + public boolean isPrincipal() { + return principal; + } + + public void setPrincipal(boolean principal) { + this.principal = principal; + } + + public boolean isDummy() { + return dummy; + } + + public void setDummy(boolean dummy) { + this.dummy = dummy; + } + + public ProviderType getProvider() { + return provider; + } + + public void setProvider(ProviderType provider) { + this.provider = provider; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public List getServerEntries() { + return serverEntries; + } + + public void setServerEntries(List serverEntries) { + this.serverEntries = serverEntries; + } + + public CommandProps getCommand() { + return command; + } + + public void setCommand(CommandProps command) { + this.command = command; + } + + public String getServerName() { + return serverName; + } + + public void setServerName(String serverName) { + this.serverName = serverName; + } + + @Override + public String toString() { + return "SectionProps{" + + "principal=" + principal + + ", dummy=" + dummy + + ", provider=" + provider + + ", parentName='" + parentName + '\'' + + ", serverEntries=" + serverEntries + + ", command=" + command + + ", serverName='" + serverName + '\'' + + '}'; + } +} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/CheckerProperties.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/CheckerProperties.java deleted file mode 100644 index 75f57b0..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/CheckerProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; -import com.jaimemartz.playerbalancer.ping.PingTactic; - -import java.util.List; - -import static ch.jalu.configme.properties.PropertyInitializer.newListProperty; -import static ch.jalu.configme.properties.PropertyInitializer.newProperty; - -public class CheckerProperties implements SettingsHolder { - public static final Property ENABLED = newProperty("settings.server-check.enabled", true); - - public static final Property TACTIC = newProperty(PingTactic.class, "settings.server-check.tactic", PingTactic.CUSTOM); - - public static final Property ATTEMPTS = newProperty("settings.server-check.attempts", 5); - - public static final Property INTERVAL = newProperty("settings.server-check.interval", 10000); - - public static final Property> MARKER_DESCS = newListProperty("settings.server-check.marker-descs", - "Sever is not accessible", - "Gamemode has already started" - ); - - public static final Property DEBUG = newProperty("settings.server-check.debug", false); -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/CommandProperties.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/CommandProperties.java deleted file mode 100644 index 37da1ed..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/CommandProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; -import com.google.common.collect.ImmutableMap; -import com.jaimemartz.playerbalancer.settings.beans.CommandData; - -import java.util.List; -import java.util.Map; - -import static ch.jalu.configme.properties.PropertyInitializer.*; - -public class CommandProperties implements SettingsHolder { - public static final Property ENABLED = newProperty("settings.fallback-command.enabled", true); - - public static final Property COMMAND = newBeanProperty(CommandData.class, "settings.fallback-command.command", - new CommandData("fallback", "", "lobby", "hub", "back") - ); - - public static final Property> IGNORED_SECTIONS = newListProperty("settings.fallback-command.ignored"); - - public static final Property RESTRICTED = newProperty("settings.fallback-command.restricted", true); - - public static final Property> RULES = newStringKeyMapProperty(String.class, "settings.fallback-command.rules", - ImmutableMap.of("section-from", "section-to") - ); -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/GeneralProperties.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/GeneralProperties.java deleted file mode 100644 index d9f4bed..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/GeneralProperties.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; - -import static ch.jalu.configme.properties.PropertyInitializer.newProperty; - -public class GeneralProperties implements SettingsHolder { - public static final Property ENABLED = newProperty("settings.enabled", false); - - public static final Property SILENT = newProperty("settings.silent", false); - - public static final Property AUTO_RELOAD = newProperty("settings.auto-reload", true); - - public static final Property REDIS_BUNGEE = newProperty("settings.redis-bungee", false); - - public static final Property ASSIGN_TARGETS = newProperty("settings.assign-targets", true); - - public static final Property FALLBACK_PRINCIPAL = newProperty("settings.fallback-principal", true); - - public static final Property AUTO_UPDATE = newProperty("settings.auto-update", false); -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/MessageProperties.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/MessageProperties.java deleted file mode 100644 index f79701b..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/MessageProperties.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; - -import java.util.Optional; - -import static ch.jalu.configme.properties.PropertyInitializer.optionalStringProperty; - -public class MessageProperties implements SettingsHolder { - public static final Property> CONNECTING_SERVER = optionalStringProperty("settings.messages.connecting-server"); - - public static final Property> CONNECTED_SERVER = optionalStringProperty("settings.messages.connected-server"); - - public static final Property> MISC_FAILURE = optionalStringProperty("settings.messages.misc-failure"); - - public static final Property> UNKNOWN_SECTION = optionalStringProperty("settings.messages.unknown-section"); - - public static final Property> INVALID_INPUT = optionalStringProperty("settings.messages.invalid-input"); - - public static final Property> UNAVAILABLE_SERVER = optionalStringProperty("settings.messages.unavailable-server"); - - public static final Property> PLAYER_KICKED = optionalStringProperty("settings.messages.player-kicked"); - - public static final Property> PLAYER_BYPASS = optionalStringProperty("settings.messages.player-bypass"); - - public static final Property> SAME_SECTION = optionalStringProperty("settings.messages.same-section"); -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/ReconnectorProperties.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/ReconnectorProperties.java deleted file mode 100644 index d54aaa4..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/ReconnectorProperties.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static ch.jalu.configme.properties.PropertyInitializer.*; - -public class ReconnectorProperties implements SettingsHolder { - public static final Property ENABLED = newProperty("settings.reconnect-kick.enabled", true); - - public static final Property INVERTED = newProperty("settings.reconnect-kick.inverted", false); - - public static final Property> REASONS = newListProperty("settings.reconnect-kick.reasons"); - - public static final Property> IGNORED_SECTIONS = newListProperty("settings.reconnect-kick.ignored"); - - public static final Property RESTRICTED = newProperty("settings.reconnect-kick.restricted", true); - - public static final Property FORCE_PRINCIPAL = newProperty("settings.reconnect-kick.force-principal", false); - - public static final Property> RULES = newStringKeyMapProperty(String.class, "settings.reconnect-kick.rules", - Collections.emptyMap()//ImmutableMap.of("section-from", "section-to") - ); - - public static final Property DEBUG = newProperty("settings.reconnect-kick.debug", false); -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/settings/types/SectionsHolder.java b/src/main/java/com/jaimemartz/playerbalancer/settings/types/SectionsHolder.java deleted file mode 100644 index 29cfb83..0000000 --- a/src/main/java/com/jaimemartz/playerbalancer/settings/types/SectionsHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jaimemartz.playerbalancer.settings.types; - -import ch.jalu.configme.SettingsHolder; -import ch.jalu.configme.properties.Property; -import com.jaimemartz.playerbalancer.connection.ProviderType; -import com.jaimemartz.playerbalancer.settings.beans.CommandData; -import com.jaimemartz.playerbalancer.settings.beans.SectionData; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static ch.jalu.configme.properties.PropertyInitializer.newStringKeyMapProperty; - -public class SectionsHolder implements SettingsHolder { - public static final Property> SECTIONS = newStringKeyMapProperty(SectionData.class, "sections", getDefaultSections()); - - public static Map getDefaultSections() { - Map map = new HashMap<>(); - - SectionData authLobbies = new SectionData(); - authLobbies.setProvider(ProviderType.RANDOM); - authLobbies.setServers(Arrays.asList("Auth1", "Auth2", "Auth3")); - map.put("auth-lobbies", authLobbies); - - SectionData generalLobbies = new SectionData(); - generalLobbies.setParent("auth-lobbies"); - generalLobbies.setPrincipal(true); - generalLobbies.setProvider(ProviderType.RANDOM); - generalLobbies.setServers(Arrays.asList("SWLobby1", "SWLobby2", "SWLobby3")); - map.put("general-lobbies", generalLobbies); - - SectionData skywarsLobbies = new SectionData(); - skywarsLobbies.setParent("general-lobbies"); - skywarsLobbies.setProvider(ProviderType.LOWEST); - skywarsLobbies.setServers(Arrays.asList("SWLobby1", "SWLobby2", "SWLobby3")); - map.put("skywars-lobbies", skywarsLobbies); - - SectionData skywarsGames = new SectionData(); - skywarsGames.setProvider(ProviderType.FILLER); - skywarsGames.setParent("skywarsd-lobbies"); - skywarsGames.setServers(Arrays.asList("SW_1", "SW2", "SW3", "SW4", "SW5")); - skywarsGames.setCommand(new CommandData("playskywars", "", "skywars")); - skywarsGames.setServer("skywars"); - skywarsGames.setDummy(true); - map.put("skywars-games", skywarsGames); - - return map; - } -} diff --git a/src/main/java/com/jaimemartz/playerbalancer/utils/GuestPaste.java b/src/main/java/com/jaimemartz/playerbalancer/utils/GuestPaste.java index fa8467a..09a0c24 100644 --- a/src/main/java/com/jaimemartz/playerbalancer/utils/GuestPaste.java +++ b/src/main/java/com/jaimemartz/playerbalancer/utils/GuestPaste.java @@ -1,8 +1,5 @@ package com.jaimemartz.playerbalancer.utils; -import lombok.Data; -import lombok.Getter; - import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.DataOutputStream; @@ -14,7 +11,6 @@ import java.util.AbstractMap.SimpleEntry; import java.util.LinkedList; import java.util.List; -@Data public final class GuestPaste { private final String key; private final String code; @@ -105,11 +101,14 @@ public final class GuestPaste { SIX_MONTHS("6M"), ONE_YEAR("1Y"); - @Getter private final String value; Expiration(String value) { this.value = value; } + + public String getValue() { + return value; + } } public enum Exposure { @@ -117,11 +116,14 @@ public final class GuestPaste { UNLISTED(1), PRIVATE(2); - @Getter private final int value; Exposure(int value) { this.value = value; } + + public int getValue() { + return value; + } } public class PasteException extends Exception { @@ -129,4 +131,44 @@ public final class GuestPaste { super(response); } } + + public String getKey() { + return key; + } + + public String getCode() { + return code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public Expiration getExpiration() { + return expiration; + } + + public void setExpiration(Expiration expiration) { + this.expiration = expiration; + } + + public Exposure getExposure() { + return exposure; + } + + public void setExposure(Exposure exposure) { + this.exposure = exposure; + } } diff --git a/src/main/resources/default.conf b/src/main/resources/default.conf new file mode 100644 index 0000000..4ad9361 --- /dev/null +++ b/src/main/resources/default.conf @@ -0,0 +1 @@ +enabled = true