From 3e1ec094871040fe9adb35990beb3f48ac5d3f85 Mon Sep 17 00:00:00 2001 From: William278 Date: Wed, 1 Mar 2023 16:23:01 +0000 Subject: [PATCH] Start refactor work --- .../william278/huskhomes/BukkitHuskHomes.java | 71 +- .../william278/huskhomes/hook/DynMapHook.java | 4 +- .../huskhomes/hook/RedisEconomyHook.java | 2 +- .../listener/BukkitEventListener.java | 2 +- .../huskhomes/migrator/LegacyMigrator.java | 18 +- .../huskhomes/util/BukkitTaskRunner.java | 30 + .../java/net/william278/huskhomes/Cache.java | 2 +- .../net/william278/huskhomes/HuskHomes.java | 38 +- .../huskhomes/ValidationException.java | 9 +- .../huskhomes/api/BaseHuskHomesAPI.java | 132 +- .../huskhomes/command/DelHomeCommand.java | 4 +- .../huskhomes/command/DelWarpCommand.java | 4 +- .../huskhomes/command/EditHomeCommand.java | 14 +- .../huskhomes/command/EditWarpCommand.java | 8 +- .../huskhomes/command/HomeCommand.java | 2 +- .../huskhomes/command/HomeListCommand.java | 2 +- .../huskhomes/command/HuskHomesCommand.java | 2 +- .../huskhomes/command/PublicHomeCommand.java | 2 +- .../command/PublicHomeListCommand.java | 2 +- .../huskhomes/command/RtpCommand.java | 44 +- .../huskhomes/command/SetHomeCommand.java | 10 +- .../huskhomes/command/SetSpawnCommand.java | 12 +- .../huskhomes/command/SetWarpCommand.java | 2 +- .../huskhomes/command/SpawnCommand.java | 23 +- .../huskhomes/command/WarpCommand.java | 8 +- .../huskhomes/command/WarpListCommand.java | 4 +- .../william278/huskhomes/config/Settings.java | 361 +++- .../huskhomes/database/Database.java | 86 +- .../huskhomes/database/MySqlDatabase.java | 1597 ++++++++--------- .../huskhomes/database/SqLiteDatabase.java | 1509 ++++++++-------- .../huskhomes/hook/BlueMapHook.java | 4 +- .../william278/huskhomes/hook/MapHook.java | 18 +- .../huskhomes/hook/PlanDataExtension.java | 22 +- .../william278/huskhomes/hook/PlanHook.java | 2 +- .../huskhomes/listener/EventListener.java | 16 +- .../huskhomes/manager/HomesManager.java | 98 + .../william278/huskhomes/manager/Manager.java | 34 + .../huskhomes/manager/UsersManager.java | 15 + .../huskhomes/manager/WarpsManager.java | 83 + .../huskhomes/network/Messenger.java | 2 +- .../william278/huskhomes/network/Request.java | 4 +- .../position/SavedPositionManager.java | 443 ----- .../random/NormalDistributionEngine.java | 10 +- .../random/RandomTeleportEngine.java | 19 +- .../huskhomes/redis/RedisWorker.java | 8 +- .../huskhomes/request/RequestManager.java | 8 +- .../huskhomes/teleport/Teleport.java | 6 +- .../huskhomes/teleport/TeleportBuilder.java | 6 +- .../huskhomes/teleport/TimedTeleport.java | 2 +- .../william278/huskhomes/util/TaskRunner.java | 16 + .../william278/huskhomes/util/Validator.java | 51 + 51 files changed, 2397 insertions(+), 2474 deletions(-) create mode 100644 bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java create mode 100644 common/src/main/java/net/william278/huskhomes/manager/HomesManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/manager/Manager.java create mode 100644 common/src/main/java/net/william278/huskhomes/manager/UsersManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java delete mode 100644 common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/TaskRunner.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/Validator.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 4b427130..9ca47a99 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -19,6 +19,7 @@ import net.william278.huskhomes.event.EventDispatcher; import net.william278.huskhomes.hook.*; import net.william278.huskhomes.listener.BukkitEventListener; import net.william278.huskhomes.listener.EventListener; +import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Messenger; import net.william278.huskhomes.network.PluginMessenger; import net.william278.huskhomes.network.RedisMessenger; @@ -27,7 +28,6 @@ import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.player.BukkitPlayer; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.World; import net.william278.huskhomes.random.NormalDistributionEngine; @@ -58,7 +58,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.stream.Collectors; -public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { +public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTaskRunner { /** * Metrics ID for HuskHomes on Bukkit. @@ -70,7 +70,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { private Database database; private Cache cache; private RequestManager requestManager; - private SavedPositionManager savedPositionManager; + private Validator validator; + private Manager manager; private EventListener eventListener; private RandomTeleportEngine randomTeleportEngine; private CachedSpawn serverSpawn; @@ -118,7 +119,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); initialized.set(reload()); if (initialized.get()) { - logger.showDebugLogs(settings.debugLogging); + logger.showDebugLogs(settings.doDebugLogging()); if (upgradeData != null) { upgradeData.upgradeSettings(settings); } @@ -129,7 +130,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Initialize the database getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database..."); - final Settings.DatabaseType databaseType = settings.databaseType; + final Settings.DatabaseType databaseType = settings.getDatabaseType(); this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) { case MYSQL -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); @@ -142,9 +143,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } // Initialize the network messenger if proxy mode is enabled - if (getSettings().crossServer) { + if (getSettings().isCrossServer()) { getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); - messenger = switch (settings.messengerType) { + messenger = switch (settings.getMessengerType()) { case PLUGIN_MESSAGE -> new PluginMessenger(); case REDIS -> new RedisMessenger(); }; @@ -152,6 +153,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); } + // Prepare the validator + this.validator = new Validator(this); + // Prepare the request manager this.requestManager = new RequestManager(this); @@ -163,22 +167,22 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { cache.initialize(database); // Prepare the home and warp position manager - this.savedPositionManager = new SavedPositionManager(this); + this.manager = new Manager(this); // Initialize the RTP engine with the default normal distribution engine setRandomTeleportEngine(new NormalDistributionEngine(this)); // Register plugin hooks (Economy, Maps, Plan) this.pluginHooks = new HashSet<>(); - if (settings.economy) { + if (settings.isEconomy()) { if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) { pluginHooks.add(new RedisEconomyHook(this)); } else if (Bukkit.getPluginManager().getPlugin("Vault") != null) { pluginHooks.add(new VaultEconomyHook(this)); } } - if (settings.doMapHook) { - switch (settings.mappingPlugin) { + if (settings.isDoMapHook()) { + switch (settings.getMappingPlugin()) { case DYNMAP -> { final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap"); if (dynmapPlugin != null) { @@ -223,7 +227,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } // If the command is disabled, use the disabled CommandBase - if (settings.disabledCommands.stream().anyMatch(disabledCommand -> { + if (settings.getDisabledCommands().stream().anyMatch(disabledCommand -> { final String command = (disabledCommand.startsWith("/") ? disabledCommand.substring(1) : disabledCommand); return command.equalsIgnoreCase(commandType.commandBase.command) || Arrays.stream(commandType.commandBase.aliases).anyMatch(alias -> alias.equalsIgnoreCase(command)); })) { @@ -246,7 +250,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { registerMetrics(METRICS_ID); // Check for updates - if (settings.checkForUpdates) { + if (settings.doCheckForUpdates()) { getLoggingAdapter().log(Level.INFO, "Checking for updates..."); getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getPluginVersion() + ")"))); } @@ -347,10 +351,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { return requestManager; } + @Override + @NotNull + public Validator getValidator() { + return validator; + } + @NotNull @Override - public SavedPositionManager getSavedPositionManager() { - return savedPositionManager; + public Manager getManager() { + return manager; } @NotNull @@ -478,11 +488,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get(); // Load locales from language preset default - final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get(); - this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"), languagePresets).get(); + final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.getLanguage() + ".yml"))).get(); + this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.getLanguage() + ".yml"), languagePresets).get(); // Load server from file - if (settings.crossServer) { + if (settings.isCrossServer()) { this.server = Annotaml.create(new File(getDataFolder(), "server.yml"), Server.class).get(); } else { this.server = Server.getDefault(); @@ -514,22 +524,28 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { public void registerMetrics(int metricsId) { try { final Metrics metrics = new Metrics(this, metricsId); - metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().crossServer))); - if (getSettings().crossServer) { - metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().messengerType.displayName)); + metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().isCrossServer()))); + if (getSettings().isCrossServer()) { + metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().getMessengerType().displayName)); } - metrics.addCustomChart(new SimplePie("language", () -> getSettings().language.toLowerCase())); - metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().databaseType.displayName)); - metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().economy))); - metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook))); - if (getSettings().doMapHook) { - metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().mappingPlugin.displayName)); + metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase())); + metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().displayName)); + metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().isEconomy()))); + metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().isDoMapHook()))); + if (getSettings().isDoMapHook()) { + metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName)); } } catch (Exception e) { getLoggingAdapter().log(Level.WARNING, "Failed to register metrics", e); } } + @Override + @NotNull + public HuskHomes getPlugin() { + return this; + } + // Default constructor @SuppressWarnings("unused") public BukkitHuskHomes() { @@ -541,5 +557,4 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) { super(loader, description, dataFolder, file); } - } diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java index 690cd2e1..6e30835f 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java @@ -37,7 +37,7 @@ public class DynMapHook extends MapHook { protected CompletableFuture initializeMap() { return CompletableFuture.runAsync(() -> { final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI(); - if (plugin.getSettings().publicHomesOnMap) { + if (plugin.getSettings().isPublicHomesOnMap()) { markerAPI.getMarkerIcons().stream() .filter(markerIcon -> markerIcon.getMarkerIconID().equals(PUBLIC_HOME_MARKER_IMAGE_NAME)) .findFirst() @@ -47,7 +47,7 @@ public class DynMapHook extends MapHook { markerAPI.createMarkerSet(PUBLIC_HOMES_MARKER_SET_ID, "Public Homes", dynmapAPI.getMarkerAPI().getMarkerIcons(), false); } - if (plugin.getSettings().warpsOnMap) { + if (plugin.getSettings().isWarpsOnMap()) { markerAPI.getMarkerIcons().stream() .filter(markerIcon -> markerIcon.getMarkerIconID().equals(WARP_MARKER_IMAGE_NAME)) .findFirst() diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/RedisEconomyHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/RedisEconomyHook.java index e1aab080..9ab45ba3 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/RedisEconomyHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/RedisEconomyHook.java @@ -14,7 +14,7 @@ public class RedisEconomyHook extends VaultEconomyHook { public boolean initialize() { RedisEconomyAPI api = RedisEconomyAPI.getAPI(); if (api != null) { - economy = api.getCurrencyByName(plugin.getSettings().redisEconomyName); + economy = api.getCurrencyByName(plugin.getSettings().getRedisEconomyName()); if (economy != null) { return true; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java index 8dc28e5a..7867b4a6 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java @@ -62,7 +62,7 @@ public class BukkitEventListener extends EventListener implements Listener { // (https://jd.papermc.io/paper/1.19/com/destroystokyo/paper/event/player/PlayerSetSpawnEvent.html) @EventHandler(priority = EventPriority.NORMAL) public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { - if (!(plugin.getSettings().crossServer && plugin.getSettings().globalRespawning)) return; + if (!(plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning())) return; if (event.getClickedBlock() == null) return; if (!(event.getClickedBlock().getBlockData() instanceof Bed || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return; diff --git a/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java b/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java index d9e8da9a..5cae54cf 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java +++ b/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java @@ -25,12 +25,12 @@ public class LegacyMigrator extends Migrator { public LegacyMigrator(@NotNull HuskHomes implementor) { super(implementor); - this.sourceDatabaseType = implementor.getSettings().databaseType; - this.sourceMySqlHost = implementor.getSettings().mySqlHost; - this.sourceMySqlPort = implementor.getSettings().mySqlPort; - this.sourceMySqlDatabase = implementor.getSettings().mySqlDatabase; - this.sourceMySqlUsername = implementor.getSettings().mySqlUsername; - this.sourceMySqlPassword = implementor.getSettings().mySqlPassword; + this.sourceDatabaseType = implementor.getSettings().getDatabaseType(); + this.sourceMySqlHost = implementor.getSettings().getMySqlHost(); + this.sourceMySqlPort = implementor.getSettings().getMySqlPort(); + this.sourceMySqlDatabase = implementor.getSettings().getMySqlDatabase(); + this.sourceMySqlUsername = implementor.getSettings().getMySqlUsername(); + this.sourceMySqlPassword = implementor.getSettings().getMySqlPassword(); } public LegacyMigrator(@NotNull HuskHomes implementor, @NotNull BukkitUpgradeUtil bukkitUpgradeUtil) { @@ -57,9 +57,9 @@ public class LegacyMigrator extends Migrator { return true; } - if (sourceDatabaseType == plugin.getSettings().databaseType - && sourceMySqlHost.equals(plugin.getSettings().mySqlHost) - && sourceMySqlPort == plugin.getSettings().mySqlPort) { + if (sourceDatabaseType == plugin.getSettings().getDatabaseType() + && sourceMySqlHost.equals(plugin.getSettings().getMySqlHost()) + && sourceMySqlPort == plugin.getSettings().getMySqlPort()) { migrateMySqlDatabase(); return true; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java new file mode 100644 index 00000000..4375ce35 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java @@ -0,0 +1,30 @@ +package net.william278.huskhomes.util; + +import net.william278.huskhomes.BukkitHuskHomes; +import net.william278.huskhomes.HuskHomes; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public interface BukkitTaskRunner extends TaskRunner { + @Override + default void runAsync(@NotNull Runnable runnable) { + Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable); + } + + @Override + default CompletableFuture supplyAsync(@NotNull Supplier supplier) { + final CompletableFuture future = new CompletableFuture<>(); + Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), + () -> future.complete(supplier.get())); + return future; + } + + @Override + default void runSync(@NotNull Runnable runnable) { + Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java index b6beb760..fb145bf9 100644 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -112,7 +112,7 @@ public class Cache { .map(onlineUser -> onlineUser.username) .toList()); - if (plugin.getSettings().crossServer) { + if (plugin.getSettings().isCrossServer()) { return plugin.getMessenger() .getOnlinePlayerNames(requester) .thenApply(networkedPlayers -> { diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index a2eb28d5..a6b6b4cd 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -11,6 +11,7 @@ import net.william278.huskhomes.event.EventDispatcher; import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.MapHook; import net.william278.huskhomes.hook.PluginHook; +import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Messenger; import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.player.OnlineUser; @@ -19,6 +20,8 @@ import net.william278.huskhomes.random.RandomTeleportEngine; import net.william278.huskhomes.request.RequestManager; import net.william278.huskhomes.util.Logger; import net.william278.huskhomes.util.Permission; +import net.william278.huskhomes.util.TaskRunner; +import net.william278.huskhomes.util.Validator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -32,7 +35,7 @@ import java.util.concurrent.CompletableFuture; /** * Represents a cross-platform instance of the plugin */ -public interface HuskHomes { +public interface HuskHomes extends TaskRunner { int SPIGOT_RESOURCE_ID = 83767; @@ -85,7 +88,7 @@ public interface HuskHomes { if (localPlayer.isPresent()) { return CompletableFuture.completedFuture(Optional.of(localPlayer.get().username)); } - if (getSettings().crossServer) { + if (getSettings().isCrossServer()) { return getMessenger().findPlayer(requester, targetPlayerName); } return CompletableFuture.completedFuture(Optional.empty()); @@ -128,15 +131,24 @@ public interface HuskHomes { * * @return the plugin {@link RequestManager} */ - @NotNull RequestManager getRequestManager(); + @NotNull + RequestManager getRequestManager(); /** - * The {@link SavedPositionManager} that manages setting homes and warps + * The {@link Validator} for validating thome names and descriptions * - * @return the {@link SavedPositionManager} implementation + * @return the {@link Validator} instance */ @NotNull - SavedPositionManager getSavedPositionManager(); + Validator getValidator(); + + /** + * The {@link Manager} that manages home, warp and user data + * + * @return the {@link Manager} implementation + */ + @NotNull + Manager getManager(); /** * The {@link Messenger} that sends cross-network messages @@ -189,10 +201,10 @@ public interface HuskHomes { * * @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set */ - default CompletableFuture> getSpawn() { - return CompletableFuture.supplyAsync(() -> getSettings().crossServer && getSettings().globalSpawn - ? getDatabase().getWarp(getSettings().globalSpawnName).join() - : getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName()))); + default Optional getSpawn() { + return getSettings().isCrossServer() && getSettings().isGlobalSpawn() + ? getDatabase().getWarp(getSettings().getGlobalSpawnName()) + : getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName())); } /** @@ -246,7 +258,7 @@ public interface HuskHomes { * @return the {@link MapHook} optionally being used */ default Optional getMapHook() { - return getSettings().doMapHook ? getHook(MapHook.class) : Optional.empty(); + return getSettings().isDoMapHook() ? getHook(MapHook.class) : Optional.empty(); } /** @@ -255,7 +267,7 @@ public interface HuskHomes { * @return the {@link EconomyHook} optionally being used */ default Optional getEconomyHook() { - return getSettings().economy ? getHook(EconomyHook.class) : Optional.empty(); + return getSettings().isEconomy() ? getHook(EconomyHook.class) : Optional.empty(); } /** @@ -288,7 +300,7 @@ public interface HuskHomes { * @param action the action to deduct the cost from if needed */ default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull Settings.EconomyAction action) { - if (!getSettings().economy) return; + if (!getSettings().isEconomy()) return; final Optional cost = getSettings().getEconomyCost(action).map(Math::abs); if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) { diff --git a/common/src/main/java/net/william278/huskhomes/ValidationException.java b/common/src/main/java/net/william278/huskhomes/ValidationException.java index 61463605..acdb61ee 100644 --- a/common/src/main/java/net/william278/huskhomes/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/ValidationException.java @@ -9,11 +9,10 @@ public class ValidationException extends IllegalArgumentException { } public enum ValidationError { - NAME_LENGTH, + NOT_FOUND, NAME_TAKEN, - NAME_CHARACTERS, - NAME_RESERVED, - DESCRIPTION_LENGTH, - DESCRIPTION_CHARACTERS + NAME_INVALID, + DESCRIPTION_INVALID } + } diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index e057d362..5e361ede 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -47,7 +47,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getUserData(@NotNull UUID uuid) { - return plugin.getDatabase().getUserData(uuid); + return plugin.supplyAsync(() -> plugin.getDatabase().getUserData(uuid)); } /** @@ -58,7 +58,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getUserData(@NotNull String username) { - return plugin.getDatabase().getUserDataByName(username); + return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username)); } /** @@ -69,7 +69,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public CompletableFuture> getUserLastPosition(@NotNull User user) { - return plugin.getDatabase().getLastPosition(user); + return plugin.supplyAsync(() -> plugin.getDatabase().getLastPosition(user)); } /** @@ -80,7 +80,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public CompletableFuture> getUserOfflinePosition(@NotNull User user) { - return plugin.getDatabase().getOfflinePosition(user); + return plugin.supplyAsync(() -> plugin.getDatabase().getOfflinePosition(user)); } /** @@ -94,10 +94,10 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public CompletableFuture> getUserRespawnPosition(@NotNull User user) { - if (!plugin.getSettings().crossServer || plugin.getSettings().globalRespawning) { + if (!plugin.getSettings().isCrossServer() || plugin.getSettings().isGlobalRespawning()) { return CompletableFuture.completedFuture(Optional.empty()); } - return plugin.getDatabase().getRespawnPosition(user); + return plugin.supplyAsync(() -> plugin.getDatabase().getRespawnPosition(user)); } /** @@ -119,8 +119,8 @@ public abstract class BaseHuskHomesAPI { * @return A {@link CompletableFuture} that will complete when the data has been saved * @since 3.0 */ - public final CompletableFuture saveUserData(@NotNull UserData userData) { - return plugin.getDatabase().updateUserData(userData); + public final void saveUserData(@NotNull UserData userData) { + plugin.runAsync(() -> plugin.getDatabase().updateUserData(userData)); } /** @@ -130,7 +130,7 @@ public abstract class BaseHuskHomesAPI { * @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user */ public final CompletableFuture> getUserHomes(@NotNull User user) { - return plugin.getDatabase().getHomes(user); + return plugin.supplyAsync(() -> plugin.getDatabase().getHomes(user)); } /** @@ -154,7 +154,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getPublicHomes() { - return plugin.getDatabase().getPublicHomes(); + return plugin.supplyAsync(() -> plugin.getDatabase().getPublicHomes()); } /** @@ -166,7 +166,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getHome(@NotNull User user, @NotNull String homeName) { - return plugin.getDatabase().getHome(user, homeName); + return plugin.supplyAsync(() -> plugin.getDatabase().getHome(user, homeName)); } /** @@ -176,7 +176,7 @@ public abstract class BaseHuskHomesAPI { * @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional} */ public final CompletableFuture> getHome(@NotNull UUID homeUuid) { - return plugin.getDatabase().getHome(homeUuid); + return plugin.supplyAsync(() -> plugin.getDatabase().getHome(homeUuid)); } /** @@ -186,7 +186,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getWarps() { - return plugin.getDatabase().getWarps(); + return plugin.supplyAsync(() -> plugin.getDatabase().getWarps()); } /** @@ -197,7 +197,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getWarp(@NotNull String warpName) { - return plugin.getDatabase().getWarp(warpName); + return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpName)); } /** @@ -207,7 +207,7 @@ public abstract class BaseHuskHomesAPI { * @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional} */ public final CompletableFuture> getWarp(@NotNull UUID warpUuid) { - return plugin.getDatabase().getWarp(warpUuid); + return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpUuid)); } /** @@ -217,76 +217,7 @@ public abstract class BaseHuskHomesAPI { * @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point */ public final CompletableFuture> getSpawn() { - return plugin.getSpawn(); - } - - /** - * Update the {@link PositionMeta} of a {@link Home} - * - * @param home The {@link Home} to update - * @param newMeta The new {@link PositionMeta} to set - * @return A {@link CompletableFuture} that will complete when the {@link Home} has been updated with a - * {@link SavedPositionManager.SaveResult} indicating if the update was successful - * @since 3.0 - */ - public final CompletableFuture updateHomeMeta(@NotNull Home home, - @NotNull PositionMeta newMeta) { - return plugin.getSavedPositionManager().updateHomeMeta(home, newMeta); - } - - /** - * Update the position of a {@link Home}, relocating it - * - * @param home The {@link Home} to update - * @param newPosition The new {@link Position} to relocate the home to - * @return A {@link CompletableFuture} that will complete with a boolean indicating if the home was - * updated ({@code true} if it was updated; otherwise, {@code false}) - * @since 3.0 - */ - public final CompletableFuture updateHomePosition(@NotNull Home home, - @NotNull Position newPosition) { - return plugin.getSavedPositionManager().updateHomePosition(home, newPosition); - } - - /** - * Update the privacy of a {@link Home} - * - * @param home The {@link Home} to update - * @param isPublic Whether the home should be set to public or not - * @return A {@link CompletableFuture} that will complete with a boolean indicating if the home's privacy - * was updated ({@code true} if it was updated; otherwise, {@code false}) - * @since 3.0 - */ - public final CompletableFuture updateHomePrivacy(@NotNull Home home, - final boolean isPublic) { - return plugin.getSavedPositionManager().updateHomePrivacy(home, isPublic); - } - - /** - * Update the {@link PositionMeta} of a {@link Warp} - * - * @param warp The {@link Warp} to update - * @param newMeta The new {@link PositionMeta} to set - * @return A {@link CompletableFuture} that will complete when the {@link Warp} has been updated with a - * {@link SavedPositionManager.SaveResult} indicating if the update was successful - * @since 3.0 - */ - public final CompletableFuture updateWarpMeta(@NotNull Warp warp, - @NotNull PositionMeta newMeta) { - return plugin.getSavedPositionManager().updateWarpMeta(warp, newMeta); - } - - /** - * Update the position of a {@link Warp}, relocating it - * - * @param warp The {@link Warp} to update - * @param newPosition The new {@link Position} to relocate the warp to - * @return A {@link CompletableFuture} that will complete with a boolean indicating if the warp was - * updated ({@code true} if it was updated; otherwise, {@code false}) - */ - public final CompletableFuture updateWarpPosition(@NotNull Warp warp, - @NotNull Position newPosition) { - return plugin.getSavedPositionManager().updateWarpPosition(warp, newPosition); + return plugin.supplyAsync(plugin::getSpawn); } /** @@ -297,7 +228,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final int getMaxHomeSlots(@NotNull OnlineUser user) { - return user.getMaxHomes(plugin.getSettings().maxHomes, plugin.getSettings().stackPermissionLimits); + return user.getMaxHomes(plugin.getSettings().getMaxHomes(), plugin.getSettings().doStackPermissionLimits()); } /** @@ -310,7 +241,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final int getFreeHomeSlots(@NotNull OnlineUser user) { - return user.getFreeHomes(plugin.getSettings().freeHomeSlots, plugin.getSettings().stackPermissionLimits); + return user.getFreeHomes(plugin.getSettings().getFreeHomeSlots(), plugin.getSettings().doStackPermissionLimits()); } /** @@ -321,7 +252,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0 */ public final int getMaxPublicHomeSlots(@NotNull OnlineUser user) { - return user.getMaxPublicHomes(plugin.getSettings().maxPublicHomes, plugin.getSettings().stackPermissionLimits); + return user.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), plugin.getSettings().doStackPermissionLimits()); } /** @@ -388,22 +319,19 @@ public abstract class BaseHuskHomesAPI { public final CompletableFuture randomlyTeleportPlayer(@NotNull OnlineUser user, final boolean timedTeleport, @NotNull String... rtpArgs) { - return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine() + return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine() .getRandomPosition(user.getPosition().world, rtpArgs) - .thenApply(position -> { - if (position.isPresent()) { - final TeleportBuilder builder = Teleport.builder(plugin, user) - .setTarget(position.get()); + .map(position -> { + final TeleportBuilder builder = Teleport.builder(plugin, user) + .setTarget(position); + return timedTeleport + ? builder.toTimedTeleport() + .thenApplyAsync(teleport -> teleport.execute().join().getState()).join() + : builder.toTeleport() + .thenApplyAsync(teleport -> teleport.execute().join().getState()).join(); - return timedTeleport - ? builder.toTimedTeleport() - .thenApplyAsync(teleport -> teleport.execute().join().getState()).join() - : builder.toTeleport() - .thenApplyAsync(teleport -> teleport.execute().join().getState()).join(); - } else { - return TeleportResult.CANCELLED; - } - }).join()); + }) + .orElse(TeleportResult.CANCELLED)); } /** diff --git a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java index 187f3ea3..0df8f9ab 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -68,7 +68,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable { */ private void deletePlayerHome(@NotNull OnlineUser deleter, @NotNull User homeOwner, @NotNull String homeName, final boolean delHomeAllConfirm) { - plugin.getSavedPositionManager().deleteHome(homeOwner, homeName).thenAccept(deleted -> { + plugin.getManager().deleteHome(homeOwner, homeName).thenAccept(deleted -> { if (deleter.equals(homeOwner)) { if (deleted) { plugin.getLocales().getLocale("home_deleted", homeName).ifPresent(deleter::sendMessage); @@ -108,7 +108,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable { return; } - plugin.getSavedPositionManager().deleteAllHomes(homeOwner).thenAccept(deleted -> { + plugin.getManager().deleteAllHomes(homeOwner).thenAccept(deleted -> { if (deleted == 0) { plugin.getLocales().getLocale("error_no_warps_set") .ifPresent(deleter::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index b2f6a9b5..a5b8daac 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -26,7 +26,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable { if (args.length <= 2) { final String warpName = args[0]; final boolean confirm = args.length == 2 && args[1].equalsIgnoreCase("confirm"); - plugin.getSavedPositionManager().deleteWarp(warpName).thenAccept(deleted -> { + plugin.getManager().deleteWarp(warpName).thenAccept(deleted -> { if (deleted) { plugin.getLocales().getLocale("warp_deleted", warpName) .ifPresent(onlineUser::sendMessage); @@ -59,7 +59,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable { return; } - plugin.getSavedPositionManager().deleteAllWarps().thenAccept(deleted -> { + plugin.getManager().deleteAllWarps().thenAccept(deleted -> { if (deleted == 0) { plugin.getLocales().getLocale("error_no_warps_set") .ifPresent(deleter::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java index 5c2016ac..c3f529d5 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -116,7 +116,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { final String oldHomeName = home.meta.name; final String newHomeName = editArgs; - plugin.getSavedPositionManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description)) + plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description)) .thenAccept(renameResult -> (switch (renameResult.resultType()) { case SUCCESS -> { if (home.owner.equals(editor)) { @@ -137,7 +137,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { final String oldHomeDescription = home.meta.description; final String newDescription = editArgs != null ? editArgs : ""; - plugin.getSavedPositionManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription)) + plugin.getManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription)) .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { case SUCCESS -> { if (home.owner.equals(editor)) { @@ -165,7 +165,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { }).ifPresent(editor::sendMessage)); } case "relocate" -> - plugin.getSavedPositionManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { + plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { if (home.owner.equals(editor)) { editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", home.meta.name).orElse(new MineDown(""))); @@ -216,8 +216,8 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { // Check against maximum public homes final List existingPublicHomes = editorHomes.stream() .filter(existingHome -> existingHome.isPublic).toList(); - final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes, - plugin.getSettings().stackPermissionLimits); + final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), + plugin.getSettings().doStackPermissionLimits()); if (existingPublicHomes.size() >= maxPublicHomes) { plugin.getLocales().getLocale("error_edit_home_maximum_public_homes", Integer.toString(maxPublicHomes)) @@ -232,7 +232,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { } // Execute the update - plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> { + plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> { if (home.owner.equals(editor)) { editor.sendMessage(plugin.getLocales().getLocale( "edit_home_privacy_" + privacyKeyedString + "_success", @@ -313,7 +313,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { .ifPresent(this::add); } - if (!plugin.getSettings().crossServer) { + if (!plugin.getSettings().isCrossServer()) { plugin.getLocales().getLocale("edit_home_menu_world", home.world.name) .ifPresent(this::add); } else { diff --git a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java index e81f9746..594d5618 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java @@ -85,7 +85,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable { final String oldWarpName = warp.meta.name; final String newWarpName = editArgs; - plugin.getSavedPositionManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description)) + plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description)) .thenAccept(renameResult -> (switch (renameResult.resultType()) { case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName); @@ -99,7 +99,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable { final String oldWarpDescription = warp.meta.description; final String newDescription = editArgs != null ? editArgs : ""; - plugin.getSavedPositionManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription)) + plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription)) .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description", warp.meta.name, @@ -115,7 +115,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable { }).ifPresent(editor::sendMessage)); } case "relocate" -> - plugin.getSavedPositionManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> { + plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> { editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location", warp.meta.name).orElse(new MineDown(""))); @@ -175,7 +175,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable { .ifPresent(this::add); } - if (!plugin.getSettings().crossServer) { + if (!plugin.getSettings().isCrossServer()) { plugin.getLocales().getLocale("edit_warp_menu_world", warp.world.name).ifPresent(this::add); } else { plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.world.name, warp.server.name).ifPresent(this::add); diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index 1bd085da..18d2762a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -36,7 +36,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE .setTarget(homes.get(0)) .toTimedTeleport().thenAccept(TimedTeleport::execute); default -> plugin.getCache().getHomeList(onlineUser, onlineUser, - plugin.getLocales(), homes, plugin.getSettings().listItemsPerPage, 1) + plugin.getLocales(), homes, plugin.getSettings().getListItemsPerPage(), 1) .ifPresent(onlineUser::sendMessage); } }); diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java index be9d1ba4..7cbe3bc2 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -76,7 +76,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable { } plugin.getCache().getHomeList(onlineUser, userData.user(), plugin.getLocales(), homes, - plugin.getSettings().listItemsPerPage, pageNumber) + plugin.getSettings().getListItemsPerPage(), pageNumber) .ifPresent(onlineUser::sendMessage); }); }, () -> plugin.getLocales().getLocale("error_player_not_found", homeOwner).ifPresent(onlineUser::sendMessage))); diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index e81e5856..a1b301a6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -78,7 +78,7 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, } } onlineUser.sendMessage(plugin.getCache().getCommandList(onlineUser, - plugin.getLocales(), plugin.getCommands(), plugin.getSettings().listItemsPerPage, page)); + plugin.getLocales(), plugin.getCommands(), plugin.getSettings().getListItemsPerPage(), page)); } case "reload" -> { if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_RELOAD.node)) { diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index f976394a..27543cc0 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -37,7 +37,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co } plugin.getCache().getPublicHomeList(onlineUser, plugin.getLocales(), - publicHomes, plugin.getSettings().listItemsPerPage, 1) + publicHomes, plugin.getSettings().getListItemsPerPage(), 1) .ifPresent(onlineUser::sendMessage); }); case 1 -> { diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java index 20b6bc93..06c36d10 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java @@ -54,7 +54,7 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta } plugin.getCache().getPublicHomeList(onlineUser, plugin.getLocales(), publicHomes, - plugin.getSettings().listItemsPerPage, pageNumber) + plugin.getSettings().getListItemsPerPage(), pageNumber) .ifPresent(onlineUser::sendMessage); }); diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index b9b01ed5..a5751b07 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -41,7 +41,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } final Position userPosition = target.getPosition(); final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args; - if (plugin.getSettings().rtpRestrictedWorlds.stream() + if (plugin.getSettings().getRtpRestrictedWorlds().stream() .anyMatch(worldName -> worldName.equals(userPosition.world.name))) { plugin.getLocales().getLocale("error_rtp_restricted_world") .ifPresent(onlineUser::sendMessage); @@ -62,7 +62,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } final Instant currentTime = Instant.now(); if (isExecutorTeleporting && !currentTime.isAfter(userData.get().rtpCooldown()) - && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { + && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { plugin.getLocales().getLocale("error_rtp_cooldown", Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES) + 1)) .ifPresent(onlineUser::sendMessage); @@ -72,29 +72,29 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { // Get a random position and teleport plugin.getLocales().getLocale("teleporting_random_generation") .ifPresent(onlineUser::sendMessage); - plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments).thenAccept(position -> { - if (position.isEmpty()) { - plugin.getLocales().getLocale("error_rtp_randomization_timeout") - .ifPresent(onlineUser::sendMessage); - return; - } - final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport) - .setTarget(position.get()); - final CompletableFuture teleportFuture = isExecutorTeleporting - ? builder.setEconomyActions(Settings.EconomyAction.RANDOM_TELEPORT).toTimedTeleport() - : builder.toTeleport(); + final Optional position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments); + if (position.isEmpty()) { + plugin.getLocales().getLocale("error_rtp_randomization_timeout") + .ifPresent(onlineUser::sendMessage); + return; + } - teleportFuture.thenAccept(teleport -> teleport.execute() - .thenAccept(result -> { - if (isExecutorTeleporting && + final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport) + .setTarget(position.get()); + final CompletableFuture teleportFuture = isExecutorTeleporting + ? builder.setEconomyActions(Settings.EconomyAction.RANDOM_TELEPORT).toTimedTeleport() + : builder.toTeleport(); + + teleportFuture.thenAccept(teleport -> teleport.execute() + .thenAccept(result -> { + if (isExecutorTeleporting && result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { - plugin.getDatabase().updateUserData(new UserData(onlineUser, - userData.get().homeSlots(), userData.get().ignoringTeleports(), - Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES))); - } - })); - }); + plugin.getDatabase().updateUserData(new UserData(onlineUser, + userData.get().homeSlots(), userData.get().ignoringTeleports(), + Instant.now().plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES))); + } + })); }); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java index fa7d3c47..df1c55a9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -55,7 +55,7 @@ public class SetHomeCommand extends CommandBase { */ private void setHome(@NotNull OnlineUser onlineUser, @NotNull String homeName, @NotNull List currentHomes) { // Check against maximum homes - final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().maxHomes, plugin.getSettings().stackPermissionLimits); + final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().getMaxHomes(), plugin.getSettings().doStackPermissionLimits()); if (currentHomes.size() >= maxHomes) { plugin.getLocales().getLocale("error_set_home_maximum_homes", Integer.toString(maxHomes)) .ifPresent(onlineUser::sendMessage); @@ -67,9 +67,9 @@ public class SetHomeCommand extends CommandBase { // Check against economy if needed final AtomicBoolean newSlotNeeded = new AtomicBoolean(false); final AtomicReference userDataToUpdate = new AtomicReference<>(null); - if (plugin.getSettings().economy) { - final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots, - plugin.getSettings().stackPermissionLimits); + if (plugin.getSettings().isEconomy()) { + final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(), + plugin.getSettings().doStackPermissionLimits()); if (fetchedData.isPresent()) { final Settings.EconomyAction action = Settings.EconomyAction.ADDITIONAL_HOME_SLOT; newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots())); @@ -95,7 +95,7 @@ public class SetHomeCommand extends CommandBase { } // Set the home in the saved position manager - plugin.getSavedPositionManager() + plugin.getManager() .setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition()) .thenAccept(setResult -> { // Display feedback of the result of the set operation diff --git a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java index 9b653ab4..857ca75c 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java @@ -4,13 +4,9 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.PositionMeta; -import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - public class SetSpawnCommand extends CommandBase { protected SetSpawnCommand(@NotNull HuskHomes implementor) { @@ -26,12 +22,12 @@ public class SetSpawnCommand extends CommandBase { } final Position position = onlineUser.getPosition(); - if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) { - plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).thenApply(warp -> { + if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalSpawn()) { + plugin.getDatabase().getWarp(plugin.getSettings().getGlobalSpawnName()).thenApply(warp -> { if (warp.isPresent()) { - return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position); + return plugin.getManager().updateWarpPosition(warp.get(), position); } else { - return plugin.getSavedPositionManager().setWarp(new PositionMeta(plugin.getSettings().globalSpawnName, + return plugin.getManager().setWarp(new PositionMeta(plugin.getSettings().getGlobalSpawnName(), plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position) .thenApply(result -> result.resultType().successful); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java index f5f3f408..eed2b739 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java @@ -23,7 +23,7 @@ public class SetWarpCommand extends CommandBase { } private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) { - plugin.getSavedPositionManager().setWarp( + plugin.getManager().setWarp( new PositionMeta(warpName, ""), onlineUser.getPosition()).thenAccept(setResult -> (switch (setResult.resultType()) { case SUCCESS -> { diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index 3b36e871..43d64e86 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -2,11 +2,14 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.OnlineUser; +import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TimedTeleport; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; +import java.util.Optional; + public class SpawnCommand extends CommandBase { protected SpawnCommand(@NotNull HuskHomes implementor) { @@ -21,15 +24,15 @@ public class SpawnCommand extends CommandBase { return; } - plugin.getSpawn().thenAccept(position -> { - if (position.isEmpty()) { - plugin.getLocales().getLocale("error_spawn_not_set") - .ifPresent(onlineUser::sendMessage); - return; - } - Teleport.builder(plugin, onlineUser) - .setTarget(position.get()) - .toTimedTeleport().thenAccept(TimedTeleport::execute); - }); + final Optional spawn = plugin.getSpawn(); + if (spawn.isEmpty()) { + plugin.getLocales().getLocale("error_spawn_not_set") + .ifPresent(onlineUser::sendMessage); + return; + } + Teleport.builder(plugin, onlineUser) + .setTarget(spawn.get()) + .toTimedTeleport() + .thenAccept(TimedTeleport::execute); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index 49d3f364..0b34d1b1 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -24,7 +24,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE switch (args.length) { case 0 -> plugin.getDatabase().getWarps() .thenApply(warps -> warps.stream() - .filter(warp -> warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) + .filter(warp -> warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser)) .collect(Collectors.toList())) .thenAccept(warps -> { if (warps.isEmpty()) { @@ -33,7 +33,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE return; } plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps, - plugin.getSettings().listItemsPerPage, 1) + plugin.getSettings().getListItemsPerPage(), 1) .ifPresent(onlineUser::sendMessage); }); case 1 -> { @@ -42,7 +42,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE .getWarp(warpName) .thenAccept(warpResult -> warpResult.ifPresentOrElse(warp -> { // Handle permission restrictions - if (!warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) { + if (!warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser)) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(onlineUser::sendMessage); return; @@ -64,7 +64,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE @Override public @NotNull List onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { return plugin.getCache().warps.stream() - .filter(s -> user == null || Warp.hasPermission(plugin.getSettings().permissionRestrictWarps, user, s)) + .filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s)) .filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : "")) .sorted() .collect(Collectors.toList()); diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index 66c3ca88..8644f5c8 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -48,7 +48,7 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable { // Dispatch the warp list event plugin.getDatabase().getWarps() .thenApply(warps -> warps.stream() - .filter(warp -> warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) + .filter(warp -> warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser)) .collect(Collectors.toList())) .thenAccept(warps -> { if (warps.isEmpty()) { @@ -56,7 +56,7 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable { return; } plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps, - plugin.getSettings().listItemsPerPage, pageNumber) + plugin.getSettings().getListItemsPerPage(), pageNumber) .ifPresent(onlineUser::sendMessage); }); } diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index 7cdd3e47..8ea7b22a 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -25,56 +25,57 @@ import java.util.Optional; public class Settings { // Top-level settings - public String language = "en-gb"; + @YamlKey("language") + private String language = "en-gb"; @YamlKey("check_for_updates") - public boolean checkForUpdates = true; + private boolean checkForUpdates = true; @YamlKey("debug_logging") - public boolean debugLogging = false; + private boolean debugLogging = false; // Database settings @YamlComment("Database connection settings") @YamlKey("database.type") - public DatabaseType databaseType = DatabaseType.SQLITE; + private DatabaseType databaseType = DatabaseType.SQLITE; @YamlKey("database.mysql.credentials.host") - public String mySqlHost = "localhost"; + private String mySqlHost = "localhost"; @YamlKey("database.mysql.credentials.port") - public int mySqlPort = 3306; + private int mySqlPort = 3306; @YamlKey("database.mysql.credentials.database") - public String mySqlDatabase = "HuskHomes"; + private String mySqlDatabase = "HuskHomes"; @YamlKey("database.mysql.credentials.username") - public String mySqlUsername = "root"; + private String mySqlUsername = "root"; @YamlKey("database.mysql.credentials.password") - public String mySqlPassword = "pa55w0rd"; + private String mySqlPassword = "pa55w0rd"; @YamlKey("database.mysql.credentials.parameters") - public String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"; + private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"; @YamlComment("MySQL connection pool properties") @YamlKey("database.mysql.connection_pool.size") - public int mySqlConnectionPoolSize = 12; + private int mySqlConnectionPoolSize = 12; @YamlKey("database.mysql.connection_pool.idle") - public int mySqlConnectionPoolIdle = 12; + private int mySqlConnectionPoolIdle = 12; @YamlKey("database.mysql.connection_pool.lifetime") - public long mySqlConnectionPoolLifetime = 1800000; + private long mySqlConnectionPoolLifetime = 1800000; @YamlKey("database.mysql.connection_pool.keepalive") - public long mySqlConnectionPoolKeepAlive = 30000; + private long mySqlConnectionPoolKeepAlive = 30000; @YamlKey("database.mysql.connection_pool.timeout") - public long mySqlConnectionPoolTimeout = 20000; + private long mySqlConnectionPoolTimeout = 20000; @YamlKey("database.table_names") - public Map tableNames = Map.of( + private Map tableNames = Map.of( TableName.PLAYER_DATA.name().toLowerCase(), TableName.PLAYER_DATA.defaultName, TableName.POSITION_DATA.name().toLowerCase(), TableName.POSITION_DATA.defaultName, TableName.SAVED_POSITION_DATA.name().toLowerCase(), TableName.SAVED_POSITION_DATA.defaultName, @@ -85,142 +86,142 @@ public class Settings { @NotNull public String getTableName(@NotNull TableName tableName) { - return Optional.ofNullable(tableNames.get(tableName.name().toLowerCase())).orElse(tableName.defaultName); + return Optional.ofNullable(getTableNames().get(tableName.name().toLowerCase())).orElse(tableName.defaultName); } // General settings @YamlComment("General plugin settings") @YamlKey("general.max_homes") - public int maxHomes = 10; + private int maxHomes = 10; @YamlKey("general.max_public_homes") - public int maxPublicHomes = 10; + private int maxPublicHomes = 10; @YamlKey("general.stack_permission_limits") - public boolean stackPermissionLimits = true; + private boolean stackPermissionLimits = true; @YamlKey("general.permission_restrict_warps") - public boolean permissionRestrictWarps = false; + private boolean permissionRestrictWarps = false; @YamlKey("general.overwrite_existing_homes_warps") - public boolean overwriteExistingHomesWarps = true; + private boolean overwriteExistingHomesWarps = true; @YamlKey("general.teleport_warmup_time") - public int teleportWarmupTime = 5; + private int teleportWarmupTime = 5; @YamlKey("general.teleport_warmup_display") - public MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR; + private MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR; @YamlKey("general.teleport_request_expiry_time") - public int teleportRequestExpiryTime = 60; + private int teleportRequestExpiryTime = 60; @YamlKey("general.strict_tpa_here_requests") - public boolean strictTpaHereRequests = true; + private boolean strictTpaHereRequests = true; @YamlKey("general.allow_unicode_names") - public boolean allowUnicodeNames = false; + private boolean allowUnicodeNames = false; @YamlKey("general.allow_unicode_descriptions") - public boolean allowUnicodeDescriptions = true; + private boolean allowUnicodeDescriptions = true; @YamlKey("general.back_command_return_by_death") - public boolean backCommandReturnByDeath = true; + private boolean backCommandReturnByDeath = true; @YamlKey("general.back_command_save_teleport_event") - public boolean backCommandSaveOnTeleportEvent = false; + private boolean backCommandSaveOnTeleportEvent = false; @YamlKey("general.list_items_per_page") - public int listItemsPerPage = 12; + private int listItemsPerPage = 12; @YamlKey("general.asynchronous_teleports") - public boolean asynchronousTeleports = true; + private boolean asynchronousTeleports = true; @YamlKey("general.play_sound_effects") - public boolean playSoundEffects = true; + private boolean playSoundEffects = true; @YamlKey("general.sound_effects") - public Map soundEffects = Map.of( + private Map soundEffects = Map.of( SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect, SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect, SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect ); public Optional getSoundEffect(@NotNull SoundEffectAction action) { - if (!playSoundEffects) { + if (!isPlaySoundEffects()) { return Optional.empty(); } - return Optional.ofNullable(soundEffects.get(action.name().toLowerCase())); + return Optional.ofNullable(getSoundEffects().get(action.name().toLowerCase())); } // Cross-server settings @YamlComment("Enable teleporting across proxied servers. Requires MySQL") @YamlKey("cross_server.enabled") - public boolean crossServer = false; + private boolean crossServer = false; @YamlKey("cross_server.messenger_type") - public MessengerType messengerType = MessengerType.PLUGIN_MESSAGE; + private MessengerType messengerType = MessengerType.PLUGIN_MESSAGE; @YamlKey("cross_server.cluster_id") - public String clusterId = ""; + private String clusterId = ""; @YamlKey("cross_server.global_spawn.enabled") - public boolean globalSpawn = false; + private boolean globalSpawn = false; @YamlKey("cross_server.global_spawn.warp_name") - public String globalSpawnName = "Spawn"; + private String globalSpawnName = "Spawn"; @YamlKey("cross_server.global_respawning") - public boolean globalRespawning = false; + private boolean globalRespawning = false; @YamlKey("cross_server.redis_credentials.host") - public String redisHost = "localhost"; + private String redisHost = "localhost"; @YamlKey("cross_server.redis_credentials.port") - public int redisPort = 6379; + private int redisPort = 6379; @YamlKey("cross_server.redis_credentials.password") - public String redisPassword = ""; + private String redisPassword = ""; @YamlKey("cross_server.redis_credentials.use_ssl") - public boolean redisUseSsl = false; + private boolean redisUseSsl = false; // Rtp command settings @YamlComment("Random teleport (/rtp) command settings") @YamlKey("rtp.cooldown_length") - public int rtpCooldownLength = 10; + private int rtpCooldownLength = 10; @YamlKey("rtp.radius") - public int rtpRadius = 5000; + private int rtpRadius = 5000; @YamlKey("rtp.spawn_radius") - public int rtpSpawnRadius = 500; + private int rtpSpawnRadius = 500; @YamlKey("rtp.distribution_mean") - public float rtpDistributionMean = 0.75f; + private float rtpDistributionMean = 0.75f; @YamlKey("rtp.distribution_deviation") - public float rtpDistributionStandardDeviation = 2f; + private float rtpDistributionStandardDeviation = 2f; @YamlKey("rtp.restricted_worlds") - public List rtpRestrictedWorlds = List.of("world_nether", "world_the_end"); + private List rtpRestrictedWorlds = List.of("world_nether", "world_the_end"); // Economy settings @YamlComment("Charge for certain actions (requires Vault)") @YamlKey("economy.enabled") - public boolean economy = false; + private boolean economy = false; @YamlComment("Use this currency for payments (works only with RedisEconomy), defaults to Vault currency") @YamlKey("economy.redis_economy_name") - public String redisEconomyName = "vault"; + private String redisEconomyName = "vault"; @YamlKey("economy.free_home_slots") - public int freeHomeSlots = 5; + private int freeHomeSlots = 5; @YamlKey("economy.costs") - public Map economyCosts = Map.of( + private Map economyCosts = Map.of( EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost, EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost, EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost, @@ -228,10 +229,10 @@ public class Settings { ); public Optional getEconomyCost(@NotNull EconomyAction action) { - if (!economy) { + if (!isEconomy()) { return Optional.empty(); } - final Double cost = economyCosts.get(action.name().toLowerCase()); + final Double cost = getEconomyCosts().get(action.name().toLowerCase()); if (cost != null && cost > 0d) { return Optional.of(cost); } @@ -241,25 +242,257 @@ public class Settings { // Mapping plugins @YamlComment("Display public homes/warps on web maps (DYNMAP, BLUEMAP)") @YamlKey("map_hook.enabled") - public boolean doMapHook = false; + private boolean doMapHook = false; @YamlKey("map_hook.map_plugin") - public MappingPlugin mappingPlugin = MappingPlugin.DYNMAP; + private MappingPlugin mappingPlugin = MappingPlugin.DYNMAP; @YamlKey("map_hook.show_public_homes") - public boolean publicHomesOnMap = true; + private boolean publicHomesOnMap = true; @YamlKey("map_hook.show_warps") - public boolean warpsOnMap = true; + private boolean warpsOnMap = true; // Disabled commands @YamlComment("Disabled commands (e.g. ['/home', '/warp'] to disable /home and /warp)") @YamlKey("disabled_commands") - public List disabledCommands = Collections.emptyList(); + private List disabledCommands = Collections.emptyList(); @SuppressWarnings("unused") - public Settings() { + private Settings() { + } + + public String getLanguage() { + return language; + } + + public boolean doCheckForUpdates() { + return checkForUpdates; + } + + public boolean doDebugLogging() { + return debugLogging; + } + + public DatabaseType getDatabaseType() { + return databaseType; + } + + public String getMySqlHost() { + return mySqlHost; + } + + public int getMySqlPort() { + return mySqlPort; + } + + public String getMySqlDatabase() { + return mySqlDatabase; + } + + public String getMySqlUsername() { + return mySqlUsername; + } + + public String getMySqlPassword() { + return mySqlPassword; + } + + public String getMySqlConnectionParameters() { + return mySqlConnectionParameters; + } + + public int getMySqlConnectionPoolSize() { + return mySqlConnectionPoolSize; + } + + public int getMySqlConnectionPoolIdle() { + return mySqlConnectionPoolIdle; + } + + public long getMySqlConnectionPoolLifetime() { + return mySqlConnectionPoolLifetime; + } + + public long getMySqlConnectionPoolKeepAlive() { + return mySqlConnectionPoolKeepAlive; + } + + public long getMySqlConnectionPoolTimeout() { + return mySqlConnectionPoolTimeout; + } + + public Map getTableNames() { + return tableNames; + } + + public int getMaxHomes() { + return maxHomes; + } + + public int getMaxPublicHomes() { + return maxPublicHomes; + } + + public boolean doStackPermissionLimits() { + return stackPermissionLimits; + } + + public boolean isPermissionRestrictWarps() { + return permissionRestrictWarps; + } + + public boolean isOverwriteExistingHomesWarps() { + return overwriteExistingHomesWarps; + } + + public int getTeleportWarmupTime() { + return teleportWarmupTime; + } + + public MessageDisplayType getTeleportWarmupDisplay() { + return teleportWarmupDisplay; + } + + public int getTeleportRequestExpiryTime() { + return teleportRequestExpiryTime; + } + + public boolean isStrictTpaHereRequests() { + return strictTpaHereRequests; + } + + public boolean isAllowUnicodeNames() { + return allowUnicodeNames; + } + + public boolean isAllowUnicodeDescriptions() { + return allowUnicodeDescriptions; + } + + public boolean isBackCommandReturnByDeath() { + return backCommandReturnByDeath; + } + + public boolean isBackCommandSaveOnTeleportEvent() { + return backCommandSaveOnTeleportEvent; + } + + public int getListItemsPerPage() { + return listItemsPerPage; + } + + public boolean isAsynchronousTeleports() { + return asynchronousTeleports; + } + + public boolean isPlaySoundEffects() { + return playSoundEffects; + } + + public Map getSoundEffects() { + return soundEffects; + } + + public boolean isCrossServer() { + return crossServer; + } + + public MessengerType getMessengerType() { + return messengerType; + } + + public String getClusterId() { + return clusterId; + } + + public boolean isGlobalSpawn() { + return globalSpawn; + } + + public String getGlobalSpawnName() { + return globalSpawnName; + } + + public boolean isGlobalRespawning() { + return globalRespawning; + } + + public String getRedisHost() { + return redisHost; + } + + public int getRedisPort() { + return redisPort; + } + + public String getRedisPassword() { + return redisPassword; + } + + public boolean isRedisUseSsl() { + return redisUseSsl; + } + + public int getRtpCooldownLength() { + return rtpCooldownLength; + } + + public int getRtpRadius() { + return rtpRadius; + } + + public int getRtpSpawnRadius() { + return rtpSpawnRadius; + } + + public float getRtpDistributionMean() { + return rtpDistributionMean; + } + + public float getRtpDistributionStandardDeviation() { + return rtpDistributionStandardDeviation; + } + + public List getRtpRestrictedWorlds() { + return rtpRestrictedWorlds; + } + + public boolean isEconomy() { + return economy; + } + + public String getRedisEconomyName() { + return redisEconomyName; + } + + public int getFreeHomeSlots() { + return freeHomeSlots; + } + + public Map getEconomyCosts() { + return economyCosts; + } + + public boolean isDoMapHook() { + return doMapHook; + } + + public MappingPlugin getMappingPlugin() { + return mappingPlugin; + } + + public boolean isPublicHomesOnMap() { + return publicHomesOnMap; + } + + public boolean isWarpsOnMap() { + return warpsOnMap; + } + + public List getDisabledCommands() { + return disabledCommands; } /** diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index b712f856..72257989 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -17,7 +17,6 @@ import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** @@ -167,7 +166,7 @@ public abstract class Database { /** * Initialize the database and ensure tables are present; create tables if they do not exist. * - * @return A future returning void when complete + * @return {@code true} if done successfully */ public abstract boolean initialize(); @@ -175,9 +174,8 @@ public abstract class Database { * Execute a MySQL script file read as an InputStream * * @param inputStream The input stream to read the script from - * @return A future returning void when complete */ - public abstract CompletableFuture runScript(@NotNull InputStream inputStream, + public abstract void runScript(@NotNull InputStream inputStream, @NotNull Map replacements); /** @@ -224,9 +222,8 @@ public abstract class Database { * Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date * * @param user The {@link User} to ensure - * @return A future returning void when complete */ - public abstract CompletableFuture ensureUser(@NotNull User user); + public abstract void ensureUser(@NotNull User user); /** * Get {@link UserData} for a user by their Minecraft username (case-insensitive) @@ -234,7 +231,7 @@ public abstract class Database { * @param name Username of the {@link UserData} to get (case-insensitive) * @return A future returning an optional with the {@link UserData} present if they exist */ - public abstract CompletableFuture> getUserDataByName(@NotNull String name); + public abstract Optional getUserDataByName(@NotNull String name); /** * Get {@link UserData} for a user by their Minecraft account {@link UUID} @@ -242,7 +239,7 @@ public abstract class Database { * @param uuid Minecraft account {@link UUID} of the {@link UserData} to get * @return A future returning an optional with the {@link UserData} present if they exist */ - public abstract CompletableFuture> getUserData(@NotNull UUID uuid); + public abstract Optional getUserData(@NotNull UUID uuid); /** @@ -251,14 +248,14 @@ public abstract class Database { * @param user {@link User} to get the homes of * @return A future returning void when complete */ - public abstract CompletableFuture> getHomes(@NotNull User user); + public abstract List getHomes(@NotNull User user); /** * Get a list of all {@link Warp}s that have been set * * @return A future returning a list containing all {@link Warp}s */ - public abstract CompletableFuture> getWarps(); + public abstract List getWarps(); /** * Get a list of publicly-set {@link Warp}s on this {@link Server} @@ -267,16 +264,16 @@ public abstract class Database { * @return A future returning a list containing all {@link Warp}s set on this server * @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs */ - public final CompletableFuture> getLocalWarps(@NotNull HuskHomes plugin) { + public final List getLocalWarps(@NotNull HuskHomes plugin) { try { final Server server = plugin.getServerName(); - return getWarps().thenApplyAsync(warps -> warps.stream() + return getWarps().stream() .filter(warp -> warp.server.equals(server)) - .collect(Collectors.toList())); + .collect(Collectors.toList()); } catch (IllegalStateException e) { - return getWarps().thenApplyAsync(warps -> warps.stream() + return getWarps().stream() .filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.world))) - .collect(Collectors.toList())); + .collect(Collectors.toList()); } } @@ -285,7 +282,7 @@ public abstract class Database { * * @return A future returning a list containing all publicly-set {@link Home}s */ - public abstract CompletableFuture> getPublicHomes(); + public abstract List getPublicHomes(); /** * Get a list of publicly-set {@link Home}s on this {@link Server} @@ -294,16 +291,16 @@ public abstract class Database { * @return A future returning a list containing all publicly-set {@link Home}s on this server * @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs */ - public final CompletableFuture> getLocalPublicHomes(@NotNull HuskHomes plugin) { + public final List getLocalPublicHomes(@NotNull HuskHomes plugin) { try { final Server server = plugin.getServerName(); - return getPublicHomes().thenApplyAsync(homes -> homes.stream() + return getPublicHomes().stream() .filter(home -> home.server.equals(server)) - .collect(Collectors.toList())); + .collect(Collectors.toList()); } catch (IllegalStateException e) { - return plugin.getDatabase().getPublicHomes().thenApplyAsync(homes -> homes.stream() + return plugin.getDatabase().getPublicHomes().stream() .filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.world))) - .collect(Collectors.toList())); + .collect(Collectors.toList()); } } @@ -314,7 +311,7 @@ public abstract class Database { * @param homeName The case-insensitive name of the home to get * @return A future returning an optional with the {@link Home} present if it exists */ - public abstract CompletableFuture> getHome(@NotNull User user, @NotNull String homeName); + public abstract Optional getHome(@NotNull User user, @NotNull String homeName); /** * Get a {@link Home} by its unique id @@ -322,7 +319,7 @@ public abstract class Database { * @param uuid the {@link UUID} of the home to get * @return A future returning an optional with the {@link Home} present if it exists */ - public abstract CompletableFuture> getHome(@NotNull UUID uuid); + public abstract Optional getHome(@NotNull UUID uuid); /** * Get a {@link Warp} with the given name (case-insensitive) @@ -330,7 +327,7 @@ public abstract class Database { * @param warpName The case-insensitive name of the warp to get * @return A future returning an optional with the {@link Warp} present if it exists */ - public abstract CompletableFuture> getWarp(@NotNull String warpName); + public abstract Optional getWarp(@NotNull String warpName); /** * Get a {@link Warp} by its unique id @@ -338,7 +335,7 @@ public abstract class Database { * @param uuid the {@link UUID} of the warp to get * @return A future returning an optional with the {@link Warp} present if it exists */ - public abstract CompletableFuture> getWarp(@NotNull UUID uuid); + public abstract Optional getWarp(@NotNull UUID uuid); /** * Get the current {@link Teleport} being executed by the specified {@link OnlineUser} @@ -346,15 +343,14 @@ public abstract class Database { * @param onlineUser The {@link OnlineUser} to check * @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server */ - public abstract CompletableFuture> getCurrentTeleport(@NotNull OnlineUser onlineUser); + public abstract Optional getCurrentTeleport(@NotNull OnlineUser onlineUser); /** * Updates a user in the database with new {@link UserData} * * @param userData The {@link UserData} to update - * @return A future returning void when complete */ - public abstract CompletableFuture updateUserData(@NotNull UserData userData); + public abstract void updateUserData(@NotNull UserData userData); /** * Sets or clears the current {@link Teleport} being executed by a {@link User} @@ -362,9 +358,8 @@ public abstract class Database { * @param user The {@link User} to set the current teleport of. * Pass as {@code null} to clear the player's current teleport.

* @param teleport The {@link Teleport} to set as their current cross-server teleport - * @return A future returning void when complete */ - public abstract CompletableFuture setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport); + public abstract void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport); /** * Get the last teleport {@link Position} of a specified {@link User} @@ -372,16 +367,15 @@ public abstract class Database { * @param user The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getLastPosition(@NotNull User user); + public abstract Optional getLastPosition(@NotNull User user); /** * Sets the last teleport {@link Position} of a {@link User} * * @param user The {@link User} to set the last position of * @param position The {@link Position} to set as their last position - * @return A future returning void when complete */ - public abstract CompletableFuture setLastPosition(@NotNull User user, @NotNull Position position); + public abstract void setLastPosition(@NotNull User user, @NotNull Position position); /** * Get the offline {@link Position} of a specified {@link User} @@ -389,16 +383,15 @@ public abstract class Database { * @param user The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getOfflinePosition(@NotNull User user); + public abstract Optional getOfflinePosition(@NotNull User user); /** * Sets the offline {@link Position} of a {@link User} * * @param user The {@link User} to set the offline position of * @param position The {@link Position} to set as their offline position - * @return A future returning void when complete */ - public abstract CompletableFuture setOfflinePosition(@NotNull User user, @NotNull Position position); + public abstract void setOfflinePosition(@NotNull User user, @NotNull Position position); /** * Get the respawn {@link Position} of a specified {@link User} @@ -406,7 +399,7 @@ public abstract class Database { * @param user The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getRespawnPosition(@NotNull User user); + public abstract Optional getRespawnPosition(@NotNull User user); /** * Sets or clears the respawn {@link Position} of a {@link User} @@ -414,33 +407,29 @@ public abstract class Database { * @param user The {@link User} to set the respawn position of * @param position The {@link Position} to set as their respawn position * Pass as {@code null} to clear the player's current respawn position.

- * @return A future returning void when complete */ - public abstract CompletableFuture setRespawnPosition(@NotNull User user, @Nullable Position position); + public abstract void setRespawnPosition(@NotNull User user, @Nullable Position position); /** * Sets or updates a {@link Home} into the home data table on the database. * * @param home The {@link Home} to set - or update - in the database. - * @return A future returning void when complete */ - public abstract CompletableFuture saveHome(@NotNull Home home); + public abstract void saveHome(@NotNull Home home); /** * Sets or updates a {@link Warp} into the warp data table on the database. * * @param warp The {@link Warp} to set - or update - in the database. - * @return A future returning void when complete */ - public abstract CompletableFuture saveWarp(@NotNull Warp warp); + public abstract void saveWarp(@NotNull Warp warp); /** * Deletes a {@link Home} by the given unique id from the home table on the database. * * @param uuid {@link UUID} of the home to delete - * @return A future returning void when complete */ - public abstract CompletableFuture deleteHome(@NotNull UUID uuid); + public abstract void deleteHome(@NotNull UUID uuid); /** * Deletes all {@link Home}s of a {@link User} from the home table on the database. @@ -448,22 +437,21 @@ public abstract class Database { * @param user The {@link User} to delete all homes of * @return A future returning an integer; the number of deleted homes */ - public abstract CompletableFuture deleteAllHomes(@NotNull User user); + public abstract int deleteAllHomes(@NotNull User user); /** * Deletes a {@link Warp} by the given unique id from the warp table on the database. * * @param uuid {@link UUID} of the warp to delete - * @return A future returning void when complete */ - public abstract CompletableFuture deleteWarp(@NotNull UUID uuid); + public abstract void deleteWarp(@NotNull UUID uuid); /** * Deletes all {@link Warp}s set on the database table * * @return A future returning an integer; the number of deleted warps */ - public abstract CompletableFuture deleteAllWarps(); + public abstract int deleteAllWarps(); /** * Close any remaining connection to the database source diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index 3ab61e44..c330103b 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -16,7 +16,6 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; /** @@ -43,17 +42,17 @@ public class MySqlDatabase extends Database { public MySqlDatabase(@NotNull HuskHomes plugin) { super(plugin); - this.host = plugin.getSettings().mySqlHost; - this.port = plugin.getSettings().mySqlPort; - this.database = plugin.getSettings().mySqlDatabase; - this.username = plugin.getSettings().mySqlUsername; - this.password = plugin.getSettings().mySqlPassword; - this.connectionParameters = plugin.getSettings().mySqlConnectionParameters; - this.connectionPoolSize = plugin.getSettings().mySqlConnectionPoolSize; - this.connectionPoolIdle = plugin.getSettings().mySqlConnectionPoolIdle; - this.connectionPoolLifetime = plugin.getSettings().mySqlConnectionPoolLifetime; - this.connectionPoolKeepAlive = plugin.getSettings().mySqlConnectionPoolKeepAlive; - this.connectionPoolTimeout = plugin.getSettings().mySqlConnectionPoolTimeout; + this.host = plugin.getSettings().getMySqlHost(); + this.port = plugin.getSettings().getMySqlPort(); + this.database = plugin.getSettings().getMySqlDatabase(); + this.username = plugin.getSettings().getMySqlUsername(); + this.password = plugin.getSettings().getMySqlPassword(); + this.connectionParameters = plugin.getSettings().getMySqlConnectionParameters(); + this.connectionPoolSize = plugin.getSettings().getMySqlConnectionPoolSize(); + this.connectionPoolIdle = plugin.getSettings().getMySqlConnectionPoolIdle(); + this.connectionPoolLifetime = plugin.getSettings().getMySqlConnectionPoolLifetime(); + this.connectionPoolKeepAlive = plugin.getSettings().getMySqlConnectionPoolKeepAlive(); + this.connectionPoolTimeout = plugin.getSettings().getMySqlConnectionPoolTimeout(); } /** @@ -121,24 +120,22 @@ public class MySqlDatabase extends Database { } @Override - public CompletableFuture runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - final String[] scriptString; - scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; - replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); - connection.setAutoCommit(false); - try (Statement statement = connection.createStatement()) { - for (String statementString : scriptString[0].split(";")) { - statement.addBatch(statementString); - } - statement.executeBatch(); + public void runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { + try (Connection connection = getConnection()) { + final String[] scriptString; + scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; + replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + for (String statementString : scriptString[0].split(";")) { + statement.addBatch(statementString); } - } catch (IOException | SQLException e) { - getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); - throw new RuntimeException(e); + statement.executeBatch(); } - }); + } catch (IOException | SQLException e) { + getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); + throw new RuntimeException(e); + } } @Override @@ -244,848 +241,802 @@ public class MySqlDatabase extends Database { } @Override - public CompletableFuture ensureUser(@NotNull User onlineUser) { - return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser -> - optionalUser.ifPresentOrElse(existingUserData -> { - if (!existingUserData.getUsername().equals(onlineUser.username)) { - // Update a player's name if it has changed in the database - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `username`=? - WHERE `uuid`=?"""))) { - - statement.setString(1, onlineUser.username); - statement.setString(2, existingUserData.getUserUuid().toString()); - statement.executeUpdate(); - } - getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.username + ")"); - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); - } - } - }, - () -> { - // Insert new player data into the database - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) - VALUES (?,?);"""))) { - - statement.setString(1, onlineUser.uuid.toString()); - statement.setString(2, onlineUser.username); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); - } - }))); - } - - @Override - public CompletableFuture> getUserDataByName(@NotNull String name) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `username`=?"""))) { - statement.setString(1, name); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new UserData( - new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getUserData(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `uuid`=?"""))) { - - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new UserData( - new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getHomes(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - final List userHomes = new ArrayList<>(); - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - ORDER BY `name`;"""))) { - - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - user, - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); - } - return userHomes; - }); - } - - @Override - public CompletableFuture> getWarps() { - return CompletableFuture.supplyAsync(() -> { - final List warps = new ArrayList<>(); - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - ORDER BY `name`;"""))) { - - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - warps.add(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); - } - return warps; - }); - } - - @Override - public CompletableFuture> getPublicHomes() { - return CompletableFuture.supplyAsync(() -> { - final List userHomes = new ArrayList<>(); - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `public`=true - ORDER BY `name`;"""))) { - - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); - } - return userHomes; - }); - } - - @Override - public CompletableFuture> getHome(@NotNull User user, @NotNull String homeName) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - AND `name`=?;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, homeName); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getHome(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getWarp(@NotNull String warpName) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `name`=?;"""))) { - statement.setString(1, warpName); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getWarp(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getCurrentTeleport(@NotNull OnlineUser onlineUser) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` - FROM `%teleports_table%` - INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` - WHERE `player_uuid`=?"""))) { - statement.setString(1, onlineUser.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Teleport.builder(plugin, onlineUser) - .setTarget(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))) - .setType(TeleportType.getTeleportType(resultSet.getInt("type")) - .orElse(TeleportType.TELEPORT)) - .doUpdateLastPosition(false) - .toTeleport() - .join()); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture updateUserData(@NotNull UserData userData) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? - WHERE `uuid`=?"""))) { - - statement.setInt(1, userData.homeSlots()); - statement.setBoolean(2, userData.ignoringTeleports()); - statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown())); - statement.setString(4, userData.getUserUuid().toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); - } - }); - } - - @Override - public CompletableFuture setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - // Clear the user's current teleport - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `id`=( - SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? - );"""))) { - deleteStatement.setString(1, user.uuid.toString()); - deleteStatement.executeUpdate(); - } - - // Set the user's teleport into the database (if it's not null) - if (teleport != null && teleport.target != null) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) - VALUES (?,?,?);"""))) { - statement.setString(1, user.uuid.toString()); - statement.setInt(2, setPosition(teleport.target, connection)); - statement.setInt(3, teleport.type.typeId); - - statement.executeUpdate(); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture> getLastPosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setLastPosition(@NotNull User user, @NotNull Position position) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `last_position` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - // Update the last position - updatePosition(resultSet.getInt("last_position"), position, connection); - } else { - // Set the last position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `last_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); - } - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture> getOfflinePosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setOfflinePosition(@NotNull User user, @NotNull Position position) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `offline_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - // Update the offline position - updatePosition(resultSet.getInt("offline_position"), position, connection); - } else { - // Set the offline position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `offline_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); - } - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture> getRespawnPosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setRespawnPosition(@NotNull User user, @Nullable Position position) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `respawn_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - if (position == null) { - // Delete a respawn position - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `id`=( - SELECT `respawn_position` - FROM `%players_table%` - WHERE `%players_table%`.`uuid`=? - );"""))) { - deleteStatement.setString(1, user.uuid.toString()); - deleteStatement.executeUpdate(); - } - } else { - // Update the respawn position - updatePosition(resultSet.getInt("respawn_position"), position, connection); - } - } else { - if (position != null) { - // Set a respawn position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + public void ensureUser(@NotNull User onlineUser) { + getUserData(onlineUser.uuid).ifPresentOrElse(existingUserData -> { + if (!existingUserData.getUsername().equals(onlineUser.username)) { + // Update a player's name if it has changed in the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" UPDATE `%players_table%` - SET `respawn_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); + SET `username`=? + WHERE `uuid`=?"""))) { + + statement.setString(1, onlineUser.username); + statement.setString(2, existingUserData.getUserUuid().toString()); + statement.executeUpdate(); } + getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.username + ")"); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); } } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture saveHome(@NotNull Home home) { - return CompletableFuture.runAsync(() -> getHome(home.uuid) - .thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> { - try (Connection connection = getConnection()) { - // Update the home's saved position, including metadata - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%homes_table%` - WHERE `uuid`=?;"""))) { - statement.setString(1, home.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection); - } - } - - // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%homes_table%` - SET `public`=? - WHERE `uuid`=?;"""))) { - statement.setBoolean(1, home.isPublic); - statement.setString(2, home.uuid.toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, - "Failed to update a home in the database for " + home.owner.username, e); - } - }, () -> { + }, + () -> { + // Insert new player data into the database try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) - VALUES (?,?,?,?);"""))) { - statement.setString(1, home.uuid.toString()); - statement.setInt(2, setSavedPosition(home, connection)); - statement.setString(3, home.owner.uuid.toString()); - statement.setBoolean(4, home.isPublic); - - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, - "Failed to set a home to the database for " + home.owner.username, e); - } - }))); - } - - @Override - public CompletableFuture saveWarp(@NotNull Warp warp) { - return CompletableFuture.runAsync(() -> getWarp(warp.uuid) - .thenAccept(existingHome -> existingHome.ifPresentOrElse(presentWarp -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%warps_table%` - WHERE `uuid`=?;"""))) { - statement.setString(1, warp.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); - } - }, () -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + INSERT INTO `%players_table%` (`uuid`,`username`) VALUES (?,?);"""))) { - statement.setString(1, warp.uuid.toString()); - statement.setInt(2, setSavedPosition(warp, connection)); + statement.setString(1, onlineUser.uuid.toString()); + statement.setString(2, onlineUser.username); statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); + getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); } - }))); + }); } @Override - public CompletableFuture deleteHome(@NotNull UUID uuid) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( - SELECT `saved_position_id` - FROM `%homes_table%` - WHERE `uuid`=? - ) - );"""))) { - statement.setString(1, uuid.toString()); + public Optional getUserDataByName(@NotNull String name) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + FROM `%players_table%` + WHERE `username`=?"""))) { + statement.setString(1, name); - statement.executeUpdate(); + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new UserData( + new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests"), + resultSet.getTimestamp("rtp_cooldown").toInstant())); } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); } - }); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + } + return Optional.empty(); } @Override - public CompletableFuture deleteAllHomes(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( - SELECT `saved_position_id` - FROM `%homes_table%` - WHERE `owner_uuid`=? - ) - );"""))) { + public Optional getUserData(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + FROM `%players_table%` + WHERE `uuid`=?"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new UserData( + new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests"), + resultSet.getTimestamp("rtp_cooldown").toInstant())); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + } + return Optional.empty(); + } + + @Override + public List getHomes(@NotNull User user) { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + ORDER BY `name`;"""))) { + + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); + } + return userHomes; + } + + @Override + public List getWarps() { + final List warps = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + warps.add(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); + } + return warps; + } + + @Override + public List getPublicHomes() { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `public`=true + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); + } + return userHomes; + } + + @Override + public Optional getHome(@NotNull User user, @NotNull String homeName) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + AND `name`=?;"""))) { + statement.setString(1, user.uuid.toString()); + statement.setString(2, homeName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home", e); + } + return Optional.empty(); + } + + @Override + public Optional getHome(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `%homes_table%`.`uuid`=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull String warpName) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `name`=?;"""))) { + statement.setString(1, warpName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `%warps_table%`.uuid=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` + FROM `%teleports_table%` + INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + WHERE `player_uuid`=?"""))) { + statement.setString(1, onlineUser.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Teleport.builder(plugin, onlineUser) + .setTarget(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))) + .setType(TeleportType.getTeleportType(resultSet.getInt("type")) + .orElse(TeleportType.TELEPORT)) + .doUpdateLastPosition(false) + .toTeleport() + .join()); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); + } + return Optional.empty(); + } + + @Override + public void updateUserData(@NotNull UserData userData) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? + WHERE `uuid`=?"""))) { + + statement.setInt(1, userData.homeSlots()); + statement.setBoolean(2, userData.ignoringTeleports()); + statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown())); + statement.setString(4, userData.getUserUuid().toString()); + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); + } + } + + @Override + public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { + try (Connection connection = getConnection()) { + // Clear the user's current teleport + try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `destination_id` + FROM `%teleports_table%` + WHERE `%teleports_table%`.`player_uuid`=? + );"""))) { + deleteStatement.setString(1, user.uuid.toString()); + deleteStatement.executeUpdate(); + } + + // Set the user's teleport into the database (if it's not null) + if (teleport != null && teleport.target != null) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + VALUES (?,?,?);"""))) { statement.setString(1, user.uuid.toString()); - return statement.executeUpdate(); + statement.setInt(2, setPosition(teleport.target, connection)); + statement.setInt(3, teleport.type.typeId); + + statement.executeUpdate(); } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); } - return 0; - }); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e); + } } @Override - public CompletableFuture deleteWarp(@NotNull UUID uuid) { - return CompletableFuture.runAsync(() -> { + public Optional getLastPosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setLastPosition(@NotNull User user, @NotNull Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `last_position` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the last position + updatePosition(resultSet.getInt("last_position"), position, connection); + } else { + // Set the last position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `last_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); + } + } + + @Override + public Optional getOfflinePosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setOfflinePosition(@NotNull User user, @NotNull Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `offline_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the offline position + updatePosition(resultSet.getInt("offline_position"), position, connection); + } else { + // Set the offline position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `offline_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); + } + } + + @Override + public Optional getRespawnPosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setRespawnPosition(@NotNull User user, @Nullable Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `respawn_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + if (position == null) { + // Delete a respawn position + try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `respawn_position` + FROM `%players_table%` + WHERE `%players_table%`.`uuid`=? + );"""))) { + deleteStatement.setString(1, user.uuid.toString()); + deleteStatement.executeUpdate(); + } + } else { + // Update the respawn position + updatePosition(resultSet.getInt("respawn_position"), position, connection); + } + } else { + if (position != null) { + // Set a respawn position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `respawn_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); + } + } + + @Override + public void saveHome(@NotNull Home home) { + getHome(home.uuid).ifPresentOrElse(presentHome -> { + try (Connection connection = getConnection()) { + // Update the home's saved position, including metadata + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `saved_position_id` FROM `%homes_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, home.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection); + } + } + + // Update the home privacy + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%homes_table%` + SET `public`=? + WHERE `uuid`=?;"""))) { + statement.setBoolean(1, home.isPublic); + statement.setString(2, home.uuid.toString()); + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, + "Failed to update a home in the database for " + home.owner.username, e); + } + }, () -> { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( - SELECT `saved_position_id` - FROM `%warps_table%` - WHERE `uuid`=? - ) - );"""))) { - statement.setString(1, uuid.toString()); + INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, home.uuid.toString()); + statement.setInt(2, setSavedPosition(home, connection)); + statement.setString(3, home.owner.uuid.toString()); + statement.setBoolean(4, home.isPublic); statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); + getLogger().log(Level.SEVERE, + "Failed to set a home to the database for " + home.owner.username, e); } }); } @Override - public CompletableFuture deleteAllWarps() { - return CompletableFuture.supplyAsync(() -> { + public void saveWarp(@NotNull Warp warp) { + getWarp(warp.uuid).ifPresentOrElse(presentWarp -> { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( - SELECT `saved_position_id` - FROM `%warps_table%` - ) - );"""))) { - return statement.executeUpdate(); + SELECT `saved_position_id` FROM `%warps_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, warp.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection); + } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); + } + }, () -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + VALUES (?,?);"""))) { + statement.setString(1, warp.uuid.toString()); + statement.setInt(2, setSavedPosition(warp, connection)); + + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); } - return 0; }); } + @Override + public void deleteHome(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); + + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); + } + } + + @Override + public int deleteAllHomes(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `owner_uuid`=? + ) + );"""))) { + + statement.setString(1, user.uuid.toString()); + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); + } + return 0; + } + + @Override + public void deleteWarp(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%warps_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); + + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); + } + } + + @Override + public int deleteAllWarps() { + + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%warps_table%` + ) + );"""))) { + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + } + return 0; + } + @Override public void terminate() { if (dataSource != null) { diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index bafda450..b90df952 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -17,7 +17,6 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; /** @@ -109,28 +108,26 @@ public class SqLiteDatabase extends Database { } @Override - public CompletableFuture runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { - return CompletableFuture.runAsync(() -> { - try { - final String[] scriptString; - scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; - replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); - final boolean autoCommit = getConnection().getAutoCommit(); + public void runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { + try { + final String[] scriptString; + scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; + replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); + final boolean autoCommit = getConnection().getAutoCommit(); - // Execute batched SQLite script - getConnection().setAutoCommit(false); - try (Statement statement = getConnection().createStatement()) { - for (String statementString : scriptString[0].split(";")) { - statement.addBatch(statementString); - } - statement.executeBatch(); + // Execute batched SQLite script + getConnection().setAutoCommit(false); + try (Statement statement = getConnection().createStatement()) { + for (String statementString : scriptString[0].split(";")) { + statement.addBatch(statementString); } - getConnection().setAutoCommit(autoCommit); - } catch (IOException | SQLException e) { - getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); - throw new RuntimeException(e); + statement.executeBatch(); } - }); + getConnection().setAutoCommit(autoCommit); + } catch (IOException | SQLException e) { + getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); + throw new RuntimeException(e); + } } @Override @@ -240,723 +237,673 @@ public class SqLiteDatabase extends Database { } @Override - public CompletableFuture ensureUser(@NotNull User onlineUser) { - return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser -> - optionalUser.ifPresentOrElse(existingUser -> { - if (!existingUser.getUsername().equals(onlineUser.username)) { - // Update a player's name if it has changed in the database - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `username`=? - WHERE `uuid`=?"""))) { + public void ensureUser(@NotNull User onlineUser) { + getUserData(onlineUser.uuid).ifPresentOrElse(existingUser -> { + if (!existingUser.getUsername().equals(onlineUser.username)) { + // Update a player's name if it has changed in the database + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `username`=? + WHERE `uuid`=?"""))) { - statement.setString(1, onlineUser.username); - statement.setString(2, existingUser.getUserUuid().toString()); - statement.executeUpdate(); - } - getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.username + ")"); - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); - } + statement.setString(1, onlineUser.username); + statement.setString(2, existingUser.getUserUuid().toString()); + statement.executeUpdate(); } - }, - () -> { - // Insert new player data into the database - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) - VALUES (?,?);"""))) { - - statement.setString(1, onlineUser.uuid.toString()); - statement.setString(2, onlineUser.username); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); - } - }))); - } - - @Override - public CompletableFuture> getUserDataByName(@NotNull String name) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `username`=?"""))) { - statement.setString(1, name); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new UserData( - new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); + getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.username + ")"); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); + } } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); - } - return Optional.empty(); - }); - } + }, + () -> { + // Insert new player data into the database + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%players_table%` (`uuid`,`username`) + VALUES (?,?);"""))) { - @Override - public CompletableFuture> getUserData(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` - FROM `%players_table%` - WHERE `uuid`=?"""))) { - - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new UserData( - new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username")), - resultSet.getInt("home_slots"), - resultSet.getBoolean("ignoring_requests"), - resultSet.getTimestamp("rtp_cooldown").toInstant())); + statement.setString(1, onlineUser.uuid.toString()); + statement.setString(2, onlineUser.username); + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); - } - return Optional.empty(); - }); + }); } @Override - public CompletableFuture> getHomes(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - final List userHomes = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - ORDER BY `name`;"""))) { + public Optional getUserDataByName(@NotNull String name) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + FROM `%players_table%` + WHERE `username`=?"""))) { + statement.setString(1, name); - statement.setString(1, user.uuid.toString()); + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new UserData( + new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests"), + resultSet.getTimestamp("rtp_cooldown").toInstant())); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + } + return Optional.empty(); + } - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(new Home(resultSet.getDouble("x"), + @Override + public Optional getUserData(@NotNull UUID uuid) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` + FROM `%players_table%` + WHERE `uuid`=?"""))) { + + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new UserData( + new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests"), + resultSet.getTimestamp("rtp_cooldown").toInstant())); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + } + return Optional.empty(); + } + + @Override + public List getHomes(@NotNull User user) { + final List userHomes = new ArrayList<>(); + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + ORDER BY `name`;"""))) { + + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); + } + return userHomes; + } + + @Override + public List getWarps() { + final List warps = new ArrayList<>(); + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + warps.add(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); + } + return warps; + } + + @Override + public List getPublicHomes() { + final List userHomes = new ArrayList<>(); + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `public`=true + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); + } + return userHomes; + } + + @Override + public Optional getHome(@NotNull User user, @NotNull String homeName) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + AND `name`=?;"""))) { + statement.setString(1, user.uuid.toString()); + statement.setString(2, homeName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home", e); + } + return Optional.empty(); + } + + @Override + public Optional getHome(@NotNull UUID uuid) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `%homes_table%`.`uuid`=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull String warpName) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `name`=?;"""))) { + statement.setString(1, warpName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull UUID uuid) { + try { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `%warps_table%`.uuid=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { + + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` + FROM `%teleports_table%` + INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + WHERE `player_uuid`=?"""))) { + statement.setString(1, onlineUser.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Teleport.builder(plugin, onlineUser) + .setTarget(new Position(resultSet.getDouble("x"), resultSet.getDouble("y"), resultSet.getDouble("z"), resultSet.getFloat("yaw"), resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - user, - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); + new Server(resultSet.getString("server_name")))) + .setType(TeleportType.getTeleportType(resultSet.getInt("type")) + .orElse(TeleportType.TELEPORT)) + .doUpdateLastPosition(false) + .toTeleport() + .join()); } - return userHomes; - }); + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); + } + return Optional.empty(); } @Override - public CompletableFuture> getWarps() { - return CompletableFuture.supplyAsync(() -> { - final List warps = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - ORDER BY `name`;"""))) { + public void updateUserData(@NotNull UserData userData) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? + WHERE `uuid`=?"""))) { - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - warps.add(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); - } - return warps; - }); + statement.setInt(1, userData.homeSlots()); + statement.setBoolean(2, userData.ignoringTeleports()); + statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown())); + statement.setString(4, userData.getUserUuid().toString()); + statement.executeUpdate(); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); + } } @Override - public CompletableFuture> getPublicHomes() { - return CompletableFuture.supplyAsync(() -> { - final List userHomes = new ArrayList<>(); - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `public`=true - ORDER BY `name`;"""))) { - - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - userHomes.add(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); - } - return userHomes; - }); - } - - @Override - public CompletableFuture> getHome(@NotNull User user, @NotNull String homeName) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `owner_uuid`=? - AND `name`=?;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, homeName); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getHome(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Home(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("home_uuid")), - new User(UUID.fromString(resultSet.getString("owner_uuid")), - resultSet.getString("owner_username")), - resultSet.getBoolean("public"))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getWarp(@NotNull String warpName) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `name`=?;"""))) { - statement.setString(1, warpName); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getWarp(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { - statement.setString(1, uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Warp(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")), - new PositionMeta(resultSet.getString("name"), - resultSet.getString("description"), - resultSet.getTimestamp("timestamp").toInstant(), - resultSet.getString("tags")), - UUID.fromString(resultSet.getString("warp_uuid")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture> getCurrentTeleport(@NotNull OnlineUser onlineUser) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` + public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { + // Clear the user's current teleport + try { + try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `destination_id` FROM `%teleports_table%` - INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` - WHERE `player_uuid`=?"""))) { - statement.setString(1, onlineUser.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(Teleport.builder(plugin, onlineUser) - .setTarget(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))) - .setType(TeleportType.getTeleportType(resultSet.getInt("type")) - .orElse(TeleportType.TELEPORT)) - .doUpdateLastPosition(false) - .toTeleport() - .join()); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); + WHERE `%teleports_table%`.`player_uuid`=? + );"""))) { + deleteStatement.setString(1, user.uuid.toString()); + deleteStatement.executeUpdate(); } - return Optional.empty(); - }); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e); + } + + // Set the user's teleport into the database (if it's not null) + if (teleport != null && teleport.target != null) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + VALUES (?,?,?);"""))) { + statement.setString(1, user.uuid.toString()); + statement.setInt(2, setPosition(teleport.target, connection)); + statement.setInt(3, teleport.type.typeId); + + statement.executeUpdate(); + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e); + } + } } @Override - public CompletableFuture updateUserData(@NotNull UserData userData) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? - WHERE `uuid`=?"""))) { + public Optional getLastPosition(@NotNull User user) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); - statement.setInt(1, userData.homeSlots()); - statement.setBoolean(2, userData.ignoringTeleports()); - statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown())); - statement.setString(4, userData.getUserUuid().toString()); + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setLastPosition(@NotNull User user, @NotNull Position position) { + + try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `last_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the last position + updatePosition(resultSet.getInt("last_position"), position, connection); + } else { + // Set the last position + try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `last_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); + } + } + + @Override + public Optional getOfflinePosition(@NotNull User user) { + + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setOfflinePosition(@NotNull User user, @NotNull Position position) { + try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `offline_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the offline position + updatePosition(resultSet.getInt("offline_position"), position, connection); + } else { + // Set the offline position + try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `offline_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); + } + } + + @Override + public Optional getRespawnPosition(@NotNull User user) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Position(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")))); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); + } + return Optional.empty(); + } + + @Override + public void setRespawnPosition(@NotNull User user, @Nullable Position position) { + try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `respawn_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.uuid.toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + if (position == null) { + // Delete a respawn position + try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `respawn_position` + FROM `%players_table%` + WHERE `%players_table%`.`uuid`=? + );"""))) { + deleteStatement.setString(1, user.uuid.toString()); + deleteStatement.executeUpdate(); + } + } else { + // Update the respawn position + updatePosition(resultSet.getInt("respawn_position"), position, connection); + } + } else { + if (position != null) { + // Set a respawn position + try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `respawn_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.uuid.toString()); + updateStatement.executeUpdate(); + } + } + } + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); + } + } + + @Override + public void saveHome(@NotNull Home home) { + getHome(home.uuid).ifPresentOrElse(presentHome -> { + try { + // Update the home's saved position, including metadata + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + SELECT `saved_position_id` FROM `%homes_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, home.uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection); + } + } + + // Update the home privacy + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%homes_table%` + SET `public`=? + WHERE `uuid`=?;"""))) { + statement.setBoolean(1, home.isPublic); + statement.setString(2, home.uuid.toString()); statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); + getLogger().log(Level.SEVERE, + "Failed to update a home in the database for " + home.owner.username, e); } - }); - } + }, () -> { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, home.uuid.toString()); + statement.setInt(2, setSavedPosition(home, connection)); + statement.setString(3, home.owner.uuid.toString()); + statement.setBoolean(4, home.isPublic); - @Override - public CompletableFuture setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { - return CompletableFuture.runAsync(() -> { - // Clear the user's current teleport - try { - try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `id`=( - SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? - );"""))) { - deleteStatement.setString(1, user.uuid.toString()); - deleteStatement.executeUpdate(); - } + statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e); - } - - // Set the user's teleport into the database (if it's not null) - if (teleport != null && teleport.target != null) { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) - VALUES (?,?,?);"""))) { - statement.setString(1, user.uuid.toString()); - statement.setInt(2, setPosition(teleport.target, connection)); - statement.setInt(3, teleport.type.typeId); - - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e); - } + e.printStackTrace(); + getLogger().log(Level.SEVERE, + "Failed to set a home to the database for " + home.owner.username, e); } }); } @Override - public CompletableFuture> getLastPosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setLastPosition(@NotNull User user, @NotNull Position position) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `last_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - // Update the last position - updatePosition(resultSet.getInt("last_position"), position, connection); - } else { - // Set the last position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `last_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); - } - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture> getOfflinePosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setOfflinePosition(@NotNull User user, @NotNull Position position) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `offline_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - // Update the offline position - updatePosition(resultSet.getInt("offline_position"), position, connection); - } else { - // Set the offline position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `offline_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); - } - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture> getRespawnPosition(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` - WHERE `uuid`=?"""))) { - statement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new Position(resultSet.getDouble("x"), - resultSet.getDouble("y"), - resultSet.getDouble("z"), - resultSet.getFloat("yaw"), - resultSet.getFloat("pitch"), - new World(resultSet.getString("world_name"), - UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); - } - return Optional.empty(); - }); - } - - @Override - public CompletableFuture setRespawnPosition(@NotNull User user, @Nullable Position position) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `respawn_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` - WHERE `uuid`=?;"""))) { - queryStatement.setString(1, user.uuid.toString()); - - final ResultSet resultSet = queryStatement.executeQuery(); - if (resultSet.next()) { - if (position == null) { - // Delete a respawn position - try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `id`=( - SELECT `respawn_position` - FROM `%players_table%` - WHERE `%players_table%`.`uuid`=? - );"""))) { - deleteStatement.setString(1, user.uuid.toString()); - deleteStatement.executeUpdate(); - } - } else { - // Update the respawn position - updatePosition(resultSet.getInt("respawn_position"), position, connection); - } - } else { - if (position != null) { - // Set a respawn position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` - SET `respawn_position`=? - WHERE `uuid`=?;"""))) { - updateStatement.setInt(1, setPosition(position, connection)); - updateStatement.setString(2, user.uuid.toString()); - updateStatement.executeUpdate(); - } - } - } - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); - } - }); - } - - @Override - public CompletableFuture saveHome(@NotNull Home home) { - return CompletableFuture.runAsync(() -> getHome(home.uuid) - .thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> { - try { - // Update the home's saved position, including metadata - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%homes_table%` - WHERE `uuid`=?;"""))) { - statement.setString(1, home.uuid.toString()); - - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection); - } - } - - // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%homes_table%` - SET `public`=? - WHERE `uuid`=?;"""))) { - statement.setBoolean(1, home.isPublic); - statement.setString(2, home.uuid.toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, - "Failed to update a home in the database for " + home.owner.username, e); - } - }, () -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) - VALUES (?,?,?,?);"""))) { - statement.setString(1, home.uuid.toString()); - statement.setInt(2, setSavedPosition(home, connection)); - statement.setString(3, home.owner.uuid.toString()); - statement.setBoolean(4, home.isPublic); - - statement.executeUpdate(); - } - } catch (SQLException e) { - e.printStackTrace(); - getLogger().log(Level.SEVERE, - "Failed to set a home to the database for " + home.owner.username, e); - } - }))); - } - - @Override - public CompletableFuture saveWarp(@NotNull Warp warp) { - return CompletableFuture.runAsync(() -> getWarp(warp.uuid) - .thenAccept(existingHome -> existingHome.ifPresentOrElse(presentWarp -> { + public void saveWarp(@NotNull Warp warp) { + getWarp(warp.uuid) + .ifPresentOrElse(presentWarp -> { try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" SELECT `saved_position_id` FROM `%warps_table%` @@ -972,118 +919,100 @@ public class SqLiteDatabase extends Database { getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); } }, () -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) - VALUES (?,?);"""))) { - statement.setString(1, warp.uuid.toString()); - statement.setInt(2, setSavedPosition(warp, connection)); + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + VALUES (?,?);"""))) { + statement.setString(1, warp.uuid.toString()); + statement.setInt(2, setSavedPosition(warp, connection)); - statement.executeUpdate(); - } + statement.executeUpdate(); } catch (SQLException e) { getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); } - }))); + }); } @Override - public CompletableFuture deleteHome(@NotNull UUID uuid) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( - SELECT `saved_position_id` - FROM `%homes_table%` - WHERE `uuid`=? - ) - );"""))) { - statement.setString(1, uuid.toString()); + public void deleteHome(@NotNull UUID uuid) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); - } - }); + statement.executeUpdate(); + + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); + } } @Override - public CompletableFuture deleteAllHomes(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( - SELECT `saved_position_id` - FROM `%homes_table%` - WHERE `owner_uuid`=? - ) - );"""))) { + public int deleteAllHomes(@NotNull User user) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `owner_uuid`=? + ) + );"""))) { - statement.setString(1, user.uuid.toString()); - return statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); - } - return 0; - }); + statement.setString(1, user.uuid.toString()); + return statement.executeUpdate(); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); + } + return 0; } @Override - public CompletableFuture deleteWarp(@NotNull UUID uuid) { - return CompletableFuture.runAsync(() -> { - try { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( - SELECT `saved_position_id` - FROM `%warps_table%` - WHERE `uuid`=? - ) - );"""))) { - statement.setString(1, uuid.toString()); - - statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); - } - }); + public void deleteWarp(@NotNull UUID uuid) { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%warps_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); + statement.executeUpdate(); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); + } } @Override - public CompletableFuture deleteAllWarps() { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( - SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( - SELECT `saved_position_id` - FROM `%warps_table%` - ) - );"""))) { - return statement.executeUpdate(); - } - } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); - } - return 0; - }); + public int deleteAllWarps() { + try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%warps_table%` + ) + );"""))) { + return statement.executeUpdate(); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + } + return 0; } @Override diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java index 18c398e7..9229413c 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java @@ -39,11 +39,11 @@ public class BlueMapHook extends MapHook { // Create marker sets plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.uuid) .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> { - if (plugin.getSettings().publicHomesOnMap) { + if (plugin.getSettings().isPublicHomesOnMap()) { map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, MarkerSet.builder().label("Public Homes").build()); } - if (plugin.getSettings().warpsOnMap) { + if (plugin.getSettings().isWarpsOnMap()) { map.getMarkerSets().put(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, MarkerSet.builder().label("Warps").build()); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java index 80bcac59..e8f12baf 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java @@ -26,13 +26,15 @@ public abstract class MapHook extends PluginHook { @Override public final boolean initialize() { initializeMap().thenRun(() -> { - if (plugin.getSettings().publicHomesOnMap) { - plugin.getDatabase().getLocalPublicHomes(plugin) - .thenAcceptAsync(homes -> homes.forEach(this::updateHome)); + if (plugin.getSettings().isPublicHomesOnMap()) { + plugin.getDatabase() + .getLocalPublicHomes(plugin) + .forEach(this::updateHome); } - if (plugin.getSettings().warpsOnMap) { - plugin.getDatabase().getLocalWarps(plugin) - .thenAcceptAsync(warps -> warps.forEach(this::updateWarp)); + if (plugin.getSettings().isWarpsOnMap()) { + plugin.getDatabase() + .getLocalWarps(plugin) + .forEach(this::updateWarp); } }); return true; @@ -98,8 +100,8 @@ public abstract class MapHook extends PluginHook { */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") protected final boolean isValidPosition(@NotNull SavedPosition position) { - if (position instanceof Warp && !plugin.getSettings().warpsOnMap) return false; - if (position instanceof Home && !plugin.getSettings().publicHomesOnMap) return false; + if (position instanceof Warp && !plugin.getSettings().isWarpsOnMap()) return false; + if (position instanceof Home && !plugin.getSettings().isPublicHomesOnMap()) return false; try { return position.server.equals(plugin.getServerName()); diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java b/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java index 387a500a..91bcb9f5 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java @@ -50,7 +50,7 @@ public class PlanDataExtension implements DataExtension { hidden = true ) public boolean getHasUserData(@NotNull UUID uuid) { - return database.getUserData(uuid).join().isPresent(); + return database.getUserData(uuid).isPresent(); } @NumberProvider( @@ -62,8 +62,8 @@ public class PlanDataExtension implements DataExtension { ) @Conditional("hasData") public long getHomeCount(@NotNull UUID uuid) { - return database.getUserData(uuid).join() - .map(userData -> (long) database.getHomes(userData.user()).join().size()) + return database.getUserData(uuid) + .map(userData -> (long) database.getHomes(userData.user()).size()) .orElse(0L); } @@ -76,8 +76,8 @@ public class PlanDataExtension implements DataExtension { ) @Conditional("hasData") public long getPublicHomeCount(@NotNull UUID uuid) { - return database.getUserData(uuid).join() - .map(userData -> database.getHomes(userData.user()).join() + return database.getUserData(uuid) + .map(userData -> database.getHomes(userData.user()) .stream().filter(home -> home.isPublic).count()) .orElse(0L); } @@ -91,7 +91,7 @@ public class PlanDataExtension implements DataExtension { ) @Conditional("hasData") public long getPurchasedHomeSlots(@NotNull UUID uuid) { - return database.getUserData(uuid).join() + return database.getUserData(uuid) .map(userData -> (long) userData.homeSlots()) .orElse(0L); } @@ -105,7 +105,7 @@ public class PlanDataExtension implements DataExtension { ) @Conditional("hasData") public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) { - return database.getUserData(uuid).join() + return database.getUserData(uuid) .map(UserData::ignoringTeleports) .orElse(false); } @@ -119,11 +119,11 @@ public class PlanDataExtension implements DataExtension { ) @Conditional("hasData") public String getOfflinePosition(@NotNull UUID uuid) { - return database.getUserData(uuid).join() - .map(userData -> database.getOfflinePosition(userData.user()).join() + return database.getUserData(uuid) + .map(userData -> database.getOfflinePosition(userData.user()) .map(position -> "x: " + (int) position.x + ", y: " + (int) position.y + ", z: " + (int) position.z - + " (" + position.world.name + - ((crossServer) ? "/" + position.server.name + ")" : ")")) + + " (" + position.world.name + + ((crossServer) ? "/" + position.server.name + ")" : ")")) .orElse(UNKNOWN_STRING)) .orElse(UNKNOWN_STRING); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java index fcf0e20f..ab63d9ec 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java @@ -41,7 +41,7 @@ public class PlanHook extends PluginHook { private void registerDataExtension() { try { - ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().crossServer)); + ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().isCrossServer())); } catch (IllegalStateException planIsNotEnabled) { logger.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); // Plan is not enabled, handle exception diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 5b8e79ef..452e1607 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -71,7 +71,7 @@ public class EventListener { */ private CompletableFuture handleInboundTeleport(@NotNull OnlineUser onlineUser) { // If the server is in proxy mode, check if the player is teleporting cross-server and handle - if (plugin.getSettings().crossServer) { + if (plugin.getSettings().isCrossServer()) { return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> { if (teleport.isEmpty()) { return; @@ -82,10 +82,10 @@ public class EventListener { final Optional bedPosition = onlineUser.getBedSpawnPosition(); if (bedPosition.isEmpty()) { plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName())) - .ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().asynchronousTeleports)); + .ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().isAsynchronousTeleports())); onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid"); } else { - onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().asynchronousTeleports); + onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports()); } plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() -> plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null))); @@ -133,7 +133,7 @@ public class EventListener { */ protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) { // Set the player's last position to where they died - if (plugin.getSettings().backCommandReturnByDeath + if (plugin.getSettings().isBackCommandReturnByDeath() && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition()); } @@ -146,7 +146,7 @@ public class EventListener { */ protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) { // Display the return by death via /back notification - if (plugin.getSettings().backCommandReturnByDeath + if (plugin.getSettings().isBackCommandReturnByDeath() && onlineUser.hasPermission(Permission.COMMAND_BACK.node) && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { plugin.getLocales().getLocale("return_by_death_notification") @@ -154,7 +154,7 @@ public class EventListener { } // Respawn the player cross-server if needed - if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { + if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) { plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> { if (!respawnPosition.server.equals(plugin.getServerName())) { Teleport.builder(plugin, onlineUser) @@ -174,7 +174,7 @@ public class EventListener { * @param sourcePosition the source {@link Position} they came from */ protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) { - if (!plugin.getSettings().backCommandSaveOnTeleportEvent) return; + if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) return; plugin.getDatabase().getUserData(onlineUser.uuid) .thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase() @@ -188,7 +188,7 @@ public class EventListener { * @param position the new spawn point */ protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { - if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { + if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) { plugin.getDatabase().setRespawnPosition(onlineUser, position); } } diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java new file mode 100644 index 00000000..e094aae6 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -0,0 +1,98 @@ +package net.william278.huskhomes.manager; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.ValidationException; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.PositionMeta; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public class HomesManager { + private final HuskHomes plugin; + + protected HomesManager(@NotNull HuskHomes plugin) { + this.plugin = plugin; + } + + public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException { + final Optional existingHome = plugin.getDatabase().getHome(owner, name); + if (existingHome.isPresent() && !overwrite) { + throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN); + } + + if (!plugin.getValidator().isValidName(name)) { + throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + } + + final Home home = existingHome + .map(existing -> { + existing.x = position.x; + existing.y = position.y; + existing.z = position.z; + existing.world = position.world; + existing.server = position.server; + existing.yaw = position.yaw; + existing.pitch = position.pitch; + return existing; + }) + .orElse(new Home(position, new PositionMeta(name, ""), owner)); + plugin.getDatabase().saveHome(home); + } + + public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException { + final Optional home = plugin.getDatabase().getHome(owner, name); + if (home.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + plugin.getDatabase().deleteHome(home.get().uuid); + } + + public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException { + createHome(owner, name, position, true); + } + + public void renameHome(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException { + final Optional optionalHome = plugin.getDatabase().getHome(owner, name); + if (optionalHome.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + + if (!plugin.getValidator().isValidName(newName)) { + throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + } + + final Home home = optionalHome.get(); + home.meta.name = newName; + plugin.getDatabase().saveHome(home); + } + + public void updateHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException { + final Optional optionalHome = plugin.getDatabase().getHome(owner, name); + if (optionalHome.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + + if (!plugin.getValidator().isValidDescription(description)) { + throw new ValidationException(ValidationException.ValidationError.DESCRIPTION_INVALID); + } + + final Home home = optionalHome.get(); + home.meta.description = description; + plugin.getDatabase().saveHome(home); + } + + public void updateHomePrivacy(@NotNull User owner, @NotNull String name, boolean isPublic) throws ValidationException { + final Optional optionalHome = plugin.getDatabase().getHome(owner, name); + if (optionalHome.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + + final Home home = optionalHome.get(); + home.isPublic = isPublic; + plugin.getDatabase().saveHome(home); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/Manager.java b/common/src/main/java/net/william278/huskhomes/manager/Manager.java new file mode 100644 index 00000000..86ccbb11 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/manager/Manager.java @@ -0,0 +1,34 @@ +package net.william278.huskhomes.manager; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +public class Manager { + + private final HuskHomes plugin; + private final HomesManager homes; + private final WarpsManager warps; + private final UsersManager users; + + public Manager(@NotNull HuskHomes plugin) { + this.plugin = plugin; + this.homes = new HomesManager(plugin); + this.warps = new WarpsManager(plugin); + this.users = new UsersManager(plugin); + } + + @NotNull + public HomesManager homes() { + return homes; + } + + @NotNull + public WarpsManager warps() { + return warps; + } + + @NotNull + public UsersManager users() { + return users; + } +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java b/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java new file mode 100644 index 00000000..6458d2f5 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java @@ -0,0 +1,15 @@ +package net.william278.huskhomes.manager; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.player.User; +import org.jetbrains.annotations.NotNull; + +public class UsersManager { + protected UsersManager(@NotNull HuskHomes plugin) { + } + + public void ensureUser(@NotNull User user) { + + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java new file mode 100644 index 00000000..742f1669 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -0,0 +1,83 @@ +package net.william278.huskhomes.manager; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.ValidationException; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.PositionMeta; +import net.william278.huskhomes.position.Warp; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public class WarpsManager { + private final HuskHomes plugin; + protected WarpsManager(@NotNull HuskHomes plugin) { + this.plugin = plugin; + } + + public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) { + final Optional existingWarp = plugin.getDatabase().getWarp(name); + if (existingWarp.isPresent() && !overwrite) { + throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN); + } + + if (!plugin.getValidator().isValidName(name)) { + throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + } + + final Warp warp = existingWarp + .map(existing -> { + existing.x = position.x; + existing.y = position.y; + existing.z = position.z; + existing.world = position.world; + existing.server = position.server; + existing.yaw = position.yaw; + existing.pitch = position.pitch; + return existing; + }) + .orElse(new Warp(position, new PositionMeta(name, ""))); + plugin.getDatabase().saveWarp(warp); + } + + public void deleteWarp(@NotNull String name) { + final Optional warp = plugin.getDatabase().getWarp(name); + if (warp.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + plugin.getDatabase().deleteWarp(warp.get().uuid); + } + + public void relocateWarp(@NotNull String name, @NotNull Position position) { + createWarp(name, position, true); + } + + public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException { + final Optional optionalWarp = plugin.getDatabase().getWarp(name); + if (optionalWarp.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + + if (!plugin.getValidator().isValidName(newName)) { + throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + } + + final Warp warp = optionalWarp.get(); + warp.meta.name = newName; + plugin.getDatabase().saveWarp(warp); + } + + public void setWarpDescription(@NotNull String name, @NotNull String description) { + final Optional optionalWarp = plugin.getDatabase().getWarp(name); + if (optionalWarp.isEmpty()) { + throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + } + + final Warp warp = optionalWarp.get(); + warp.meta.description = description; + plugin.getDatabase().saveWarp(warp); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/network/Messenger.java b/common/src/main/java/net/william278/huskhomes/network/Messenger.java index 4e9e645f..f2b8c732 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Messenger.java +++ b/common/src/main/java/net/william278/huskhomes/network/Messenger.java @@ -57,7 +57,7 @@ public abstract class Messenger implements AutoCloseable { this.processingMessages = new HashMap<>(); this.onlinePlayerNamesRequests = new ArrayList<>(); this.onlineServersRequests = new ArrayList<>(); - this.clusterId = implementor.getSettings().clusterId; + this.clusterId = implementor.getSettings().getClusterId(); this.plugin = implementor; } diff --git a/common/src/main/java/net/william278/huskhomes/network/Request.java b/common/src/main/java/net/william278/huskhomes/network/Request.java index dfd0a8f5..e573d9da 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Request.java +++ b/common/src/main/java/net/william278/huskhomes/network/Request.java @@ -157,14 +157,14 @@ public class Request { public CompletableFuture> send(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) { this.sender = sender.username; - this.clusterId = plugin.getSettings().clusterId; + this.clusterId = plugin.getSettings().getClusterId(); return plugin.getMessenger().sendMessage(sender, this); } public void reply(@NotNull OnlineUser sender, @NotNull Payload payload, @NotNull HuskHomes plugin) { this.targetPlayer = this.sender; this.sender = sender.username; - this.clusterId = plugin.getSettings().clusterId; + this.clusterId = plugin.getSettings().getClusterId(); this.payload = payload; this.relayType = RelayType.REPLY; plugin.getMessenger().sendReply(sender, this); diff --git a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java deleted file mode 100644 index aeddf4ea..00000000 --- a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java +++ /dev/null @@ -1,443 +0,0 @@ -package net.william278.huskhomes.position; - -import net.william278.huskhomes.Cache; -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.hook.MapHook; -import net.william278.huskhomes.player.User; -import net.william278.huskhomes.util.RegexUtil; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -/** - * Cross-platform manager for validating homes and warps and updating them as necessary - */ -public class SavedPositionManager { - - private final HuskHomes plugin; - - public SavedPositionManager(@NotNull HuskHomes plugin) { - this.plugin = plugin; - } - - /** - * Tries to create a {@link Home} for a {@link User} at the specified {@link Position} from supplied - * {@link PositionMeta} data and add it to the database - * - * @param homeMeta metadata about the home - * @param homeOwner the owner of the home - * @param position where the home should be set - * @return a future supplying the {@link SaveResult}; the result of setting the home - */ - public CompletableFuture setHome(@NotNull PositionMeta homeMeta, @NotNull User homeOwner, - @NotNull Position position) { - return plugin.getDatabase().getHome(homeOwner, homeMeta.name).thenApplyAsync(optionalHome -> - validateMeta(homeMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> { - if (optionalHome.isEmpty()) { - // Handle setting a new home - final Home home = new Home(position, homeMeta, homeOwner); - return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> { - if (event.isCancelled()) { - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - } - final Cache cache = plugin.getCache(); - cache.homes.putIfAbsent(home.owner.uuid, new ArrayList<>()); - cache.homes.get(home.owner.uuid).add(home.meta.name); - cache.privateHomeLists.remove(home.owner.username); - return plugin.getDatabase().saveHome(home).thenApplyAsync(value -> - new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join(); - }).join(); - } else if (plugin.getSettings().overwriteExistingHomesWarps) { - // Handle overwriting existing homes if the option is enabled - final Home existingHome = optionalHome.get(); - updateHomePosition(existingHome, position).thenApplyAsync(result -> { - if (result) { - if (existingHome.isPublic) { - plugin.getMapHook().ifPresent(hook -> hook.updateHome(existingHome)); - } - - return new SaveResult(SaveResult.ResultType.SUCCESS_OVERWRITTEN, Optional.of(existingHome)); - } - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - }).join(); - } - return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty()); - })); - } - - /** - * Tries to delete a {@link User}'s home by given name - * - * @param homeOwner the owner of the home - * @param homeName the name of the home - * @return a future supplying a boolean; {@code true} if the home was deleted, otherwise {@code false} - * if the home name was invalid. - */ - public CompletableFuture deleteHome(@NotNull User homeOwner, @NotNull String homeName) { - return plugin.getDatabase().getHome(homeOwner, homeName).thenApplyAsync(optionalHome -> { - if (optionalHome.isPresent()) { - return plugin.getEventDispatcher().dispatchHomeDeleteEvent(optionalHome.get()).thenApplyAsync(event -> { - if (event.isCancelled()) { - return false; - } - final Home home = event.getHome(); - return plugin.getDatabase().deleteHome(home.uuid).thenApplyAsync(ignored -> { - final Cache cache = plugin.getCache(); - cache.homes.computeIfPresent(home.owner.uuid, (ownerUUID, homeNames) -> { - homeNames.remove(home.meta.name); - return homeNames; - }); - cache.privateHomeLists.remove(home.owner.username); - cache.publicHomeLists.clear(); - plugin.getMapHook().ifPresent(hook -> hook.removeHome(home)); - return true; - }).join(); - }).join(); - } - return false; - }); - } - - public CompletableFuture deleteAllHomes(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> plugin.getEventDispatcher().dispatchDeleteAllHomesEvent(user).join().isCancelled()) - .thenApply(cancelled -> plugin.getDatabase().deleteAllHomes(user) - .thenApply(result -> { - final Cache cache = plugin.getCache(); - cache.homes.remove(user.uuid); - cache.privateHomeLists.remove(user.username); - cache.publicHomeLists.clear(); - plugin.getMapHook().ifPresent(hook -> hook.clearHomes(user)); - return result; - }).join()); - } - - /** - * Tries to update an existing home with new metadata - * - * @param home the home to update - * @param newHomeMeta the new metadata for the home - * @return a future supplying the {@link SaveResult}; the result of updating the home - */ - public CompletableFuture updateHomeMeta(@NotNull Home home, @NotNull PositionMeta newHomeMeta) { - return CompletableFuture.supplyAsync(() -> { - if (!home.meta.name.equals(newHomeMeta.name) && plugin.getDatabase().getHome(home.owner, newHomeMeta.name).join().isPresent()) { - return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty()); - } - final String existingHomeName = home.meta.name; - return validateMeta(newHomeMeta).map(resultType -> - new SaveResult(resultType, Optional.empty())).orElseGet(() -> { - home.meta = newHomeMeta; - return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> { - if (event.isCancelled()) { - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - } - final Cache cache = plugin.getCache(); - if (!existingHomeName.equals(newHomeMeta.name)) { - cache.homes.get(home.owner.uuid).remove(existingHomeName); - cache.homes.get(home.owner.uuid).add(newHomeMeta.name); - } - cache.privateHomeLists.remove(home.owner.username); - cache.publicHomeLists.clear(); - if (home.isPublic) { - plugin.getMapHook().ifPresent(hook -> hook.updateHome(home)); - } - return plugin.getDatabase().saveHome(home).thenApplyAsync(value -> - new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join(); - }).join(); - }); - }); - } - - - /** - * Tries to update the position of a {@link User}'s home - * - * @param home the home to update - * @param newPosition the new position for the home - * @return a future supplying the {@link SaveResult}; the result of updating the home - */ - public CompletableFuture updateHomePosition(@NotNull Home home, @NotNull Position newPosition) { - home.update(newPosition); - return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> { - if (event.isCancelled()) { - return false; - } - if (home.isPublic) { - plugin.getMapHook().ifPresent(hook -> hook.updateHome(home)); - } - return plugin.getDatabase().saveHome(home).thenApplyAsync(ignored -> true).join(); - }); - } - - /** - * Tries to change the privacy of a {@link User}'s home by given name - * - * @param home the home to update - * @param isHomePublic whether the home should be public or not - * @return a future supplying a boolean; {@code true} if the privacy was changed, otherwise {@code false} - */ - public CompletableFuture updateHomePrivacy(@NotNull Home home, final boolean isHomePublic) { - home.isPublic = isHomePublic; - return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> { - if (event.isCancelled()) { - return false; - } - - // Save the home to database and propagate updates to cache and map hook - return plugin.getDatabase().saveHome(home).thenApplyAsync(ignored -> { - final Cache cache = plugin.getCache(); - if (home.isPublic) { - cache.publicHomes.putIfAbsent(home.owner.username, new ArrayList<>()); - cache.publicHomes.get(home.owner.username).add(home.meta.name); - plugin.getMapHook().ifPresent(hook -> hook.updateHome(home)); - } else { - if (cache.publicHomes.containsKey(home.owner.username)) { - cache.publicHomes.get(home.owner.username).remove(home.meta.name); - } - plugin.getMapHook().ifPresent(hook -> hook.removeHome(home)); - } - cache.privateHomeLists.remove(home.owner.username); - cache.publicHomeLists.clear(); - return true; - }).join(); - }); - } - - /** - * Tries to create a server {@link Warp} at the specified {@link Position} from supplied - * {@link PositionMeta} data and add it to the database - * - * @param warpMeta metadata about the warp - * @param position where the warp should be set - * @return a future supplying the {@link SaveResult}; the result of setting the warp - */ - public CompletableFuture setWarp(@NotNull PositionMeta warpMeta, @NotNull Position position) { - return plugin.getDatabase().getWarp(warpMeta.name).thenApplyAsync(optionalWarp -> - validateMeta(warpMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> { - if (optionalWarp.isEmpty()) { - // Handle setting new warps - final Warp warp = new Warp(position, warpMeta); - return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> { - if (event.isCancelled()) { - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - } - final Cache cache = plugin.getCache(); - cache.warps.add(warp.meta.name); - cache.warpLists.clear(); - plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp)); - return plugin.getDatabase().saveWarp(warp).thenApplyAsync(ignored -> - new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join(); - }).join(); - } else if (plugin.getSettings().overwriteExistingHomesWarps) { - // Handle overwriting existing warps if the option is enabled - final Warp existingWarp = optionalWarp.get(); - updateWarpPosition(existingWarp, position).thenApplyAsync(result -> { - if (result) { - plugin.getMapHook().ifPresent(hook -> hook.updateWarp(existingWarp)); - return new SaveResult(SaveResult.ResultType.SUCCESS_OVERWRITTEN, Optional.of(existingWarp)); - } - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - }).join(); - } - return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty()); - })); - } - - /** - * Tries to delete a warp by given name - * - * @param warpName the name of the warp - * @return a future supplying a boolean; {@code true} if the warp was deleted, otherwise {@code false} - * if the warp name was invalid. - */ - public CompletableFuture deleteWarp(@NotNull String warpName) { - return plugin.getDatabase().getWarp(warpName).thenApplyAsync(optionalWarp -> { - if (optionalWarp.isPresent()) { - return plugin.getEventDispatcher().dispatchWarpDeleteEvent(optionalWarp.get()).thenApplyAsync(event -> { - if (event.isCancelled()) { - return false; - } - - // Delete the warp from database and propagate updates to cache and map hook - final Warp warp = event.getWarp(); - return plugin.getDatabase().deleteWarp(warp.uuid).thenApplyAsync(ignored -> { - final Cache cache = plugin.getCache(); - cache.warps.remove(warp.meta.name); - cache.warpLists.clear(); - plugin.getMapHook().ifPresent(hook -> hook.removeWarp(warp)); - return true; - }).join(); - }).join(); - } - return false; - }); - } - - public CompletableFuture deleteAllWarps() { - return CompletableFuture.supplyAsync(() -> plugin.getEventDispatcher().dispatchDeleteAllWarpsEvent().join().isCancelled()) - .thenApply(cancelled -> plugin.getDatabase().deleteAllWarps() - .thenApply(result -> { - plugin.getCache().warps.clear(); - plugin.getCache().warpLists.clear(); - plugin.getMapHook().ifPresent(MapHook::clearWarps); - return result; - }).join()); - } - - /** - * Tries to update an existing warp with new metadata - * - * @param warp the warp to update - * @param newWarpMeta the new metadata for the home - * @return a future supplying the {@link SaveResult}; the result of updating the warp - */ - public CompletableFuture updateWarpMeta(@NotNull Warp warp, @NotNull PositionMeta newWarpMeta) { - return CompletableFuture.supplyAsync(() -> { - if (!warp.meta.name.equals(newWarpMeta.name) && plugin.getDatabase().getWarp(newWarpMeta.name).join().isPresent()) { - return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty()); - } - final String existingWarpName = warp.meta.name; - return validateMeta(newWarpMeta).map(resultType -> - new SaveResult(resultType, Optional.empty())).orElseGet(() -> { - warp.meta = newWarpMeta; - return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> { - if (event.isCancelled()) { - return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty()); - } - - final Cache cache = plugin.getCache(); - if (!existingWarpName.equals(newWarpMeta.name)) { - cache.warps.remove(existingWarpName); - cache.warps.add(newWarpMeta.name); - } - cache.warpLists.clear(); - plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp)); - return plugin.getDatabase().saveWarp(warp).thenApplyAsync(value -> - new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join(); - }).join(); - }); - }); - } - - - /** - * Tries to update the position of a warp - * - * @param warp the warp to update - * @param newPosition the new position for the warp - * @return a future supplying the {@link SaveResult}; the result of updating the warp - */ - public CompletableFuture updateWarpPosition(@NotNull Warp warp, @NotNull Position newPosition) { - warp.update(newPosition); - return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> { - if (event.isCancelled()) { - return false; - } - plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp)); - return plugin.getDatabase().saveWarp(warp).thenApplyAsync(ignored -> true).join(); - }); - } - - /** - * Validates {@link PositionMeta} to ensure it can be added to the database - * - * @param positionMeta the {@link PositionMeta} to validate - * @return An optional. If the {@link PositionMeta} is invalid, this will contain a {@link SaveResult.ResultType} - * identifying which constraint is violated by the metadata - */ - private Optional validateMeta(@NotNull PositionMeta positionMeta) { - if (positionMeta.name.length() > 16) { - return Optional.of(SaveResult.ResultType.FAILED_NAME_LENGTH); - } - if (!plugin.getSettings().allowUnicodeNames) { - if (!RegexUtil.NAME_PATTERN.matcher(positionMeta.name).matches()) { - return Optional.of(SaveResult.ResultType.FAILED_NAME_CHARACTERS); - } - } - if (positionMeta.name.contains(".")) { - return Optional.of(SaveResult.ResultType.FAILED_NAME_CHARACTERS); - } - if (positionMeta.description.length() > 255) { - return Optional.of(SaveResult.ResultType.FAILED_DESCRIPTION_LENGTH); - } - if (!plugin.getSettings().allowUnicodeDescriptions) { - if (!RegexUtil.DESCRIPTION_PATTERN.matcher(positionMeta.description).matches()) { - return Optional.of(SaveResult.ResultType.FAILED_DESCRIPTION_CHARACTERS); - } - } - return Optional.empty(); - } - - /** - * A record of information about the result of setting or updating a {@link SavedPosition} in the form of a warp or home - * - * @param resultType The {@link ResultType} of the result returned, indicating success - * @param savedPosition The {@link Position} of the saved position, if the result is {@link ResultType#SUCCESS}, otherwise {@link Optional#empty()} - */ - public record SaveResult(@NotNull ResultType resultType, @NotNull Optional savedPosition) { - - /** - * Indicates the result of setting a warp or home - */ - public enum ResultType { - /** - * The home or warp was successfully set - */ - SUCCESS(true), - - /** - * A home or warp was attempted to be set, but one already exists with the same name (for the user in the - * case of homes), so the existing position was updated instead. - *

- * - * @implNote This will only fire if the {@link Settings#overwriteExistingHomesWarps} config value is - * set to {@code true} - */ - SUCCESS_OVERWRITTEN(true), - - /** - * The position was not set; one by this name has already been set (for the user in the case of homes) - *

- * - * @implNote This will only fire if the {@link Settings#overwriteExistingHomesWarps} config value is - * set to {@code false} - */ - FAILED_DUPLICATE(false), - - /** - * The position was not set or updated; the name exceeds the maximum length - */ - FAILED_NAME_LENGTH(false), - - /** - * The position was not set or updated; the description exceeds the maximum length - */ - FAILED_DESCRIPTION_LENGTH(false), - - /** - * The position was not set or updated; the name uses illegal characters - */ - FAILED_NAME_CHARACTERS(false), - - /** - * The position was not set or updated; the description uses illegal characters - */ - FAILED_DESCRIPTION_CHARACTERS(false), - - /** - * The position was not set or updated; the save event was cancelled by a plugin - */ - FAILED_EVENT_CANCELLED(false); - - public final boolean successful; - - ResultType(final boolean successful) { - this.successful = successful; - } - } - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java index 7efd5fd6..a5d70170 100644 --- a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java @@ -22,10 +22,10 @@ public class NormalDistributionEngine extends RandomTeleportEngine { public NormalDistributionEngine(@NotNull HuskHomes implementor) { super(implementor, "Normal Distribution"); - this.radius = implementor.getSettings().rtpRadius; - this.spawnRadius = implementor.getSettings().rtpSpawnRadius; - this.mean = implementor.getSettings().rtpDistributionMean; - this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation; + this.radius = implementor.getSettings().getRtpRadius(); + this.spawnRadius = implementor.getSettings().getRtpSpawnRadius(); + this.mean = implementor.getSettings().getRtpDistributionMean(); + this.standardDeviation = implementor.getSettings().getRtpDistributionStandardDeviation(); } /** @@ -85,7 +85,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine { } @Override - protected Optional generatePosition(@NotNull World world, @NotNull String[] args) { + protected Optional getRandomPosition(@NotNull World world, @NotNull String[] args) { Optional location = generateSafeLocation(world).join(); int attempts = 0; while (location.isEmpty()) { diff --git a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java index 5aa59c8f..25c580b8 100644 --- a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java @@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; /** * Represents an engine for generating random position targets @@ -64,23 +63,7 @@ public abstract class RandomTeleportEngine { * @param args The arguments to pass to the random teleport engine * @return The position, optionally, which will be empty if the random teleport engine timed out after a * {@link #randomTimeout configured number of attempts} - * @implNote This is run asynchronously (i.e. not on the main server thread) */ - protected abstract Optional generatePosition(@NotNull World world, @NotNull String[] args); - - /** - * Gets a random position in the {@link World}, supplying a future to be completed with the optional position - * is found, or empty if the operation times out after a number of attempts. - * - * @param world The world to find a random position in - * @param args The arguments to pass to the random teleport engine - * @return A {@link CompletableFuture} containing the random position, if one is found in - * {@link #randomTimeout configured number of attempts}, or if the operation times out after 10 seconds - */ - public CompletableFuture> getRandomPosition(@NotNull World world, @NotNull String[] args) { - return CompletableFuture.supplyAsync(() -> generatePosition(world, args)) - .orTimeout(10, TimeUnit.SECONDS) - .exceptionally(e -> Optional.empty()); - } + public abstract Optional getRandomPosition(@NotNull World world, @NotNull String[] args); } diff --git a/common/src/main/java/net/william278/huskhomes/redis/RedisWorker.java b/common/src/main/java/net/william278/huskhomes/redis/RedisWorker.java index 31ef1b6f..c49469e3 100644 --- a/common/src/main/java/net/william278/huskhomes/redis/RedisWorker.java +++ b/common/src/main/java/net/william278/huskhomes/redis/RedisWorker.java @@ -25,10 +25,10 @@ public class RedisWorker { public JedisPool jedisPool; public RedisWorker(@NotNull Settings settings) { - this.host = settings.redisHost; - this.port = settings.redisPort; - this.password = settings.redisPassword != null ? settings.redisPassword : ""; - this.ssl = settings.redisUseSsl && !(this.host.equalsIgnoreCase("localhost") + this.host = settings.getRedisHost(); + this.port = settings.getRedisPort(); + this.password = settings.getRedisPassword() != null ? settings.getRedisPassword() : ""; + this.ssl = settings.isRedisUseSsl() && !(this.host.equalsIgnoreCase("localhost") || this.host.equalsIgnoreCase("127.0.0.1")); } diff --git a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java index 4e762fa0..37689346 100644 --- a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java +++ b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java @@ -127,7 +127,7 @@ public class RequestManager { public CompletableFuture> sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, @NotNull TeleportRequest.RequestType requestType) { final TeleportRequest request = new TeleportRequest(requester, requestType, - Instant.now().getEpochSecond() + plugin.getSettings().teleportRequestExpiryTime); + Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime()); final Optional localTarget = plugin.findOnlinePlayer(targetUser); if (localTarget.isPresent()) { if (localTarget.get().equals(requester)) { @@ -138,7 +138,7 @@ public class RequestManager { } // If the player couldn't be found locally, send the request cross-server - if (plugin.getSettings().crossServer) { + if (plugin.getSettings().isCrossServer()) { // Find the matching networked target return plugin.getMessenger().findPlayer(requester, targetUser).thenApplyAsync(networkedTarget -> { if (networkedTarget.isEmpty()) { @@ -279,7 +279,7 @@ public class RequestManager { final Optional localRequester = plugin.findOnlinePlayer(request.requesterName); if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); - } else if (plugin.getSettings().crossServer) { + } else if (plugin.getSettings().isCrossServer()) { // Ensure the sender is still online plugin.getMessenger() .findPlayer(recipient, request.requesterName) @@ -313,7 +313,7 @@ public class RequestManager { // If the request is a tpa here request, teleport the recipient to the sender if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) { // Strict /tpahere requests will teleport to where the sender was when typing the command - if (plugin.getSettings().strictTpaHereRequests) { + if (plugin.getSettings().isStrictTpaHereRequests()) { Teleport.builder(plugin, recipient) .setTarget(request.requesterPosition) .toTimedTeleport() diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index b8a8a574..db996f33 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -173,13 +173,13 @@ public class Teleport { // Dispatch the teleport event and update the player's last position plugin.getEventDispatcher().dispatchTeleportEvent(this); - if (updateLastPosition && !plugin.getSettings().backCommandSaveOnTeleportEvent && type == TeleportType.TELEPORT) { + if (updateLastPosition && !plugin.getSettings().isBackCommandSaveOnTeleportEvent() && type == TeleportType.TELEPORT) { plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); } // If the target position is local, finalize economy transactions and teleport the player - if (!plugin.getSettings().crossServer || target.server.equals(plugin.getServerName())) { - return teleporter.teleportLocally(target, plugin.getSettings().asynchronousTeleports); + if (!plugin.getSettings().isCrossServer() || target.server.equals(plugin.getServerName())) { + return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports()); } // If the target position is on another server, execute a cross-server teleport diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java index d27bf460..a1a3bc70 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -89,7 +89,7 @@ public class TeleportBuilder { .findOnlinePlayer(teleporterUsername) .map(onlineUser -> (User) onlineUser) .or(() -> { - if (plugin.getSettings().crossServer) { + if (plugin.getSettings().isCrossServer()) { return plugin.getMessenger() .findPlayer(executor, teleporterUsername).join() .map(username -> new User(UUID.randomUUID(), username)); @@ -208,7 +208,7 @@ public class TeleportBuilder { return CompletableFuture.supplyAsync(() -> { final User teleporter = this.teleporter.join(); final Position target = this.target.join(); - final int warmupTime = plugin.getSettings().teleportWarmupTime; + final int warmupTime = plugin.getSettings().getTeleportWarmupTime(); if (!(teleporter instanceof OnlineUser onlineUser)) { throw new IllegalStateException("Timed teleports can only be executed for local users"); @@ -232,7 +232,7 @@ public class TeleportBuilder { if (localPlayer.isPresent()) { return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition())); } - if (plugin.getSettings().crossServer) { + if (plugin.getSettings().isCrossServer()) { return plugin.getMessenger() .findPlayer(executor, playerName) .thenApplyAsync(foundPlayer -> { diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index c4c7ee4f..9e49a8ac 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -180,7 +180,7 @@ public class TimedTeleport extends Teleport { * @param message the message to send */ private void sendStatusMessage(@NotNull MineDown message) { - switch (plugin.getSettings().teleportWarmupDisplay) { + switch (plugin.getSettings().getTeleportWarmupDisplay()) { case ACTION_BAR -> teleporter.sendActionBar(message); case SUBTITLE -> teleporter.sendTitle(message, true); case TITLE -> teleporter.sendTitle(message, false); diff --git a/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java b/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java new file mode 100644 index 00000000..e01b7f34 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java @@ -0,0 +1,16 @@ +package net.william278.huskhomes.util; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public interface TaskRunner { + void runAsync(@NotNull Runnable runnable); + CompletableFuture supplyAsync(@NotNull Supplier supplier); + void runSync(@NotNull Runnable runnable); + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/Validator.java b/common/src/main/java/net/william278/huskhomes/util/Validator.java new file mode 100644 index 00000000..dab0baeb --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/Validator.java @@ -0,0 +1,51 @@ +package net.william278.huskhomes.util; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +public class Validator { + + public static final int MAX_NAME_LENGTH = 16; + public static final int MIN_NAME_LENGTH = 1; + public static final int MAX_DESCRIPTION_LENGTH = 256; + + private final HuskHomes plugin; + + public Validator(@NotNull HuskHomes plugin) { + this.plugin = plugin; + } + + /** + * Check if a name is valid + * + * @param name The name to check + * @return True if the name is valid as per the plugin settings, false otherwise + */ + public boolean isValidName(@NotNull String name) { + return (isAsciiOnly(name) || plugin.getSettings().isAllowUnicodeNames()) + && !containsWhitespace(name) + && name.length() <= MAX_NAME_LENGTH && name.length() >= MIN_NAME_LENGTH; + } + + /** + * Validate home and warp descriptions + * + * @param meta The meta to validate + * @return Whether the meta is valid against the plugin settings + */ + public boolean isValidDescription(@NotNull String meta) { + return (isAsciiOnly(meta) || plugin.getSettings().isAllowUnicodeDescriptions()) + && meta.length() <= MAX_DESCRIPTION_LENGTH; + } + + // Check if a string contains only ASCII characters + private static boolean isAsciiOnly(@NotNull String string) { + return string.matches("\\A\\p{ASCII}*\\z"); + } + + // Check if a string contains whitespace + private static boolean containsWhitespace(@NotNull String string) { + return string.matches(".*\\s.*"); + } + +}