From 39e0b25d460028c360f3fd83d55245ece3245e20 Mon Sep 17 00:00:00 2001 From: William278 Date: Sat, 4 Mar 2023 21:38:53 +0000 Subject: [PATCH] Further refactoring, move away from using future thread pool --- .../william278/huskhomes/BukkitHuskHomes.java | 61 +--- .../huskhomes/api/HuskHomesAPI.java | 17 +- .../huskhomes/migrator/LegacyMigrator.java | 212 ------------- .../huskhomes/util/BukkitTaskRunner.java | 23 +- .../huskhomes/util/BukkitUpgradeUtil.java | 88 ------ .../huskhomes/BukkitPluginTests.java | 6 +- .../java/net/william278/huskhomes/Cache.java | 20 +- .../net/william278/huskhomes/HuskHomes.java | 62 +--- .../huskhomes/api/BaseHuskHomesAPI.java | 93 ++---- .../huskhomes/command/BackCommand.java | 2 +- .../huskhomes/command/DelHomeCommand.java | 1 - .../huskhomes/command/EditHomeCommand.java | 5 +- .../huskhomes/command/HomeCommand.java | 1 - .../huskhomes/command/HuskHomesCommand.java | 43 --- .../huskhomes/command/PublicHomeCommand.java | 1 - .../huskhomes/command/RtpCommand.java | 5 +- .../huskhomes/command/SetHomeCommand.java | 6 +- .../huskhomes/command/TpCommand.java | 1 - .../huskhomes/command/TpaAllCommand.java | 4 +- .../huskhomes/command/TpaCommand.java | 4 +- .../huskhomes/command/TpaHereCommand.java | 4 +- .../william278/huskhomes/config/Locales.java | 2 +- .../william278/huskhomes/config/Settings.java | 18 +- .../config/{CachedSpawn.java => Spawn.java} | 10 +- .../huskhomes/database/Database.java | 30 +- .../huskhomes/database/MySqlDatabase.java | 33 +-- .../huskhomes/database/SqLiteDatabase.java | 33 +-- .../huskhomes/hook/EconomyHook.java | 4 +- .../huskhomes/hook/PlanDataExtension.java | 7 +- .../huskhomes/listener/EventListener.java | 23 +- .../huskhomes/manager/HomesManager.java | 18 +- .../william278/huskhomes/manager/Manager.java | 7 + .../RequestsManager.java} | 166 ++++------- .../huskhomes/manager/WarpsManager.java | 14 +- .../huskhomes/migrator/Migrator.java | 68 ----- .../william278/huskhomes/network/Broker.java | 104 +++---- .../william278/huskhomes/network/Message.java | 39 +-- .../william278/huskhomes/network/Payload.java | 65 ++-- .../huskhomes/position/Position.java | 3 +- .../huskhomes/teleport/CompletedTeleport.java | 117 -------- .../william278/huskhomes/teleport/Target.java | 12 + .../huskhomes/teleport/Teleport.java | 279 +++++++----------- .../huskhomes/teleport/TeleportBuilder.java | 269 ++++------------- .../TeleportRequest.java | 110 ++++--- .../huskhomes/teleport/TeleportType.java | 31 -- .../huskhomes/teleport/Teleportable.java | 12 + .../teleport/TeleportationException.java | 16 + .../huskhomes/teleport/TimedTeleport.java | 96 ++---- .../huskhomes/teleport/Username.java | 16 + .../william278/huskhomes/user/OnlineUser.java | 3 +- .../william278/huskhomes/util/RegexUtil.java | 65 ---- .../william278/huskhomes/util/TaskRunner.java | 6 +- .../{ => util}/ValidationException.java | 6 +- .../william278/huskhomes/util/Validator.java | 1 + .../huskhomes/network/MessageTests.java | 58 ++++ .../huskhomes/network/RequestTests.java | 50 ---- 56 files changed, 737 insertions(+), 1713 deletions(-) delete mode 100644 bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java delete mode 100644 bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java rename common/src/main/java/net/william278/huskhomes/config/{CachedSpawn.java => Spawn.java} (88%) rename common/src/main/java/net/william278/huskhomes/{request/RequestManager.java => manager/RequestsManager.java} (61%) delete mode 100644 common/src/main/java/net/william278/huskhomes/migrator/Migrator.java delete mode 100644 common/src/main/java/net/william278/huskhomes/teleport/CompletedTeleport.java create mode 100644 common/src/main/java/net/william278/huskhomes/teleport/Target.java rename common/src/main/java/net/william278/huskhomes/{request => teleport}/TeleportRequest.java (55%) delete mode 100644 common/src/main/java/net/william278/huskhomes/teleport/TeleportType.java create mode 100644 common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java create mode 100644 common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java create mode 100644 common/src/main/java/net/william278/huskhomes/teleport/Username.java delete mode 100644 common/src/main/java/net/william278/huskhomes/util/RegexUtil.java rename common/src/main/java/net/william278/huskhomes/{ => util}/ValidationException.java (67%) create mode 100644 common/src/test/java/net/william278/huskhomes/network/MessageTests.java delete mode 100644 common/src/test/java/net/william278/huskhomes/network/RequestTests.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index c9bc0be8..8ace2345 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -8,7 +8,7 @@ import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommandType; import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.command.DisabledCommand; -import net.william278.huskhomes.config.CachedSpawn; +import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.database.Database; @@ -23,8 +23,6 @@ import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.PluginMessageBroker; import net.william278.huskhomes.network.RedisBroker; -import net.william278.huskhomes.migrator.LegacyMigrator; -import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.Location; @@ -32,7 +30,6 @@ import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.World; import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.request.RequestManager; import net.william278.huskhomes.util.*; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; @@ -71,17 +68,15 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess private BukkitLogger logger; private Database database; private Cache cache; - private RequestManager requestManager; private Validator validator; private Manager manager; private EventListener eventListener; private RandomTeleportEngine randomTeleportEngine; - private CachedSpawn serverSpawn; + private Spawn serverSpawn; private UnsafeBlocks unsafeBlocks; private EventDispatcher eventDispatcher; private Set pluginHooks; private List registeredCommands; - private List migrators; private Server server; @Nullable @@ -114,17 +109,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Create adventure audience this.audiences = BukkitAudiences.create(this); - // Detect if an upgrade is needed - final BukkitUpgradeUtil upgradeData = BukkitUpgradeUtil.detect(this); - // Load settings and locales getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); initialized.set(reload()); if (initialized.get()) { logger.showDebugLogs(settings.doDebugLogging()); - if (upgradeData != null) { - upgradeData.upgradeSettings(settings); - } getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); } else { throw new IllegalStateException("Failed to load plugin configuration settings and/or locales"); @@ -158,9 +147,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Prepare the validator this.validator = new Validator(this); - // Prepare the request manager - this.requestManager = new RequestManager(this); - // Prepare the event dispatcher this.eventDispatcher = new BukkitEventDispatcher(this); @@ -175,14 +161,14 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Register plugin hooks (Economy, Maps, Plan) this.pluginHooks = new HashSet<>(); - if (settings.isEconomy()) { + if (settings.doEconomy()) { 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.isDoMapHook()) { + if (settings.doMapHook()) { switch (settings.getMappingPlugin()) { case DYNMAP -> { final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap"); @@ -243,10 +229,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess }); getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands."); - // Prepare migrators - this.migrators = new ArrayList<>(); - this.migrators.add(new LegacyMigrator(this)); - // Hook into bStats metrics registerMetrics(METRICS_ID); @@ -255,18 +237,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess 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" + getVersion() + ")"))); } - - // Perform automatic upgrade if detected - if (upgradeData != null) { - getLoggingAdapter().log(Level.INFO, "Performing automatic upgrade..."); - new LegacyMigrator(this, upgradeData).start().thenAccept(result -> { - if (result) { - getLoggingAdapter().log(Level.INFO, "Successfully performed automatic upgrade."); - } else { - getLoggingAdapter().log(Level.WARNING, "Failed to perform automatic upgrade."); - } - }); - } } catch (IllegalStateException exception) { getLoggingAdapter().log(Level.SEVERE, exception.getMessage()); initialized.set(false); @@ -346,12 +316,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess return cache; } - @Override - @NotNull - public RequestManager getRequestManager() { - return requestManager; - } - @Override @NotNull public Validator getValidator() { @@ -391,18 +355,13 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess } @Override - public List getMigrators() { - return migrators; - } - - @Override - public Optional getLocalCachedSpawn() { + public Optional getLocalCachedSpawn() { return Optional.ofNullable(serverSpawn); } @Override public void setServerSpawn(@NotNull Location location) { - final CachedSpawn newSpawn = new CachedSpawn(location); + final Spawn newSpawn = new Spawn(location); this.serverSpawn = newSpawn; try { Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn); @@ -502,7 +461,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Load spawn location from file final File spawnFile = new File(getDataFolder(), "spawn.yml"); if (spawnFile.exists()) { - this.serverSpawn = Annotaml.create(spawnFile, CachedSpawn.class).get(); + this.serverSpawn = Annotaml.create(spawnFile, Spawn.class).get(); } // Load unsafe blocks from resources @@ -531,9 +490,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess } 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("using_economy", () -> Boolean.toString(getSettings().doEconomy()))); + metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook()))); + if (getSettings().doMapHook()) { metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName)); } } catch (Exception e) { diff --git a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java index 3003d59e..d7477959 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java +++ b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java @@ -98,14 +98,25 @@ public class HuskHomesAPI extends BaseHuskHomesAPI { * @param location the bukkit location to get the {@link Position} instance for * @param server the {@link Server} the position is on * @return the {@link Position} instance for the given bukkit {@link Location} on the given {@link Server} - * @see Position#server - * @since 3.0 + * @see Position#getServer() to get the server the position is on + * @since 4.0 */ - @Nullable + @NotNull public Position adaptPosition(@NotNull org.bukkit.Location location, @NotNull String server) { return new Position(Objects.requireNonNull(adaptLocation(location)), server); } + /** + * Returns a {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on. + * @param location the bukkit location to get the {@link Position} instance for + * @return the {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on + * @since 4.0 + */ + @NotNull + public Position adaptPosition(@NotNull org.bukkit.Location location) { + return new Position(Objects.requireNonNull(adaptLocation(location)), getServer()); + } + /** * Get the {@link Server}, containing the ID of the server the plugin is running on * diff --git a/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java b/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java deleted file mode 100644 index b418c08f..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java +++ /dev/null @@ -1,212 +0,0 @@ -package net.william278.huskhomes.migrator; - -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.database.Database; -import net.william278.huskhomes.util.BukkitUpgradeUtil; -import org.jetbrains.annotations.NotNull; - -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; - -public class LegacyMigrator extends Migrator { - - public Database.DatabaseType sourceDatabaseType; - public String sourceMySqlHost; - public int sourceMySqlPort; - public String sourceMySqlDatabase; - public String sourceMySqlUsername; - public String sourceMySqlPassword; - public String sourcePlayerDataTable = "huskhomes_player_data"; - public String sourceLocationsDataTable = "huskhomes_location_data"; - public String sourceHomesDataTable = "huskhomes_home_data"; - public String sourceWarpsDataTable = "huskhomes_warp_data"; - - public LegacyMigrator(@NotNull HuskHomes implementor) { - super(implementor); - 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) { - super(implementor); - this.sourceDatabaseType = bukkitUpgradeUtil.databaseType; - - this.sourceMySqlHost = bukkitUpgradeUtil.mySqlHost; - this.sourceMySqlPort = bukkitUpgradeUtil.mySqlPort; - this.sourceMySqlDatabase = bukkitUpgradeUtil.mySqlDatabase; - this.sourceMySqlUsername = bukkitUpgradeUtil.mySqlUsername; - this.sourceMySqlPassword = bukkitUpgradeUtil.mySqlPassword; - - this.sourcePlayerDataTable = bukkitUpgradeUtil.sourcePlayerDataTable; - this.sourceLocationsDataTable = bukkitUpgradeUtil.sourceLocationsDataTable; - this.sourceHomesDataTable = bukkitUpgradeUtil.sourceHomesDataTable; - this.sourceWarpsDataTable = bukkitUpgradeUtil.sourceWarpsDataTable; - } - - @Override - public CompletableFuture start() { - return CompletableFuture.supplyAsync(() -> { - if (sourceDatabaseType == Database.DatabaseType.SQLITE) { - migrateSqLiteDatabase(); - return true; - } - - if (sourceDatabaseType == plugin.getSettings().getDatabaseType() - && sourceMySqlHost.equals(plugin.getSettings().getMySqlHost()) - && sourceMySqlPort == plugin.getSettings().getMySqlPort()) { - migrateMySqlDatabase(); - return true; - } - - plugin.getLoggingAdapter().log(Level.SEVERE, "Migration failed! Different source and target databases/types." + - "Please dump your data from your source database manually and then" + - " import it to your new database, then attempt migration again."); - return false; - }); - } - - private void migrateSqLiteDatabase() { - plugin.getLoggingAdapter().log(Level.INFO, "Migrating SQLite database, please wait... This may take a while!"); - - // Execute the migration script - try { - plugin.getDatabase().runScript(Objects.requireNonNull(plugin.getResource("database/migrator/sqlite_migrator.sql")), - Map.of("%target_positions_table%", plugin.getSettings().getTableName(Database.TableName.POSITION_DATA), - "%source_positions_table%", sourceLocationsDataTable, - "%target_users_table%", plugin.getSettings().getTableName(Database.TableName.PLAYER_DATA), - "%source_users_table%", sourcePlayerDataTable, - "%target_saved_positions%", plugin.getSettings().getTableName(Database.TableName.SAVED_POSITION_DATA), - "%source_homes_table%", sourceHomesDataTable, - "%target_homes_table%", plugin.getSettings().getTableName(Database.TableName.HOME_DATA), - "%source_warps_table%", sourceWarpsDataTable, - "%target_warps_table%", plugin.getSettings().getTableName(Database.TableName.WARP_DATA))); - plugin.getLoggingAdapter().log(Level.INFO, "SQLite Migration complete!"); - } catch (Exception e) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Migration of SQLite database failed!" + - " Perhaps the target tables was not clean?", e); - } - } - - private void migrateMySqlDatabase() { - plugin.getLoggingAdapter().log(Level.INFO, "Migrating MySQL database, please wait... This may take a while!"); - - // Execute the migration script - try { - plugin.getDatabase().runScript(Objects.requireNonNull(plugin.getResource("database/migrator/mysql_migrator.sql")), - Map.of("%target_positions_table%", plugin.getSettings().getTableName(Database.TableName.POSITION_DATA), - "%source_positions_table%", sourceLocationsDataTable, - "%target_users_table%", plugin.getSettings().getTableName(Database.TableName.PLAYER_DATA), - "%source_users_table%", sourcePlayerDataTable, - "%target_saved_positions%", plugin.getSettings().getTableName(Database.TableName.SAVED_POSITION_DATA), - "%source_homes_table%", sourceHomesDataTable, - "%target_homes_table%", plugin.getSettings().getTableName(Database.TableName.HOME_DATA), - "%source_warps_table%", sourceWarpsDataTable, - "%target_warps_table%", plugin.getSettings().getTableName(Database.TableName.WARP_DATA), - "%source_database%", sourceMySqlDatabase)); - plugin.getLoggingAdapter().log(Level.INFO, "MySQL Migration complete!"); - } catch (Exception e){ - plugin.getLoggingAdapter().log(Level.SEVERE, "Migration of MySQL database failed!" + - " Perhaps the target tables was not clean?", e); - } - } - - @Override - public void handleConfigurationCommand(@NotNull String[] args) { - if (args.length == 2) { - if (switch (args[0].toLowerCase()) { - case "database" -> { - this.sourceMySqlDatabase = args[1]; - yield true; - } - case "player_data_table" -> { - this.sourcePlayerDataTable = args[1]; - yield true; - } - case "locations_data_table" -> { - this.sourceLocationsDataTable = args[1]; - yield true; - } - case "homes_data_table" -> { - this.sourceHomesDataTable = args[1]; - yield true; - } - case "warps_data_table" -> { - this.sourceWarpsDataTable = args[1]; - yield true; - } - default -> false; - }) { - plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu()); - plugin.getLoggingAdapter().log(Level.INFO, "Successfully set " + args[0] + " to " + - obfuscateDataString(args[1])); - } else { - plugin.getLoggingAdapter().log(Level.INFO, "Invalid operation, could not set " + args[0] + " to " + - obfuscateDataString(args[1]) + " (is it a valid option?)"); - } - } else { - plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu()); - } - } - - @Override - public @NotNull String getIdentifier() { - return "legacy"; - } - - @Override - public @NotNull String getName() { - return "HuskHomes Legacy (v2.x)"; - } - - @NotNull - @Override - public String getHelpMenu() { - return """ - === HuskHomes v2.x --> v3.x Migration Wizard ========= - This will migrate all user data from HuskHomes v2.x - to HuskHomes v3.x. The source and target databases - must be the same, please note. - - [!] Existing data in the database will be wiped. [!] - - STEP 1] Please ensure no players are on any servers - running HuskHomes. If you're running MySQL, you only - need to do this once - it's best to only have one - server running. - - STEP 2] Ensure the following settings are correct: - - Source table names: - - player_data: %source_players_table% - - locations_data: %source_locations_table% - - homes_data: %source_homes_table% - - warps_data: %source_warps_table% - - Source MySQL database name (ignore if using SQLite): - - database: %source_mysql_database% - - If any of these are not correct, please correct them - using the command: - "huskhomes migrate legacy set " - (e.g.: "huskhomes migrate legacy set database foo") - - STEP 3] HuskHomes will migrate data into the database - tables configured in the config.yml file of this - server. Please make sure you're happy with this - before proceeding. - - STEP 4] To start the migration, please run: - "huskhomes migrate legacy start" - """.replaceAll("%source_players_table%", sourcePlayerDataTable) - .replaceAll("%source_locations_table%", sourceLocationsDataTable) - .replaceAll("%source_homes_table%", sourceHomesDataTable) - .replaceAll("%source_warps_table%", sourceWarpsDataTable) - .replaceAll("%source_mysql_database%", sourceMySqlDatabase); - } -} diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java index 4375ce35..177120de 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTaskRunner.java @@ -1,17 +1,17 @@ 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.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; public interface BukkitTaskRunner extends TaskRunner { @Override - default void runAsync(@NotNull Runnable runnable) { - Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable); + default int runAsync(@NotNull Runnable runnable) { + return Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable).getTaskId(); } @Override @@ -23,8 +23,21 @@ public interface BukkitTaskRunner extends TaskRunner { } @Override - default void runSync(@NotNull Runnable runnable) { - Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable); + default int runSync(@NotNull Runnable runnable) { + return Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable).getTaskId(); + } + + @Override + default int runAsyncRepeating(@NotNull Runnable runnable, long period) { + AtomicInteger taskId = new AtomicInteger(); + taskId.set(Bukkit.getScheduler().runTaskTimerAsynchronously((BukkitHuskHomes) getPlugin(), + runnable, 0, period).getTaskId()); + return taskId.get(); + } + + @Override + default void cancelTask(int taskId) { + Bukkit.getScheduler().cancelTask(taskId); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java deleted file mode 100644 index 2ddcb352..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package net.william278.huskhomes.util; - -import net.william278.annotaml.Annotaml; -import net.william278.huskhomes.BukkitHuskHomes; -import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.database.Database; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; - -/** - * Utility class for upgrading important stuff from HuskHomes v2.x config files to v3.x. - */ -public class BukkitUpgradeUtil { - - private final BukkitHuskHomes plugin; - public Database.DatabaseType databaseType; - public String mySqlHost; - public int mySqlPort; - public String mySqlDatabase; - public String mySqlUsername; - public String mySqlPassword; - public String mySqlParams; - - public String sourcePlayerDataTable; - public String sourceLocationsDataTable; - public String sourceHomesDataTable; - public String sourceWarpsDataTable; - - private BukkitUpgradeUtil(@NotNull BukkitHuskHomes plugin) { - this.plugin = plugin; - } - - /** - * Reads old settings from the config and writes them to the new config. - */ - private void readOldSettings() { - this.databaseType = Database.DatabaseType.valueOf(plugin.getConfig() - .getString("data_storage_options.storage_type", "SQLITE").toUpperCase()); - - this.mySqlHost = plugin.getConfig().getString("data_storage_options.mysql_credentials.host", "localhost"); - this.mySqlPort = plugin.getConfig().getInt("data_storage_options.mysql_credentials.port", 3306); - this.mySqlDatabase = plugin.getConfig().getString("data_storage_options.mysql_credentials.database", "HuskHomes"); - this.mySqlUsername = plugin.getConfig().getString("data_storage_options.mysql_credentials.username", "root"); - this.mySqlPassword = plugin.getConfig().getString("data_storage_options.mysql_credentials.password", "pa55w0rd"); - this.mySqlParams = plugin.getConfig().getString("data_storage_options.mysql_credentials.params", "?autoReconnect=true&useSSL=false"); - - this.sourcePlayerDataTable = plugin.getConfig().getString("data_storage_options.table_names.player_data", "huskhomes_player_data"); - this.sourceLocationsDataTable = plugin.getConfig().getString("data_storage_options.table_names.locations_data", "huskhomes_location_data"); - this.sourceHomesDataTable = plugin.getConfig().getString("data_storage_options.table_names.homes_data", "huskhomes_home_data"); - this.sourceWarpsDataTable = plugin.getConfig().getString("data_storage_options.table_names.warps_data", "huskhomes_warp_data"); - } - - /** - * Upgrade the config from an older version to the current version. - * - * @param settings The settings to upgrade - */ - public void upgradeSettings(@NotNull Settings settings) { - plugin.getLoggingAdapter().log(Level.WARNING, "Upgrading critical HuskHomes v2.x settings to v3.x."); - settings.databaseType = databaseType; - settings.mySqlHost = mySqlHost; - settings.mySqlPort = mySqlPort; - settings.mySqlDatabase = mySqlDatabase; - settings.mySqlUsername = mySqlUsername; - settings.mySqlPassword = mySqlPassword; - settings.mySqlConnectionParameters = mySqlParams; - try { - Annotaml.create(new File(plugin.getDataFolder(), "config.yml"), settings); - } catch (IOException e) { - plugin.getLogger().log(Level.SEVERE, "Failed to upgrade HuskHomes settings from a legacy version", e); - } - } - - @Nullable - public static BukkitUpgradeUtil detect(@NotNull BukkitHuskHomes plugin) { - if (!plugin.getConfig().contains("config_file_version")) { - return null; - } - final BukkitUpgradeUtil upgrade = new BukkitUpgradeUtil(plugin); - upgrade.readOldSettings(); - return upgrade; - } - -} diff --git a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java index 530dfc10..e6cbddcb 100644 --- a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java +++ b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java @@ -59,9 +59,9 @@ public class BukkitPluginTests { final MineDown simpleLocale = plugin.getLocales() .getLocale("error_in_game_only") - .orElseThrow(() -> new HuskHomesException("Failed to load locale")); + .orElseThrow(() -> new IllegalStateException("Failed to load locale")); final String simpleLocaleText = plugin.getLocales().getRawLocale("error_in_game_only") - .orElseThrow(() -> new HuskHomesException("Failed to load raw locale")); + .orElseThrow(() -> new IllegalStateException("Failed to load raw locale")); BukkitUser.adapt(player).sendMessage(simpleLocale); player.assertSaid(simpleLocaleText); } @@ -72,7 +72,7 @@ public class BukkitPluginTests { final MineDown locale = plugin.getLocales() .getLocale("teleporting_action_bar_warmup", Integer.toString(3)) - .orElseThrow(() -> new HuskHomesException("Failed to load locale")); + .orElseThrow(() -> new IllegalStateException("Failed to load locale")); BukkitUser.adapt(player).sendActionBar(locale); BukkitUser.adapt(player).sendMessage(locale); BukkitUser.adapt(player).sendTitle(locale, false); diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java index 14926ac1..c4795000 100644 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -64,17 +64,17 @@ public class Cache { getPlayers().addAll(plugin.getOnlineUsers() .stream() .filter(player -> !player.isVanished()) - .map(onlineUser -> onlineUser.getUsername()) + .map(User::getUsername) .toList()); - - if (plugin.getSettings().isCrossServer()) { - return plugin.getMessenger() - .getOnlinePlayerNames(requester) - .thenApply(networkedPlayers -> { - getPlayers().addAll(Set.of(networkedPlayers)); - return getPlayers(); - }); - } +//todo +// if (plugin.getSettings().isCrossServer()) { +// return plugin.getMessenger() +// .getOnlinePlayerNames(requester) +// .thenApply(networkedPlayers -> { +// getPlayers().addAll(Set.of(networkedPlayers)); +// return getPlayers(); +// }); +// } return CompletableFuture.completedFuture(getPlayers()); } diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index e41b7024..5f40acc8 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -9,7 +9,7 @@ import net.william278.desertwell.Version; import net.william278.huskhomes.command.CommandBase; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.config.CachedSpawn; +import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.database.Database; import net.william278.huskhomes.event.EventDispatcher; import net.william278.huskhomes.hook.EconomyHook; @@ -17,11 +17,9 @@ import net.william278.huskhomes.hook.MapHook; import net.william278.huskhomes.hook.PluginHook; import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Broker; -import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.*; 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; @@ -76,29 +74,6 @@ public interface HuskHomes extends TaskRunner { .findFirst()); } - /** - * Looks for a player logged in either on this server or the network of connected servers, by approximate name. - * Auto-completes partially typed names for the closest match. - * - * @param requester the player requesting the player to be found - * @param targetPlayerName the name of the player to find - * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found - */ - @NotNull - default CompletableFuture> findPlayer(@NotNull OnlineUser requester, @NotNull String targetPlayerName) { - if (requester.getUsername().equalsIgnoreCase(targetPlayerName)) { - return CompletableFuture.completedFuture(Optional.of(requester.getUsername())); - } - final Optional localPlayer = findOnlinePlayer(targetPlayerName); - if (localPlayer.isPresent()) { - return CompletableFuture.completedFuture(Optional.of(localPlayer.get().getUsername())); - } - if (getSettings().isCrossServer()) { - return getMessenger().findPlayer(requester, targetPlayerName); - } - return CompletableFuture.completedFuture(Optional.empty()); - } - /** * The plugin {@link Settings} loaded from file * @@ -131,14 +106,6 @@ public interface HuskHomes extends TaskRunner { @NotNull Cache getCache(); - /** - * The {@link RequestManager} that manages player requests - * - * @return the plugin {@link RequestManager} - */ - @NotNull - RequestManager getRequestManager(); - /** * The {@link Validator} for validating thome names and descriptions * @@ -187,19 +154,12 @@ public interface HuskHomes extends TaskRunner { EventDispatcher getEventDispatcher(); /** - * The list of available {@link Migrator}s + * The local {@link Spawn} location of this server, as cached to disk * - * @return the list of available {@link Migrator} - */ - List getMigrators(); - - /** - * The local {@link CachedSpawn} location of this server, as cached to disk - * - * @return the {@link CachedSpawn} location data + * @return the {@link Spawn} location data * @see #getSpawn() for the canonical spawn point to use */ - Optional getLocalCachedSpawn(); + Optional getLocalCachedSpawn(); /** * The canonical spawn {@link Position} of this server, if it has been set @@ -229,9 +189,9 @@ public interface HuskHomes extends TaskRunner { } /** - * Update the {@link CachedSpawn} position to a location on the server + * Update the {@link Spawn} position to a location on the server * - * @param location the new {@link CachedSpawn} location + * @param location the new {@link Spawn} location */ void setServerSpawn(@NotNull Location location); @@ -263,7 +223,7 @@ public interface HuskHomes extends TaskRunner { * @return the {@link MapHook} optionally being used */ default Optional getMapHook() { - return getSettings().isDoMapHook() ? getHook(MapHook.class) : Optional.empty(); + return getSettings().doMapHook() ? getHook(MapHook.class) : Optional.empty(); } /** @@ -272,7 +232,7 @@ public interface HuskHomes extends TaskRunner { * @return the {@link EconomyHook} optionally being used */ default Optional getEconomyHook() { - return getSettings().isEconomy() ? getHook(EconomyHook.class) : Optional.empty(); + return getSettings().doEconomy() ? getHook(EconomyHook.class) : Optional.empty(); } /** @@ -283,7 +243,7 @@ public interface HuskHomes extends TaskRunner { * @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") - default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction action) { + default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { final Optional cost = getSettings().getEconomyCost(action).map(Math::abs); if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) { final Optional hook = getEconomyHook(); @@ -304,8 +264,8 @@ public interface HuskHomes extends TaskRunner { * @param player the player to deduct the cost from if needed * @param action the action to deduct the cost from if needed */ - default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.EconomyAction action) { - if (!getSettings().isEconomy()) return; + default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) { + if (!getSettings().doEconomy()) 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/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index a73ecdd5..abcd7b51 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -3,14 +3,15 @@ package net.william278.huskhomes.api; import de.themoep.minedown.adventure.MineDown; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Locales; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.random.RandomTeleportEngine; +import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.UserData; -import net.william278.huskhomes.position.*; -import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportBuilder; -import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.teleport.TeleportResult; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -116,7 +117,6 @@ public abstract class BaseHuskHomesAPI { * Save {@link UserData} to the database, updating it if data for the user already exists, or adding new user data if it doesn't. * * @param userData The {@link UserData} to save - * @return A {@link CompletableFuture} that will complete when the data has been saved * @since 3.0 */ public final void saveUserData(@NotNull UserData userData) { @@ -138,12 +138,12 @@ public abstract class BaseHuskHomesAPI { * * @param user The {@link User} to get the public homes of * @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user that - * they have made public (where {@link Home#isPublic}) + * they have made public (where {@link Home#isPublic()}) * @since 3.0 */ public final CompletableFuture> getUserPublicHomes(@NotNull User user) { return getUserHomes(user).thenApply(homes -> homes.stream() - .filter(home -> home.isPublic()) + .filter(Home::isPublic) .collect(Collectors.toList())); } @@ -264,45 +264,9 @@ public abstract class BaseHuskHomesAPI { */ @NotNull public final TeleportBuilder teleportBuilder(@NotNull OnlineUser onlineUser) { - return Teleport.builder(plugin, onlineUser); + return Teleport.builder(plugin).teleporter(onlineUser); } - /** - * Attempt to teleport an {@link OnlineUser} to a target {@link Position} - * - * @param user The {@link OnlineUser} to teleport - * @param position The {@link Position} to teleport the user to - * @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still - * for a period of time) - * @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of - * completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}. - * @since 3.0 - * @deprecated Use {@link #teleportBuilder(OnlineUser)} to construct a teleport - */ - @Deprecated(since = "3.1") - public final CompletableFuture teleportPlayer(@NotNull OnlineUser user, - @NotNull Position position, - final boolean timedTeleport) { - final TeleportBuilder builder = teleportBuilder(user).setTarget(position); - return timedTeleport - ? builder.toTimedTeleport().thenApplyAsync(teleport -> teleport.execute().join().getState()) - : builder.toTeleport().thenApplyAsync(teleport -> teleport.execute().join().getState()); - } - - /** - * Attempt to teleport an {@link OnlineUser} to a target {@link Position} - * - * @param user The {@link OnlineUser} to teleport - * @param position The {@link Position} to teleport the user to - * @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of - * completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}. - * @since 3.0 - * @deprecated Use {@link #teleportBuilder(OnlineUser)} to construct a teleport - */ - @Deprecated(since = "3.1") - public final CompletableFuture teleportPlayer(@NotNull OnlineUser user, @NotNull Position position) { - return teleportPlayer(user, position, false); - } /** * Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be @@ -312,26 +276,25 @@ public abstract class BaseHuskHomesAPI { * @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still * for a period of time) * @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine} - * @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of - * completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}. * @since 3.0 */ - public final CompletableFuture randomlyTeleportPlayer(@NotNull OnlineUser user, - final boolean timedTeleport, - @NotNull String... rtpArgs) { - return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine() - .getRandomPosition(user.getPosition().getWorld(), rtpArgs) - .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(); + public final void randomlyTeleportPlayer(@NotNull OnlineUser user, final boolean timedTeleport, @NotNull String... rtpArgs) { + plugin.runAsync(() -> { + final Optional position = plugin.getRandomTeleportEngine() + .getRandomPosition(user.getPosition().getWorld(), rtpArgs); + if (position.isEmpty()) { + throw new IllegalStateException("Random teleport engine returned an empty position"); + } - }) - .orElse(TeleportResult.CANCELLED)); + final TeleportBuilder builder = Teleport.builder(plugin) + .teleporter(user) + .target(position.get()); + if (timedTeleport) { + builder.toTimedTeleport().execute(); + } else { + builder.toTeleport().execute(); + } + }); } /** @@ -339,12 +302,10 @@ public abstract class BaseHuskHomesAPI { * generated by the current {@link RandomTeleportEngine} * * @param user The {@link OnlineUser} to teleport - * @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of - * completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}. * @since 3.0 */ - public final CompletableFuture randomlyTeleportPlayer(@NotNull OnlineUser user) { - return randomlyTeleportPlayer(user, false); + public final void randomlyTeleportPlayer(@NotNull OnlineUser user) { + this.randomlyTeleportPlayer(user, false); } /** diff --git a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java index 4b3058cc..cce8900e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java @@ -19,7 +19,7 @@ public class BackCommand extends CommandBase { plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition -> lastPosition.ifPresentOrElse(position -> Teleport.builder(plugin, onlineUser) .setTarget(position) - .setEconomyActions(EconomyHook.EconomyAction.BACK_COMMAND) + .setEconomyActions(EconomyHook.Action.BACK_COMMAND) .toTimedTeleport() .thenApply(TimedTeleport::execute), () -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage))); 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 a7ae7abe..2a56a869 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -4,7 +4,6 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.Permission; -import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; 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 caedeb18..f6edf546 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -8,7 +8,6 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.util.Permission; -import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -226,7 +225,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { } // Check against economy - if (!plugin.validateEconomyCheck(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC)) { + if (!plugin.validateEconomyCheck(editor, EconomyHook.Action.MAKE_HOME_PUBLIC)) { return; } } @@ -244,7 +243,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable { } // Perform necessary economy transaction - plugin.performEconomyTransaction(editor, EconomyHook.EconomyAction.MAKE_HOME_PUBLIC); + plugin.performEconomyTransaction(editor, EconomyHook.Action.MAKE_HOME_PUBLIC); // Show the menu if the menu flag is set if (showMenuFlag.get()) { 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 3ce47ee9..110b3ff6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -7,7 +7,6 @@ import net.william278.huskhomes.position.Home; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TimedTeleport; import net.william278.huskhomes.util.Permission; -import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; 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 31029c50..2d1eea1c 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -3,7 +3,6 @@ package net.william278.huskhomes.command; import de.themoep.minedown.adventure.MineDown; import net.william278.desertwell.AboutMenu; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -12,7 +11,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; @@ -147,50 +145,9 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, () -> plugin.getLoggingAdapter().log(Level.INFO, "HuskHomes is up to date" + " (Running v" + plugin.getVersion() + ")"))); - case "migrate" -> { - if (args.length < 2) { - plugin.getLoggingAdapter().log(Level.INFO, - "Please choose a migrator, then run \"huskhomes migrate \""); - logMigratorsList(); - return; - } - final Optional selectedMigrator = plugin.getMigrators().stream().filter(availableMigrator -> - availableMigrator.getIdentifier().equalsIgnoreCase(args[1])).findFirst(); - selectedMigrator.ifPresentOrElse(migrator -> { - if (args.length < 3) { - plugin.getLoggingAdapter().log(Level.INFO, migrator.getHelpMenu()); - return; - } - switch (args[2]) { - case "start" -> migrator.start().thenAccept(succeeded -> { - if (succeeded) { - plugin.getLoggingAdapter().log(Level.INFO, "Migration completed successfully!"); - } else { - plugin.getLoggingAdapter().log(Level.WARNING, "Migration failed!"); - } - }); - case "set" -> migrator.handleConfigurationCommand(Arrays.copyOfRange(args, 3, args.length)); - default -> plugin.getLoggingAdapter().log(Level.INFO, - "Invalid syntax. Console usage: \"huskhomes migrate " + args[1] + " "); - } - }, () -> { - plugin.getLoggingAdapter().log(Level.INFO, - "Please specify a valid migrator.\n" + - "If a migrator is not available, please verify that you meet the prerequisites to use it."); - logMigratorsList(); - }); - } } } - private void logMigratorsList() { - plugin.getLoggingAdapter().log(Level.INFO, - "List of available migrators:\nMigrator ID / Migrator Name:\n" + - plugin.getMigrators().stream() - .map(migrator -> migrator.getIdentifier() + " - " + migrator.getName()) - .collect(Collectors.joining("\n"))); - } - private void sendAboutMenu(@NotNull OnlineUser onlineUser) { if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_ABOUT.node)) { plugin.getLocales().getLocale("error_no_permission") 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 fba93be5..396228bb 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -7,7 +7,6 @@ import net.william278.huskhomes.position.Home; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TimedTeleport; import net.william278.huskhomes.util.Permission; -import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; 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 5cb45c06..2cb115d8 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -6,7 +6,6 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.UserData; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.util.Permission; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.NotNull; @@ -49,7 +48,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } // Perform economy check if necessary - if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.EconomyAction.RANDOM_TELEPORT)) { + if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.Action.RANDOM_TELEPORT)) { return; } @@ -83,7 +82,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport) .setTarget(position.get()); final CompletableFuture teleportFuture = isExecutorTeleporting - ? builder.setEconomyActions(EconomyHook.EconomyAction.RANDOM_TELEPORT).toTimedTeleport() + ? builder.setEconomyActions(EconomyHook.Action.RANDOM_TELEPORT).toTimedTeleport() : builder.toTeleport(); teleportFuture.thenAccept(teleport -> teleport.execute() 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 8cf2f2eb..6c83fc15 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -67,11 +67,11 @@ 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().isEconomy()) { + if (plugin.getSettings().doEconomy()) { final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(), plugin.getSettings().doStackPermissionLimits()); if (fetchedData.isPresent()) { - final EconomyHook.EconomyAction action = EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT; + final EconomyHook.Action action = EconomyHook.Action.ADDITIONAL_HOME_SLOT; newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots())); // If a new slot is needed, validate the user has enough funds to purchase one @@ -105,7 +105,7 @@ public class SetHomeCommand extends CommandBase { // If the user needed to buy a new slot, perform the transaction and update their data if (newSlotNeeded.get()) { - plugin.performEconomyTransaction(onlineUser, EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT); + plugin.performEconomyTransaction(onlineUser, EconomyHook.Action.ADDITIONAL_HOME_SLOT); plugin.getDatabase().updateUserData(userDataToUpdate.get()); } yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name); diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index d416a4ad..76fe9ceb 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -6,7 +6,6 @@ import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java index f0eba215..0e593b59 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.request.TeleportRequest; +import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -44,7 +44,7 @@ public class TpaAllCommand extends CommandBase { final AtomicInteger counter = new AtomicInteger(0); final List> sentRequestsFuture = new ArrayList<>(); players.forEach(playerName -> sentRequestsFuture.add(plugin.getRequestManager() - .sendTeleportRequest(onlineUser, playerName, TeleportRequest.RequestType.TPA_HERE) + .sendTeleportRequest(onlineUser, playerName, TeleportRequest.Type.TPA_HERE) .thenAccept(sent -> counter.addAndGet(sent.isPresent() ? 1 : 0)))); // Send a message when all requests have been sent diff --git a/common/src/main/java/net/william278/huskhomes/command/TpaCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpaCommand.java index 4bf3b66e..13e30146 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpaCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpaCommand.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.request.TeleportRequest; +import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -27,7 +27,7 @@ public class TpaCommand extends CommandBase implements TabCompletable { if (args.length == 1) { plugin.getRequestManager() - .sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA) + .sendTeleportRequest(onlineUser, args[0], TeleportRequest.Type.TPA) .thenAccept(sent -> { if (sent.isEmpty()) { if (args[0].equalsIgnoreCase(onlineUser.getUsername())) { diff --git a/common/src/main/java/net/william278/huskhomes/command/TpaHereCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpaHereCommand.java index 818d5ab2..3786a15a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpaHereCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpaHereCommand.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.request.TeleportRequest; +import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -27,7 +27,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable { if (args.length == 1) { plugin.getRequestManager() - .sendTeleportRequest(onlineUser, args[0], TeleportRequest.RequestType.TPA_HERE) + .sendTeleportRequest(onlineUser, args[0], TeleportRequest.Type.TPA_HERE) .thenAccept(sent -> { if (sent.isEmpty()) { if (args[0].equalsIgnoreCase(onlineUser.getUsername())) { diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java index bbab8108..6a4bfc0f 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Locales.java +++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java @@ -21,7 +21,7 @@ import java.util.Optional; ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣╸ See plugin about menu for international locale credits ┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown - ┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/Translations""") + ┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""") public class Locales { /** 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 9ed4b7e5..d075f583 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -226,14 +226,14 @@ public class Settings { @YamlKey("economy.costs") private Map economyCosts = Map.of( - EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyHook.EconomyAction.ADDITIONAL_HOME_SLOT.getDefaultCost(), - EconomyHook.EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyHook.EconomyAction.MAKE_HOME_PUBLIC.getDefaultCost(), - EconomyHook.EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyHook.EconomyAction.RANDOM_TELEPORT.getDefaultCost(), - EconomyHook.EconomyAction.BACK_COMMAND.name().toLowerCase(), EconomyHook.EconomyAction.BACK_COMMAND.getDefaultCost() + EconomyHook.Action.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyHook.Action.ADDITIONAL_HOME_SLOT.getDefaultCost(), + EconomyHook.Action.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyHook.Action.MAKE_HOME_PUBLIC.getDefaultCost(), + EconomyHook.Action.RANDOM_TELEPORT.name().toLowerCase(), EconomyHook.Action.RANDOM_TELEPORT.getDefaultCost(), + EconomyHook.Action.BACK_COMMAND.name().toLowerCase(), EconomyHook.Action.BACK_COMMAND.getDefaultCost() ); - public Optional getEconomyCost(@NotNull EconomyHook.EconomyAction action) { - if (!isEconomy()) { + public Optional getEconomyCost(@NotNull EconomyHook.Action action) { + if (!doEconomy()) { return Optional.empty(); } final Double cost = getEconomyCosts().get(action.name().toLowerCase()); @@ -363,7 +363,7 @@ public class Settings { return teleportRequestExpiryTime; } - public boolean isStrictTpaHereRequests() { + public boolean doStrictTpaHereRequests() { return strictTpaHereRequests; } @@ -463,7 +463,7 @@ public class Settings { return rtpRestrictedWorlds; } - public boolean isEconomy() { + public boolean doEconomy() { return economy; } @@ -479,7 +479,7 @@ public class Settings { return economyCosts; } - public boolean isDoMapHook() { + public boolean doMapHook() { return doMapHook; } diff --git a/common/src/main/java/net/william278/huskhomes/config/CachedSpawn.java b/common/src/main/java/net/william278/huskhomes/config/Spawn.java similarity index 88% rename from common/src/main/java/net/william278/huskhomes/config/CachedSpawn.java rename to common/src/main/java/net/william278/huskhomes/config/Spawn.java index df318971..429de197 100644 --- a/common/src/main/java/net/william278/huskhomes/config/CachedSpawn.java +++ b/common/src/main/java/net/william278/huskhomes/config/Spawn.java @@ -4,11 +4,9 @@ import net.william278.annotaml.YamlFile; import net.william278.annotaml.YamlKey; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.World; import org.jetbrains.annotations.NotNull; -import java.util.Optional; import java.util.UUID; /** @@ -16,10 +14,10 @@ import java.util.UUID; */ @YamlFile(header = """ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ - ┃ Server /spawn location cache ┃ + ┃ Server /spawn location ┃ ┃ Edit in-game using /setspawn ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""") -public class CachedSpawn { +public class Spawn { public double x; public double y; @@ -47,7 +45,7 @@ public class CachedSpawn { * * @param location The {@link Location} of the spawn */ - public CachedSpawn(@NotNull Location location) { + public Spawn(@NotNull Location location) { this.x = location.getX(); this.y = location.getY(); this.z = location.getZ(); @@ -58,6 +56,6 @@ public class CachedSpawn { } @SuppressWarnings("unused") - public CachedSpawn() { + public Spawn() { } } 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 a3e1cde8..c7030655 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -261,19 +261,12 @@ public abstract class Database { * * @param plugin The plugin instance * @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 */ + @NotNull public final List getLocalWarps(@NotNull HuskHomes plugin) { - try { - final Server server = plugin.getServerName(); - return getWarps().stream() - .filter(warp -> warp.getServer().equals(server)) - .collect(Collectors.toList()); - } catch (IllegalStateException e) { - return getWarps().stream() - .filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.getWorld()))) - .collect(Collectors.toList()); - } + return getWarps().stream() + .filter(warp -> warp.getServer().equals(plugin.getServerName())) + .collect(Collectors.toList()); } /** @@ -288,19 +281,12 @@ public abstract class Database { * * @param plugin The plugin instance * @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 */ + @NotNull public final List getLocalPublicHomes(@NotNull HuskHomes plugin) { - try { - final Server server = plugin.getServerName(); - return getPublicHomes().stream() - .filter(home -> home.getServer().equals(server)) - .collect(Collectors.toList()); - } catch (IllegalStateException e) { - return plugin.getDatabase().getPublicHomes().stream() - .filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.getWorld()))) - .collect(Collectors.toList()); - } + return getPublicHomes().stream() + .filter(home -> home.getServer().equals(plugin.getServerName())) + .collect(Collectors.toList()); } /** 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 8529026e..7fe0d564 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -7,7 +7,6 @@ import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.UserData; import net.william278.huskhomes.position.*; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -152,7 +151,7 @@ public class MySqlDatabase extends Database { statement.setFloat(5, position.getPitch()); statement.setString(6, position.getWorld().getName()); statement.setString(7, position.getWorld().getUuid().toString()); - statement.setString(8, position.getServer().getName()); + statement.setString(8, position.getServer()); statement.executeUpdate(); final ResultSet resultSet = statement.getGeneratedKeys(); @@ -183,7 +182,7 @@ public class MySqlDatabase extends Database { statement.setFloat(5, position.getPitch()); statement.setString(6, position.getWorld().getUuid().toString()); statement.setString(7, position.getWorld().getName()); - statement.setString(8, position.getServer().getName()); + statement.setString(8, position.getServer()); statement.setDouble(9, positionId); statement.executeUpdate(); } @@ -600,20 +599,20 @@ public class MySqlDatabase extends Database { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { - return Optional.of(Teleport.builder(plugin, onlineUser) - .setTarget(new Position(resultSet.getDouble("x"), + return Optional.of(Teleport.builder(plugin) + .teleporter(onlineUser) + .target(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()); + resultSet.getString("server_name"))) + .type(Teleport.Type.getTeleportType(resultSet.getInt("type")) + .orElse(Teleport.Type.TELEPORT)) + .updateLastPosition(false) + .toTeleport()); } } } catch (SQLException e) { @@ -657,13 +656,13 @@ public class MySqlDatabase extends Database { } // Set the user's teleport into the database (if it's not null) - if (teleport != null && teleport.target != null) { + if (teleport != null) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); - statement.setInt(2, setPosition(teleport.target, connection)); - statement.setInt(3, teleport.type.typeId); + statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); + statement.setInt(3, teleport.getType().getTypeId()); statement.executeUpdate(); } @@ -692,7 +691,7 @@ public class MySqlDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } } catch (SQLException e) { @@ -751,7 +750,7 @@ public class MySqlDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } } catch (SQLException e) { @@ -809,7 +808,7 @@ public class MySqlDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } } catch (SQLException e) { 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 4552111b..fcdcf09c 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -6,7 +6,6 @@ import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.UserData; import net.william278.huskhomes.position.*; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.sqlite.SQLiteConfig; @@ -144,7 +143,7 @@ public class SqLiteDatabase extends Database { statement.setFloat(5, position.getPitch()); statement.setString(6, position.getWorld().getName()); statement.setString(7, position.getWorld().getUuid().toString()); - statement.setString(8, position.getServer().getName()); + statement.setString(8, position.getServer()); statement.executeUpdate(); // Return the ID of the newly inserted row @@ -177,7 +176,7 @@ public class SqLiteDatabase extends Database { statement.setFloat(5, position.getPitch()); statement.setString(6, position.getWorld().getUuid().toString()); statement.setString(7, position.getWorld().getName()); - statement.setString(8, position.getServer().getName()); + statement.setString(8, position.getServer()); statement.setDouble(9, positionId); statement.executeUpdate(); } @@ -596,20 +595,20 @@ public class SqLiteDatabase extends Database { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { - return Optional.of(Teleport.builder(plugin, onlineUser) - .setTarget(new Position(resultSet.getDouble("x"), + return Optional.of(Teleport.builder(plugin) + .teleporter(onlineUser) + .target(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()); + resultSet.getString("server_name"))) + .type(Teleport.Type.getTeleportType(resultSet.getInt("type")) + .orElse(Teleport.Type.TELEPORT)) + .updateLastPosition(false) + .toTeleport()); } } catch (SQLException e) { @@ -654,13 +653,13 @@ public class SqLiteDatabase extends Database { } // Set the user's teleport into the database (if it's not null) - if (teleport != null && teleport.target != null) { + if (teleport != null) { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); - statement.setInt(2, setPosition(teleport.target, connection)); - statement.setInt(3, teleport.type.typeId); + statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); + statement.setInt(3, teleport.getType().getTypeId()); statement.executeUpdate(); @@ -688,7 +687,7 @@ public class SqLiteDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } catch (SQLException e) { getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); @@ -745,7 +744,7 @@ public class SqLiteDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } catch (SQLException e) { @@ -800,7 +799,7 @@ public class SqLiteDatabase extends Database { resultSet.getFloat("pitch"), new World(resultSet.getString("world_name"), UUID.fromString(resultSet.getString("world_uuid"))), - new Server(resultSet.getString("server_name")))); + resultSet.getString("server_name"))); } } catch (SQLException e) { getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); diff --git a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java index ab392971..6f674ac8 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java @@ -40,7 +40,7 @@ public abstract class EconomyHook extends PluginHook { /** * Identifies actions that incur an economic cost if economy is enabled */ - public enum EconomyAction { + public enum Action { ADDITIONAL_HOME_SLOT(100.00, "economy_action_additional_home_slot"), MAKE_HOME_PUBLIC(50.00, "economy_action_make_home_public"), RANDOM_TELEPORT(25.00, "economy_action_random_teleport"), @@ -50,7 +50,7 @@ public abstract class EconomyHook extends PluginHook { @NotNull public final String confirmationLocaleId; - EconomyAction(final double defaultCost, @NotNull String confirmationLocaleId) { + Action(final double defaultCost, @NotNull String confirmationLocaleId) { this.defaultCost = defaultCost; this.confirmationLocaleId = confirmationLocaleId; } 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 9bf7c5ed..ce2dd225 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanDataExtension.java @@ -6,6 +6,7 @@ import com.djrapitops.plan.extension.annotation.*; import com.djrapitops.plan.extension.icon.Color; import com.djrapitops.plan.extension.icon.Family; import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.position.Home; import net.william278.huskhomes.user.UserData; import org.jetbrains.annotations.NotNull; @@ -77,8 +78,8 @@ public class PlanDataExtension implements DataExtension { @Conditional("hasData") public long getPublicHomeCount(@NotNull UUID uuid) { return database.getUserData(uuid) - .map(userData -> database.getHomes(userData.user()) - .stream().filter(home -> home.isPublic()).count()) + .map(userData -> database.getHomes(userData.user()).stream() + .filter(Home::isPublic).count()) .orElse(0L); } @@ -123,7 +124,7 @@ public class PlanDataExtension implements DataExtension { .map(userData -> database.getOfflinePosition(userData.user()) .map(position -> "x: " + (int) position.getX() + ", y: " + (int) position.getY() + ", z: " + (int) position.getZ() + " (" + position.getWorld().getName() + - ((crossServer) ? "/" + position.getServer().getName() + ")" : ")")) + ((crossServer) ? "/" + position.getServer() + ")" : ")")) .orElse(UNKNOWN_STRING)) .orElse(UNKNOWN_STRING); } 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 720cbc38..7a276dd2 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -6,7 +6,6 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportType; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -43,7 +42,7 @@ public class EventListener { // Set their ignoring requests state plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> { final boolean ignoringRequests = userData.ignoringTeleports(); - plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests); + plugin.getManager().requests().setIgnoringRequests(onlineUser, ignoringRequests); // Send a reminder message if they are still ignoring requests if (ignoringRequests) { @@ -68,7 +67,7 @@ public class EventListener { */ private void handleInboundTeleport(@NotNull OnlineUser onlineUser) { plugin.getDatabase().getCurrentTeleport(onlineUser).ifPresent(teleport -> { - if (teleport.type == TeleportType.RESPAWN) { + if (teleport.getType() == Teleport.Type.RESPAWN) { final Optional bedPosition = onlineUser.getBedSpawnPosition(); if (bedPosition.isEmpty()) { plugin.getLocalCachedSpawn() @@ -83,13 +82,8 @@ public class EventListener { plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)); return; } - teleport.execute() - .thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null)) - .exceptionally(throwable -> { - plugin.getLoggingAdapter().log(Level.SEVERE, - "An error occurred while teleporting an inbound player", throwable); - return null; - }); + teleport.execute(); + plugin.getDatabase().setCurrentTeleport(onlineUser, null); }); } @@ -146,11 +140,12 @@ public class EventListener { if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) { plugin.getDatabase().getRespawnPosition(onlineUser).ifPresent(respawnPosition -> { if (!respawnPosition.getServer().equals(plugin.getServerName())) { - Teleport.builder(plugin, onlineUser) - .setType(TeleportType.RESPAWN) - .setTarget(respawnPosition) + Teleport.builder(plugin) + .teleporter(onlineUser) + .type(Teleport.Type.RESPAWN) + .target(respawnPosition) .toTeleport() - .thenAccept(Teleport::execute); + .execute(); } }); } diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index 42a9b43d..43442a9d 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.ValidationException; +import net.william278.huskhomes.util.ValidationException; import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; @@ -20,11 +20,11 @@ public class HomesManager { 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); + throw new ValidationException(ValidationException.Type.NAME_TAKEN); } if (!plugin.getValidator().isValidName(name)) { - throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + throw new ValidationException(ValidationException.Type.NAME_INVALID); } final Home home = existingHome @@ -45,7 +45,7 @@ public class HomesManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } plugin.getDatabase().deleteHome(home.get().getUuid()); } @@ -57,11 +57,11 @@ public class HomesManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } if (!plugin.getValidator().isValidName(newName)) { - throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + throw new ValidationException(ValidationException.Type.NAME_INVALID); } final Home home = optionalHome.get(); @@ -72,11 +72,11 @@ public class HomesManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } if (!plugin.getValidator().isValidDescription(description)) { - throw new ValidationException(ValidationException.ValidationError.DESCRIPTION_INVALID); + throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID); } final Home home = optionalHome.get(); @@ -87,7 +87,7 @@ public class HomesManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } final Home home = optionalHome.get(); diff --git a/common/src/main/java/net/william278/huskhomes/manager/Manager.java b/common/src/main/java/net/william278/huskhomes/manager/Manager.java index 86ccbb11..4adb2275 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/Manager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/Manager.java @@ -9,12 +9,14 @@ public class Manager { private final HomesManager homes; private final WarpsManager warps; private final UsersManager users; + private final RequestsManager requests; public Manager(@NotNull HuskHomes plugin) { this.plugin = plugin; this.homes = new HomesManager(plugin); this.warps = new WarpsManager(plugin); this.users = new UsersManager(plugin); + this.requests = new RequestsManager(plugin); } @NotNull @@ -31,4 +33,9 @@ public class Manager { public UsersManager users() { return users; } + + @NotNull + public RequestsManager requests() { + return requests; + } } diff --git a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java similarity index 61% rename from common/src/main/java/net/william278/huskhomes/request/RequestManager.java rename to common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index 3202fb61..a5e80fe7 100644 --- a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -1,22 +1,22 @@ -package net.william278.huskhomes.request; +package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.network.Request; +import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; +import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.teleport.TeleportBuilder; +import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; -import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TimedTeleport; import org.jetbrains.annotations.NotNull; import java.time.Instant; import java.util.*; -import java.util.concurrent.CompletableFuture; /** * Manages {@link TeleportRequest}s between players */ -public class RequestManager { +public class RequestsManager { @NotNull private final HuskHomes plugin; @@ -31,7 +31,7 @@ public class RequestManager { */ private final Set ignoringRequests; - public RequestManager(@NotNull HuskHomes implementation) { + public RequestsManager(@NotNull HuskHomes implementation) { this.plugin = implementation; this.requests = new HashMap<>(); this.ignoringRequests = new HashSet<>(); @@ -79,7 +79,7 @@ public class RequestManager { */ public void removeTeleportRequest(@NotNull String requesterName, @NotNull User recipient) { this.requests.computeIfPresent(recipient.getUuid(), (uuid, requests) -> { - requests.removeIf(teleportRequest -> teleportRequest.requesterName.equalsIgnoreCase(requesterName)); + requests.removeIf(teleportRequest -> teleportRequest.getRequesterName().equalsIgnoreCase(requesterName)); return requests.isEmpty() ? null : requests; }); } @@ -107,66 +107,44 @@ public class RequestManager { */ public Optional getTeleportRequest(@NotNull String requesterName, @NotNull User recipient) { return this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream() - .filter(request -> request.requesterName.equalsIgnoreCase(requesterName)) + .filter(request -> request.getRequesterName().equalsIgnoreCase(requesterName)) .filter(request -> !request.hasExpired()) .findFirst() .or(() -> this.requests.getOrDefault(recipient.getUuid(), new LinkedList<>()).stream() - .filter(request -> request.requesterName.equalsIgnoreCase(requesterName)) + .filter(request -> request.getRequesterName().equalsIgnoreCase(requesterName)) .findFirst()); } /** * Sends a teleport request of the given type to the specified user, by name, if they exist. * - * @param requester The user making the request - * @param targetUser The user to send the request to - * @param requestType The type of request to send - * @return A {@link CompletableFuture} that will return the request that was sent if it was sent successfully, - * or an empty {@link Optional} if the request was not sent + * @param requester The user making the request + * @param targetUser The user to send the request to + * @param type The type of request to send */ - 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().getTeleportRequestExpiryTime()); + public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, @NotNull TeleportRequest.Type type) throws IllegalArgumentException { + final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime(); + final TeleportRequest request = new TeleportRequest(requester, type, expiry); final Optional localTarget = plugin.findOnlinePlayer(targetUser); if (localTarget.isPresent()) { if (localTarget.get().equals(requester)) { - return CompletableFuture.completedFuture(Optional.empty()); + throw new IllegalArgumentException("Cannot send a teleport request to yourself"); } - request.recipientName = localTarget.get().getUsername(); - return CompletableFuture.completedFuture(sendLocalTeleportRequest(request, localTarget.get())); + request.setRecipientName(localTarget.get().getUsername()); + sendLocalTeleportRequest(request, localTarget.get()); + return; } // If the player couldn't be found locally, send the request cross-server if (plugin.getSettings().isCrossServer()) { - // Find the matching networked target - return plugin.getMessenger().findPlayer(requester, targetUser).thenApplyAsync(networkedTarget -> { - if (networkedTarget.isEmpty()) { - return Optional.empty(); - } - - // Use the network messenger to send the request - request.recipientName = networkedTarget.get(); - return Request.builder() - .withType(Request.MessageType.TELEPORT_REQUEST) - .withPayload(Payload.withTeleportRequest(request)) - .withTargetPlayer(networkedTarget.get()) - .build().send(requester, plugin) - .thenApply(reply -> { - if (reply.isPresent()) { - final TeleportRequest result = reply.get().getPayload().getTeleportRequest(); - if (result == null || result.status == TeleportRequest.RequestStatus.IGNORED) { - return null; - } - return result; - } - return null; - }) - .thenApply(Optional::ofNullable) - .join(); - }); + request.setRecipientName(targetUser); + Message.builder() + .type(Message.Type.TELEPORT_REQUEST) + .payload(Payload.withTeleportRequest(request)) + .target(targetUser) + .build().send(plugin.getMessenger(), requester); } - return CompletableFuture.completedFuture(Optional.empty()); + throw new IllegalArgumentException("Player not found"); } /** @@ -177,28 +155,28 @@ public class RequestManager { * @return the {@link TeleportRequest} that was sent if it could be sent, otherwise an empty optional if it was not * sent because the recipient is ignoring requests or is vanished ({@link OnlineUser#isVanished()}) */ - public Optional sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) { + public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) { + // Silently ignore the request if the recipient is ignoring requests or is vanished if (isIgnoringRequests(recipient) || recipient.isVanished()) { - request.status = TeleportRequest.RequestStatus.IGNORED; - return Optional.empty(); + request.setStatus(TeleportRequest.Status.IGNORED); + return; } // If the person already has an unexpired request of the same type by this player, don't bother sending another - final Optional existingRequest = getTeleportRequest(request.requesterName, recipient); + final Optional existingRequest = getTeleportRequest(request.getRequesterName(), recipient); if (existingRequest.isPresent()) { - if (existingRequest.get().type == request.type && !existingRequest.get().hasExpired()) { - return Optional.of(request); + if (existingRequest.get().getType() == request.getType() && !existingRequest.get().hasExpired()) { + return; } } // Add the request and display a message to the recipient addTeleportRequest(request, recipient); - plugin.getLocales().getLocale((request.type == TeleportRequest.RequestType.TPA ? "tpa" : "tpahere") - + "_request_received", request.requesterName) + plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere") + + "_request_received", request.getRequesterName()) .ifPresent(recipient::sendMessage); - plugin.getLocales().getLocale("teleport_request_buttons", request.requesterName) + plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) .ifPresent(recipient::sendMessage); - return Optional.of(request); } /** @@ -261,7 +239,7 @@ public class RequestManager { private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient, boolean accepted) { // Remove the request(s) from the sender from the recipient's queue - removeTeleportRequest(request.requesterName, recipient); + removeTeleportRequest(request.getRequesterName(), recipient); // Check if the request has expired if (request.hasExpired()) { @@ -271,39 +249,21 @@ public class RequestManager { // Send request response confirmation to the recipient plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation", - request.requesterName) + request.getRequesterName()) .ifPresent(recipient::sendMessage); - request.status = accepted ? TeleportRequest.RequestStatus.ACCEPTED : TeleportRequest.RequestStatus.DECLINED; + request.setStatus(accepted ? TeleportRequest.Status.ACCEPTED : TeleportRequest.Status.DECLINED); // Send request response to the sender - final Optional localRequester = plugin.findOnlinePlayer(request.requesterName); + final Optional localRequester = plugin.findOnlinePlayer(request.getRequesterName()); if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); } else if (plugin.getSettings().isCrossServer()) { - // Ensure the sender is still online - plugin.getMessenger() - .findPlayer(recipient, request.requesterName) - .thenApplyAsync(networkedTarget -> { - if (networkedTarget.isEmpty()) { - plugin.getLocales().getLocale("error_teleport_request_sender_not_online") - .ifPresent(recipient::sendMessage); - return false; - } - - return Request.builder() - .withType(Request.MessageType.TELEPORT_REQUEST_RESPONSE) - .withPayload(Payload.withTeleportRequest(request)) - .withTargetPlayer(networkedTarget.get()) - .build().send(recipient, plugin) - .thenApply(Optional::isPresent) - .join(); - }) - .thenAccept(online -> { - if (!online) { - plugin.getLocales().getLocale("error_teleport_request_sender_not_online") - .ifPresent(recipient::sendMessage); - } - }); + Message.builder() + .type(Message.Type.TELEPORT_REQUEST_RESPONSE) + .payload(Payload.withTeleportRequest(request)) + .target(request.getRequesterName()) + .build() + .send(plugin.getMessenger(), recipient); } else { plugin.getLocales().getLocale("error_teleport_request_sender_not_online") .ifPresent(recipient::sendMessage); @@ -311,19 +271,18 @@ 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) { + if (accepted && request.getType() == TeleportRequest.Type.TPA_HERE) { + final TeleportBuilder builder = Teleport.builder(plugin) + .teleporter(recipient); + // Strict /tpahere requests will teleport to where the sender was when typing the command - if (plugin.getSettings().isStrictTpaHereRequests()) { - Teleport.builder(plugin, recipient) - .setTarget(request.requesterPosition) - .toTimedTeleport() - .thenAccept(TimedTeleport::execute); + if (plugin.getSettings().doStrictTpaHereRequests()) { + builder.target(request.getRequesterPosition()); } else { - Teleport.builder(plugin, recipient) - .setTarget(request.requesterName) - .toTimedTeleport() - .thenAccept(TimedTeleport::execute); + builder.target(request.getRequesterName()); } + + builder.toTimedTeleport().execute(); } } @@ -335,16 +294,17 @@ public class RequestManager { * @param request The {@link TeleportRequest} to handle */ public void handleLocalRequestResponse(@NotNull OnlineUser requester, @NotNull TeleportRequest request) { - boolean accepted = request.status == TeleportRequest.RequestStatus.ACCEPTED; + boolean accepted = request.getStatus() == TeleportRequest.Status.ACCEPTED; plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined"), - request.recipientName).ifPresent(requester::sendMessage); + request.getRecipientName()).ifPresent(requester::sendMessage); // If the request is a tpa request, teleport the requester to the recipient - if (accepted && (request.type == TeleportRequest.RequestType.TPA)) { - Teleport.builder(plugin, requester) - .setTarget(request.recipientName) + if (accepted && (request.getType() == TeleportRequest.Type.TPA)) { + Teleport.builder(plugin) + .teleporter(requester) + .target(request.getRecipientName()) .toTimedTeleport() - .thenAccept(TimedTeleport::execute); + .execute(); } } diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 0f5a9bfa..71ed9403 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.ValidationException; +import net.william278.huskhomes.util.ValidationException; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.position.Warp; @@ -18,11 +18,11 @@ public class WarpsManager { 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); + throw new ValidationException(ValidationException.Type.NAME_TAKEN); } if (!plugin.getValidator().isValidName(name)) { - throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + throw new ValidationException(ValidationException.Type.NAME_INVALID); } final Warp warp = existingWarp @@ -43,7 +43,7 @@ public class WarpsManager { public void deleteWarp(@NotNull String name) { final Optional warp = plugin.getDatabase().getWarp(name); if (warp.isEmpty()) { - throw new ValidationException(ValidationException.ValidationError.NOT_FOUND); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } plugin.getDatabase().deleteWarp(warp.get().getUuid()); } @@ -55,11 +55,11 @@ public class WarpsManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } if (!plugin.getValidator().isValidName(newName)) { - throw new ValidationException(ValidationException.ValidationError.NAME_INVALID); + throw new ValidationException(ValidationException.Type.NAME_INVALID); } final Warp warp = optionalWarp.get(); @@ -70,7 +70,7 @@ public class WarpsManager { 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); + throw new ValidationException(ValidationException.Type.NOT_FOUND); } final Warp warp = optionalWarp.get(); diff --git a/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java b/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java deleted file mode 100644 index ca67901b..00000000 --- a/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.william278.huskhomes.migrator; - -import net.william278.huskhomes.HuskHomes; -import org.jetbrains.annotations.NotNull; - -import java.util.concurrent.CompletableFuture; - -/** - * A migrator that imports legacy and other plugin's data into HuskHomes' format. - */ -public abstract class Migrator { - - protected final HuskHomes plugin; - - protected Migrator(@NotNull HuskHomes implementor) { - this.plugin = implementor; - } - - /** - * Start the migrator - * - * @return A future that will be completed when the migrator is done - */ - public abstract CompletableFuture start(); - - /** - * Handle a command that sets migrator configuration parameters - * - * @param args The command arguments - */ - public abstract void handleConfigurationCommand(@NotNull String[] args); - - /** - * Obfuscates a data string to prevent important data from being logged to console - * - * @param dataString The data string to obfuscate - * @return The data string obfuscated with stars (*) - */ - @NotNull - protected final String obfuscateDataString(@NotNull String dataString) { - return (dataString.length() > 1 ? dataString.charAt(0) + "*".repeat(dataString.length() - 1) : ""); - } - - /** - * Get the unique identifier of the migrator - * - * @return The unique identifier of the migrator - */ - @NotNull - public abstract String getIdentifier(); - - /** - * Get the display name of the migrator - * - * @return The name of the migrator - */ - @NotNull - public abstract String getName(); - - /** - * Get the help splash menu of the migrator - * - * @return The help splash menu of the migrator - */ - @NotNull - public abstract String getHelpMenu(); - -} diff --git a/common/src/main/java/net/william278/huskhomes/network/Broker.java b/common/src/main/java/net/william278/huskhomes/network/Broker.java index 47e45ae1..f4164460 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Broker.java +++ b/common/src/main/java/net/william278/huskhomes/network/Broker.java @@ -1,19 +1,14 @@ package net.william278.huskhomes.network; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.request.TeleportRequest; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.teleport.Teleport; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.CompletableFuture; - public abstract class Broker { protected final HuskHomes plugin; - private final Map> outboundMessages = new HashMap<>(); /** * Create a new broker @@ -34,45 +29,31 @@ public abstract class Broker { if (message.getSourceServer().equals(getServer()) || receiver == null) { return; } - if (message.getDirection() == Message.Direction.INBOUND) { - this.outboundMessages.getOrDefault(message.getUuid(), new CompletableFuture<>()).complete(message); - this.outboundMessages.remove(message.getUuid()); - return; - } switch (message.getType()) { - case TELEPORT_TO_POSITION_REQUEST -> { - if (message.getPayload().getPosition() != null) { - Teleport.builder(plugin, receiver) - .setTarget(message.getPayload().getPosition()).toTeleport() - .thenAccept(teleport -> teleport.execute() - .thenAccept(result -> message.reply( - this, - receiver, - Payload.withTeleportResult(result.getState()) - ))); - return; - } - } - case POSITION_REQUEST -> message.reply(this, receiver, Payload.withPosition(receiver.getPosition())); - case TELEPORT_REQUEST -> { - if (message.getPayload().getTeleportRequest() != null) { - message.reply(this, receiver, plugin.getRequestManager() - .sendLocalTeleportRequest(message.getPayload().getTeleportRequest(), receiver) - .map(Payload::withTeleportRequest) - .orElse(Payload.empty())); - return; - } - message.reply(this, receiver, Payload.empty()); - } - case TELEPORT_REQUEST_RESPONSE -> { - if (message.getPayload().getTeleportRequest() != null) { - final TeleportRequest request = message.getPayload().getTeleportRequest(); - plugin.getRequestManager().handleLocalRequestResponse(receiver, request); - message.reply(this, receiver, Payload.withTeleportRequest(request)); - return; - } - message.reply(this, receiver, Payload.empty()); - } + case TELEPORT_TO_POSITION -> message.getPayload() + .getPosition().ifPresent(position -> Teleport.builder(plugin) + .teleporter(receiver) + .target(position) + .toTeleport() + .execute()); + case TELEPORT_TO_NETWORKED_POSITION -> Message.builder() + .type(Message.Type.TELEPORT_TO_POSITION) + .target(message.getSender()) + .payload(Payload.withPosition(receiver.getPosition())) + .build().send(this, receiver); + case TELEPORT_TO_NETWORKED_USER -> message.getPayload() + .getString().ifPresent(target -> Message.builder() + .type(Message.Type.TELEPORT_TO_NETWORKED_POSITION) + .target(target) + .build().send(this, receiver)); + case TELEPORT_REQUEST -> message.getPayload() + .getTeleportRequest() + .ifPresent(teleportRequest -> plugin.getManager().requests() + .sendLocalTeleportRequest(teleportRequest, receiver)); + case TELEPORT_REQUEST_RESPONSE -> message.getPayload() + .getTeleportRequest() + .ifPresent(teleportRequest -> plugin.getManager().requests() + .handleLocalRequestResponse(receiver, teleportRequest)); } } @@ -99,11 +80,6 @@ public abstract class Broker { */ public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server); - @NotNull - protected Map> getOutboundMessages() { - return outboundMessages; - } - /** * Terminate the broker */ @@ -120,23 +96,23 @@ public abstract class Broker { return plugin.getServerName(); } - /** - * Identifies types of message brokers - */ - public enum Type { - PLUGIN_MESSAGE("Plugin Messages"), - REDIS("Redis"); - @NotNull - private final String displayName; +/** + * Identifies types of message brokers + */ +public enum Type { + PLUGIN_MESSAGE("Plugin Messages"), + REDIS("Redis"); + @NotNull + private final String displayName; - Type(@NotNull String displayName) { - this.displayName = displayName; - } - - @NotNull - public String getDisplayName() { - return displayName; - } + Type(@NotNull String displayName) { + this.displayName = displayName; } + @NotNull + public String getDisplayName() { + return displayName; + } +} + } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/network/Message.java b/common/src/main/java/net/william278/huskhomes/network/Message.java index dc74829e..680a4343 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Message.java +++ b/common/src/main/java/net/william278/huskhomes/network/Message.java @@ -5,7 +5,6 @@ import net.william278.huskhomes.user.OnlineUser; import org.jetbrains.annotations.NotNull; import java.util.UUID; -import java.util.concurrent.CompletableFuture; /** * Represents a message sent by a {@link Broker} cross-server. See {@link #builder()} for @@ -27,8 +26,6 @@ public class Message { private String sender; @Expose private String sourceServer; - @Expose - private Direction direction; private Message(@NotNull Type type, @NotNull String target, @NotNull Payload payload) { this.type = type; @@ -45,22 +42,10 @@ public class Message { return new Builder(); } - public CompletableFuture send(@NotNull Broker broker, @NotNull OnlineUser sender) { + public void send(@NotNull Broker broker, @NotNull OnlineUser sender) { this.sender = sender.getUsername(); this.sourceServer = broker.getServer(); - this.direction = Direction.OUTBOUND; - final CompletableFuture future = new CompletableFuture<>(); - broker.getOutboundMessages().put(getUuid(), future); broker.send(this, sender); - return future; - } - - public void reply(@NotNull Broker broker, @NotNull OnlineUser receiver, @NotNull Payload payload) { - this.sender = receiver.getUsername(); - this.sourceServer = broker.getServer(); - this.direction = Direction.INBOUND; - this.payload = payload; - broker.send(this, receiver); } @NotNull @@ -88,11 +73,6 @@ public class Message { return sourceServer; } - @NotNull - public Direction getDirection() { - return direction; - } - @NotNull public UUID getUuid() { return id; @@ -138,21 +118,10 @@ public class Message { * Different types of cross-server messages */ public enum Type { - TELEPORT_TO_POSITION_REQUEST, - POSITION_REQUEST, + TELEPORT_TO_POSITION, + TELEPORT_TO_NETWORKED_POSITION, TELEPORT_REQUEST, - POSITION_RESPONSE, TELEPORT_REQUEST_RESPONSE - } - - public enum Direction { - /** - * The message is being sent from the sender to the target - */ - OUTBOUND, - /** - * The message is being sent from the target to the sender - */ - INBOUND + POSITION_RESPONSE, TELEPORT_TO_NETWORKED_USER, TELEPORT_REQUEST_RESPONSE } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/network/Payload.java b/common/src/main/java/net/william278/huskhomes/network/Payload.java index 7e67bde7..a27e7d7d 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Payload.java +++ b/common/src/main/java/net/william278/huskhomes/network/Payload.java @@ -1,28 +1,33 @@ package net.william278.huskhomes.network; +import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.request.TeleportRequest; +import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.teleport.TeleportResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Optional; + /** - * Represents a payload sent in a cross-server {@link Request} + * Represents a payload sent in a cross-server {@link Message} */ public class Payload { @Nullable + @Expose private Position position; @Nullable - @SerializedName("teleport_result") - private TeleportResult resultState; - - @Nullable + @Expose @SerializedName("teleport_request") private TeleportRequest teleportRequest; + @Nullable + @Expose + private String string; + /** * Returns an empty cross-server message payload * @@ -46,19 +51,6 @@ public class Payload { return payload; } - /** - * Returns a payload containing a {@link TeleportResult} - * - * @param resultState the teleport to send - * @return a payload containing the teleport result - */ - @NotNull - public static Payload withTeleportResult(@NotNull TeleportResult resultState) { - final Payload payload = new Payload(); - payload.resultState = resultState; - return payload; - } - /** * Returns a payload containing a {@link TeleportRequest} * @@ -72,30 +64,35 @@ public class Payload { return payload; } + /** + * A string field + */ + @NotNull + public static Payload withString(@NotNull String target) { + final Payload payload = new Payload(); + payload.string = target; + return payload; + } + private Payload() { } /** * A position field */ - @Nullable - public Position getPosition() { - return position; + public Optional getPosition() { + return Optional.ofNullable(position); + } + + + public Optional getTeleportRequest() { + return Optional.ofNullable(teleportRequest); } /** - * A teleport result field + * A string field */ - @Nullable - public TeleportResult getResultState() { - return resultState; - } - - /** - * A teleport request field - */ - @Nullable - public TeleportRequest getTeleportRequest() { - return teleportRequest; + public Optional getString() { + return Optional.ofNullable(string); } } diff --git a/common/src/main/java/net/william278/huskhomes/position/Position.java b/common/src/main/java/net/william278/huskhomes/position/Position.java index 3888e1e4..ff965e21 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -1,5 +1,6 @@ package net.william278.huskhomes.position; +import net.william278.huskhomes.teleport.Target; import org.jetbrains.annotations.NotNull; import java.util.Optional; @@ -8,7 +9,7 @@ import java.util.UUID; /** * Represents a position - a {@link Location} somewhere on the proxy network or server */ -public class Position extends Location { +public class Position extends Location implements Target { private String server; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/CompletedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/CompletedTeleport.java deleted file mode 100644 index 0a380afd..00000000 --- a/common/src/main/java/net/william278/huskhomes/teleport/CompletedTeleport.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.william278.huskhomes.teleport; - -import net.william278.huskhomes.config.Locales; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; -import net.william278.huskhomes.position.Position; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Optional; - -/** - * Represents the result of executing a {@link Teleport} or {@link TimedTeleport} - * - * @since 3.1 - */ -public class CompletedTeleport { - - /** - * The state of the {@link Teleport} - */ - @NotNull - private final TeleportResult state; - - /** - * The {@link User} who is doing the teleporting - */ - @Nullable - private final User teleporter; - - /** - * The {@link Position} the teleporter should be teleported to - */ - @Nullable - private final Position destination; - - /** - * Internal - Create a new {@link CompletedTeleport} (use {@link #from(TeleportResult, Teleport)}) - * - * @param state The {@link TeleportResult} of completing the teleport - * @param teleporter The {@link User} who is doing the teleporting - * @param destination The {@link Position} the teleporter should be teleported to - * @since 3.1 - */ - private CompletedTeleport(@NotNull TeleportResult state, @Nullable User teleporter, @Nullable Position destination) { - this.state = state; - this.teleporter = teleporter; - this.destination = destination; - } - - /** - * Create a new {@link CompletedTeleport} for a {@link Teleport} with an outcome {@link TeleportResult} - * - * @param state The outcome {@link TeleportResult} - * @param teleport The {@link Teleport} that was executed - * @return The {@link CompletedTeleport} of executing the supplied {@link Teleport} - * @since 3.1 - */ - public static CompletedTeleport from(@NotNull TeleportResult state, @NotNull Teleport teleport) { - return new CompletedTeleport(state, teleport.teleporter, teleport.target); - } - - /** - * Get the state of the {@link Teleport} after execution has finished - * - * @return The {@link TeleportResult} of the teleport - * @since 3.1 - */ - @NotNull - public TeleportResult getState() { - return state; - } - - /** - * Returns if the teleport was successful - * - * @return {@code true} if the teleport was successful, {@code false} otherwise - * @since 3.1 - */ - public boolean successful() { - return state.successful; - } - - /** - * Get the {@link User} who is doing the teleporting - * - * @return The teleporter, if they were resolved - * @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TELEPORTER_NOT_RESOLVED} - * @since 3.1 - */ - public Optional getTeleporter() { - return Optional.ofNullable(teleporter); - } - - /** - * Get the target {@link Position} the teleporter should have been teleported to - * - * @return The target position, if it was resolved - * @implNote The optional will return empty if the state is {@link TeleportResult#FAILED_TARGET_NOT_RESOLVED} - * @since 3.1 - */ - public Optional getDestination() { - return Optional.ofNullable(destination); - } - - /** - * Send an {@link OnlineUser} the corresponding message indicating the state of the teleport once it has executred - * - * @param locales the {@link Locales} instance to use - * @param user the {@link OnlineUser} to send the message to - * @since 3.1 - */ - public void sendResultMessage(@NotNull Locales locales, @NotNull OnlineUser user) { - this.state.sendResultMessage(locales, user); - } - -} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Target.java b/common/src/main/java/net/william278/huskhomes/teleport/Target.java new file mode 100644 index 00000000..f9ce8279 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/teleport/Target.java @@ -0,0 +1,12 @@ +package net.william278.huskhomes.teleport; + +import org.jetbrains.annotations.NotNull; + +public interface Target { + + @NotNull + static Target username(@NotNull String target) { + return new Username(target); + } + +} 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 1ff3ab6e..13d7035a 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -1,213 +1,146 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import java.util.Arrays; +import java.util.List; import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -/** - * Represents a teleport in the process of being executed - * - * @since 3.1 - */ public class Teleport { - /** - * Internal - Instance of the implementing HuskHomes plugin - */ - @NotNull private final HuskHomes plugin; + protected final OnlineUser executor; + protected final Teleportable teleporter; + protected final Target target; + protected final Type type; + protected final boolean updateLastPosition; + protected final List economyActions; + private final boolean async; - /** - * The {@link User} who is doing the teleporting - */ - @Nullable - public final User teleporter; - - /** - * The {@link OnlineUser} on this server executing the teleport. - *

- * Can be the same as the {@link #teleporter}, but not necessarily - */ - @NotNull - public final OnlineUser executor; - - /** - * The target {@link Position} the teleporter should be teleported to - */ - @Nullable - public final Position target; - - /** - * The {@link TeleportType type} of the teleport - */ - @NotNull - public final TeleportType type; - - /** - * {@link EconomyHook.EconomyAction}s to be checked against the {@link #executor executor}'s balance - */ - @NotNull - public final Set economyActions; - - /** - * Whether to update the {@link #teleporter teleporter}'s last position (i.e. their {@code /back} position) - */ - public final boolean updateLastPosition; - - /** - * Internal - use TeleportBuilder to instantiate a teleport - */ - protected Teleport(@Nullable User teleporter, @NotNull OnlineUser executor, @Nullable Position target, - @NotNull TeleportType type, @NotNull Set economyActions, - final boolean updateLastPosition, @NotNull HuskHomes plugin) { - this.teleporter = teleporter; + protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target, + @NotNull Type type, boolean updateLastPosition, @NotNull List actions, + @NotNull HuskHomes plugin) { this.executor = executor; + this.teleporter = teleporter; this.target = target; this.type = type; - this.economyActions = economyActions; - this.plugin = plugin; this.updateLastPosition = updateLastPosition; + this.economyActions = actions; + this.async = plugin.getSettings().isAsynchronousTeleports(); + this.plugin = plugin; } - /** - * Create a teleport builder with an executor to carry it out - * - * @param plugin Instance of the implementing HuskHomes plugin - * @param executor The {@link OnlineUser} on this server executing the teleport. - * Not necessarily the person being teleported, which can be set independently with - * {{@link TeleportBuilder#setTeleporter(User)}} - * @return A new {@link TeleportBuilder} instance - */ - public static TeleportBuilder builder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) { - return new TeleportBuilder(plugin, executor); + @NotNull + public static TeleportBuilder builder(@NotNull HuskHomes plugin) { + return new TeleportBuilder(plugin); } - /** - * Execute this teleport - * - * @return A {@link CompletableFuture} that completes when the teleport is finished - */ - public CompletableFuture execute() { - // Validate the teleporter - if (teleporter == null) { - return CompletableFuture.completedFuture(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); - } + public void execute() throws TeleportationException { + final Optional localTeleporter = resolveLocalTeleporter(); - // Validate the target - if (target == null) { - return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); - } - - // Check economy actions - for (EconomyHook.EconomyAction economyAction : economyActions) { - if (!plugin.validateEconomyCheck(executor, economyAction)) { - return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); + // Teleport a user on another server + if (localTeleporter.isEmpty()) { + final Username teleporter = (Username) this.teleporter; + if (!plugin.getSettings().isCrossServer()) { + throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND); } + + if (target instanceof Username username) { + Message.builder() + .type(Message.Type.TELEPORT_TO_NETWORKED_USER) + .target(username.name()) + .payload(Payload.withString(teleporter.name())) + .build().send(plugin.getMessenger(), executor); + return; + } + + Message.builder() + .type(Message.Type.TELEPORT_TO_POSITION) + .target(teleporter.name()) + .payload(Payload.withPosition((Position) target)) + .build().send(plugin.getMessenger(), executor); + return; } - // Run the teleport and apply economy actions - return run(teleporter) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)) - .thenApply(result -> { - if (teleporter instanceof OnlineUser user) { - finish(user, result); - } - return result; - }); + // Teleport a local user + final OnlineUser teleporter = localTeleporter.get(); + if (target instanceof Username username) { + final Optional localTarget = username.findLocally(plugin); + if (localTarget.isPresent()) { + teleporter.teleportLocally(localTarget.get().getPosition(), async); + return; + } + + if (plugin.getSettings().isCrossServer()) { + Message.builder() + .type(Message.Type.TELEPORT_TO_NETWORKED_POSITION) + .target(username.name()) + .build().send(plugin.getMessenger(), executor); + return; + } + + throw new TeleportationException(TeleportationException.Type.TARGET_NOT_FOUND); + } + teleporter.teleportLocally((Position) target, async); + } + + @NotNull + private Optional resolveLocalTeleporter() throws TeleportationException { + if (this.teleporter instanceof Username username) { + return username.findLocally(plugin); + } + return Optional.of((OnlineUser) this.teleporter); + } + + @NotNull + public Type getType() { + return type; + } + + @NotNull + public Teleportable getTeleporter() { + return teleporter; + } + + @NotNull + public Target getTarget() { + return target; } /** - * Run the teleport, either locally or over the network - * - * @param teleporter The {@link User} who is doing the teleporting - * @return A {@link CompletableFuture} that completes when the teleport is finished + * Represents the type of teleport being used */ - private CompletableFuture run(@NotNull User teleporter) { - return teleporter instanceof OnlineUser onlineUser - ? teleportLocalUser(onlineUser) - : teleportNetworkedUser(); - } + public enum Type { - /** - * Finish the teleport, finalize economy transactions if successful and send message - * - * @param teleporter The {@link OnlineUser} who was teleported - * @param result The {@link TeleportResult} of the teleport - */ - private void finish(@NotNull OnlineUser teleporter, @NotNull CompletedTeleport result) { - if (result.successful()) { - // Complete economy transactions - economyActions.forEach(economyAction -> plugin.performEconomyTransaction(executor, economyAction)); + TELEPORT(0), + RESPAWN(1); - // Play sound effect if successful - plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_COMPLETE) - .ifPresent(teleporter::playSound); + private final int typeId; + + Type(final int typeId) { + this.typeId = typeId; } - // Send result message - result.sendResultMessage(plugin.getLocales(), teleporter); - } - - /** - * Teleport a local user - * - * @param teleporter The teleporter - * @return A {@link CompletableFuture} that completes when the teleport is finished - */ - private CompletableFuture teleportLocalUser(@NotNull OnlineUser teleporter) { - assert target != null; - - // Dispatch the teleport event and update the player's last position - plugin.getEventDispatcher().dispatchTeleportEvent(this); - if (updateLastPosition && !plugin.getSettings().isBackCommandSaveOnTeleportEvent() && type == TeleportType.TELEPORT) { - plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); + /** + * Returns a {@link Type} by its type id. + * + * @param typeId The type id of the {@link Type} to return. + * @return The {@link Type} of the given type id. + */ + public static Optional getTeleportType(int typeId) { + return Arrays.stream(values()) + .filter(type -> type.getTypeId() == typeId) + .findFirst(); } - // If the target position is local, finalize economy transactions and teleport the player - if (!plugin.getSettings().isCrossServer() || target.getServer().equals(plugin.getServerName())) { - return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports()); + public int getTypeId() { + return typeId; } - - // If the target position is on another server, execute a cross-server teleport - plugin.getDatabase().setCurrentTeleport(teleporter, this); - plugin.getMessenger().changeServer(teleporter, target.getServer()); - return CompletableFuture.completedFuture(TeleportResult.COMPLETED_CROSS_SERVER); } - - /** - * Teleport a user not on this server but on the proxy network - * - * @return A {@link CompletableFuture} that completes when the teleport is finished. - * Successful cross-server teleports will return {@link TeleportResult#COMPLETED_CROSS_SERVER}. - * @implNote Cross-server teleports will return with a {@link TeleportResult#FAILED_INVALID_SERVER} result if the - * target server is not online, or connection timed out - */ - private CompletableFuture teleportNetworkedUser() { - assert target != null; - assert teleporter != null; - - // Send a network message to a user on another server to teleport them to the target position - return Message.builder() - .type(Message.Type.TELEPORT_TO_POSITION_REQUEST) - .payload(Payload.withPosition(target)) - .target(teleporter.getUsername()) - .build().send(plugin.getMessenger(), executor) - .thenApply(result -> Optional.ofNullable(result.getPayload().getResultState()) - .orElse(TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED)); - } - -} +} \ No newline at end of file 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 40b5f7ed..ac9c1a6b 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -2,240 +2,101 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.hook.EconomyHook; -import net.william278.huskhomes.network.Request; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; -import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.Position; import org.jetbrains.annotations.NotNull; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; +import java.util.List; -/** - * A builder for {@link Teleport}s and {@link TimedTeleport}s - * - * @since 3.1 - */ -@SuppressWarnings("unused") public class TeleportBuilder { - - // Instance of the implementing plugin - @NotNull private final HuskHomes plugin; - - /** - * The executor of the teleport; the one who triggered the teleport to happen; - * whom may not necessarily the person being teleported - */ - @NotNull - private final OnlineUser executor; - - /** - * The teleporter; the one who is being teleported, to be resolved before construction - */ - private CompletableFuture teleporter; - - /** - * The target position for the teleporter, to be resolved before construction - */ - private CompletableFuture target; - - /** - * List of {@link EconomyHook.EconomyAction}s to check against. - *

- * Note that these are checked against the {@link #executor executor} of the teleport; - * not necessarily the one doing the teleporting - */ - private final Set economyActions = new HashSet<>(); - - /** - * The type of teleport. Defaults to {@link TeleportType#TELEPORT} - */ - private TeleportType type = TeleportType.TELEPORT; - - /** - * Whether this teleport should update the user's last position (i.e. their {@code /back} position) - */ + private OnlineUser executor; + private Teleportable teleporter; + private Target target; private boolean updateLastPosition = true; + private Teleport.Type type = Teleport.Type.TELEPORT; + private List economyActions = List.of(); - protected TeleportBuilder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) { + protected TeleportBuilder(@NotNull HuskHomes plugin) { this.plugin = plugin; + } + + @NotNull + public Teleport toTeleport() throws IllegalStateException { + validateTeleport(); + return new Teleport(executor, teleporter, target, type, updateLastPosition, economyActions, plugin); + } + + @NotNull + public TimedTeleport toTimedTeleport() throws IllegalStateException { + validateTeleport(); + if (!(teleporter instanceof OnlineUser onlineTeleporter)) { + throw new IllegalStateException("Teleporter must be an OnlineUser for timed teleportation"); + } + return new TimedTeleport(executor, onlineTeleporter, target, type, + plugin.getSettings().getTeleportWarmupTime(), updateLastPosition, economyActions, plugin); + } + + private void validateTeleport() throws IllegalStateException { + if (executor == null) { + if (teleporter instanceof OnlineUser onlineUser) { + executor = onlineUser; + } else { + throw new IllegalStateException("Executor must be set if teleporter is not an OnlineUser"); + } + } + if (teleporter == null) { + throw new IllegalStateException("Teleporter must be set"); + } + if (target == null) { + throw new IllegalStateException("Target must be set"); + } + } + + @NotNull + public TeleportBuilder executor(@NotNull OnlineUser executor) { this.executor = executor; - this.teleporter = CompletableFuture.completedFuture(executor); - } - - /** - * Set the person being teleported as a {@link User} - * - * @param teleporter The {@link User} who is doing the teleporting - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setTeleporter(@NotNull User teleporter) { - this.teleporter = CompletableFuture.completedFuture(teleporter); return this; } - /** - * Set the person being teleported as the username of a player, which will attempt to be resolved - * into a user at the time of construction - * - * @param teleporterUsername The username of the player who is doing the teleporting - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setTeleporter(@NotNull String teleporterUsername) { - this.teleporter = teleporterUsername; + @NotNull + public TeleportBuilder teleporter(@NotNull Teleportable teleporter) { + this.teleporter = teleporter; return this; } - /** - * Set the target as a {@link Position} - * - * @param position The {@link Position} the teleport is aiming to teleport the {@link #teleporter} to - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setTarget(@NotNull Position position) { - this.target = CompletableFuture.completedFuture(position); + @NotNull + public TeleportBuilder teleporter(@NotNull String teleporter) { + this.teleporter = Teleportable.username(teleporter); return this; } - /** - * Set the target as a {@link Location} on this server - * - * @param location The {@link Location} on this server the teleport is aiming to teleport the {@link #teleporter} to - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setTarget(@NotNull Location location) { - this.target = CompletableFuture.completedFuture(new Position(location, plugin.getServerName())); + @NotNull + public TeleportBuilder target(@NotNull Target target) { + this.target = target; return this; } - /** - * Set the target as the position of a player, specified by their username, who may be on another server. - * - * @param targetUsername The username of the player on the target server the teleport is aiming to teleport the - * {@link #teleporter} to - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setTarget(@NotNull String targetUsername) { - this.target = getPlayerPosition(targetUsername).thenApply(position -> position.orElse(null)); + @NotNull + public TeleportBuilder target(@NotNull String target) { + this.target = Target.username(target); return this; } - /** - * Set the type of teleport - * - * @param type The {@link TeleportType} of the teleport - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder setType(@NotNull TeleportType type) { - this.type = type; - return this; - } - - /** - * Set the economy actions to check against during the teleport - * - * @param economyActions The {@link EconomyHook.EconomyAction}s to check against - * @return The {@link TeleportBuilder} instance - * @implNote These are checked against the {@link #executor executor} of the teleport; - * not necessarily the one doing the teleporting - */ - public TeleportBuilder setEconomyActions(@NotNull Set economyActions) { - this.economyActions.addAll(economyActions); - return this; - } - - /** - * Set the economy actions to check against during the teleport - * - * @param economyActions The {@link EconomyHook.EconomyAction}s to check against - * @return The {@link TeleportBuilder} instance - * @implNote These are checked against the {@link #executor executor} of the teleport; - * not necessarily the one doing the teleporting - */ - public TeleportBuilder setEconomyActions(@NotNull EconomyHook.EconomyAction... economyActions) { - this.economyActions.addAll(Arrays.asList(economyActions)); - return this; - } - - /** - * Set whether this teleport should update the user's last position (i.e. their {@code /back} position) - * - * @param updateLastPosition Whether this teleport should update the user's last position - * @return The {@link TeleportBuilder} instance - */ - public TeleportBuilder doUpdateLastPosition(boolean updateLastPosition) { + @NotNull + public TeleportBuilder updateLastPosition(boolean updateLastPosition) { this.updateLastPosition = updateLastPosition; return this; } - /** - * Resolve the teleporter and target, and construct as an instantly-completing {@link Teleport} - * - * @return The constructed {@link Teleport} - */ - public CompletableFuture toTeleport() { - return CompletableFuture.supplyAsync(() -> { - final User teleporter = this.teleporter.join(); - final Position target = this.target.join(); - - return new Teleport(teleporter, executor, target, type, economyActions, updateLastPosition, plugin); - }).exceptionally(e -> { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create teleport", e); - return null; - }); + @NotNull + public TeleportBuilder economyActions(@NotNull EconomyHook.Action... economyActions) { + this.economyActions = List.of(economyActions); + return this; } - /** - * Resolve the teleporter and target, and construct as a {@link TimedTeleport} - * - * @return The constructed {@link TimedTeleport} - */ - public CompletableFuture toTimedTeleport() { - return CompletableFuture.supplyAsync(() -> { - final User teleporter = this.teleporter.join(); - final Position target = this.target.join(); - final int warmupTime = plugin.getSettings().getTeleportWarmupTime(); - - if (!(teleporter instanceof OnlineUser onlineUser)) { - throw new IllegalStateException("Timed teleports can only be executed for local users"); - } - - return new TimedTeleport(onlineUser, executor, target, type, warmupTime, economyActions, updateLastPosition, plugin); - }).exceptionally(e -> { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create timed teleport", e); - return null; - }); + @NotNull + public TeleportBuilder type(@NotNull Teleport.Type type) { + this.type = type; + return this; } - - /** - * Gets the position of a player by their username, including players on other servers - * - * @param playerName the username of the player being requested - * @return future optionally supplying the player's position, if the player could be found - */ - private CompletableFuture> getPlayerPosition(@NotNull String playerName) { - final Optional localPlayer = plugin.findOnlinePlayer(playerName); - if (localPlayer.isPresent()) { - return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition())); - } - if (plugin.getSettings().isCrossServer()) { - return plugin.getMessenger() - .findPlayer(executor, playerName) - .thenApplyAsync(foundPlayer -> { - if (foundPlayer.isEmpty()) { - return Optional.empty(); - } - return Request.builder() - .withType(Request.MessageType.POSITION_REQUEST) - .withTargetPlayer(playerName) - .build().send(executor, plugin) - .thenApply(reply -> reply.map(message -> message.getPayload().getPosition())).join(); - }); - } - return CompletableFuture.supplyAsync(Optional::empty); - } - } diff --git a/common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java similarity index 55% rename from common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java rename to common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java index 080e0d6c..c2787488 100644 --- a/common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java @@ -1,5 +1,6 @@ -package net.william278.huskhomes.request; +package net.william278.huskhomes.teleport; +import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.Position; @@ -12,51 +13,37 @@ import java.time.Instant; */ public class TeleportRequest { - /** - * The user making the request - */ + @Expose @SerializedName("requester_name") - protected String requesterName; + private String requesterName; - /** - * The position of the requester, relevant in the case of a {@link RequestType#TPA_HERE} request - */ + @Expose @SerializedName("requester_position") - protected Position requesterPosition; + private Position requesterPosition; - /** - * Epoch timestamp when the request will expire - */ + @Expose @SerializedName("expiry_time") - protected long expiryTime; + private long expiryTime; - /** - * The type of request; a {@link RequestType#TPA} or {@link RequestType#TPA_HERE} - */ - protected RequestType type; + @Expose + private Type type; - /** - * The status of the request; a {@link RequestStatus#PENDING}, {@link RequestStatus#ACCEPTED} - * or {@link RequestStatus#DECLINED} - */ - protected RequestStatus status; + @Expose + private Status status; - /** - * The name of the request recipient - */ - protected String recipientName; + @Expose + private String recipientName; /** * Create a teleport request * * @param requester The user making the request */ - protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType, - final long expiryTime) { - this.requesterName = requester.getUsername(); - this.requesterPosition = requester.getPosition(); - this.type = requestType; - this.status = RequestStatus.PENDING; + public TeleportRequest(@NotNull OnlineUser requester, @NotNull TeleportRequest.Type type, final long expiryTime) { + this.setRequesterName(requester.getUsername()); + this.setRequesterPosition(requester.getPosition()); + this.setType(type); + this.setStatus(Status.PENDING); this.expiryTime = expiryTime; } @@ -73,15 +60,70 @@ public class TeleportRequest { return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime)); } + /** + * The name of the request recipient + */ @NotNull public String getRecipientName() { return recipientName; } + public void setRecipientName(@NotNull String recipientName) { + this.recipientName = recipientName; + } + + /** + * The user making the request + */ + public String getRequesterName() { + return requesterName; + } + + public void setRequesterName(String requesterName) { + this.requesterName = requesterName; + } + + /** + * The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request + */ + @NotNull + public Position getRequesterPosition() { + return requesterPosition; + } + + public void setRequesterPosition(Position requesterPosition) { + this.requesterPosition = requesterPosition; + } + + /** + * The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE} + */ + @NotNull + public TeleportRequest.Type getType() { + return type; + } + + public void setType(@NotNull TeleportRequest.Type type) { + this.type = type; + } + + /** + * The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} + * or {@link Status#DECLINED} + */ + @NotNull + public TeleportRequest.Status getStatus() { + return status; + } + + public void setStatus(@NotNull TeleportRequest.Status status) { + this.status = status; + } + /** * Types of teleport requests ({@code /tpa} or {@code /tpahere}) */ - public enum RequestType { + public enum Type { /** * The request is a {@code /tpa} request, where the requester is requesting to teleport to the recipient */ @@ -95,7 +137,7 @@ public class TeleportRequest { /** * The current status of a teleport request */ - protected enum RequestStatus { + public enum Status { /** * The request is currently pending and can be accepted or declined */ diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportType.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportType.java deleted file mode 100644 index d3730eac..00000000 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportType.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.william278.huskhomes.teleport; - -import java.util.Arrays; -import java.util.Optional; - -/** - * Represents the type of teleport being used - */ -public enum TeleportType { - - TELEPORT(0), - RESPAWN(1); - - public final int typeId; - - TeleportType(final int typeId) { - this.typeId = typeId; - } - - /** - * Returns a {@link TeleportType} by its type id. - * - * @param typeId The type id of the {@link TeleportType} to return. - * @return The {@link TeleportType} of the given type id. - */ - public static Optional getTeleportType(int typeId) { - return Arrays.stream(values()) - .filter(type -> type.typeId == typeId) - .findFirst(); - } -} diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java new file mode 100644 index 00000000..ed641a3c --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java @@ -0,0 +1,12 @@ +package net.william278.huskhomes.teleport; + +import org.jetbrains.annotations.NotNull; + +public interface Teleportable { + + @NotNull + static Teleportable username(@NotNull String teleporter) { + return new Username(teleporter); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java new file mode 100644 index 00000000..57b69700 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java @@ -0,0 +1,16 @@ +package net.william278.huskhomes.teleport; + +import org.jetbrains.annotations.NotNull; + +public class TeleportationException extends IllegalArgumentException { + + public TeleportationException(@NotNull Type error) { + super("Error during teleport operation: " + error.name()); + } + + public enum Type { + TELEPORTER_NOT_FOUND, + TARGET_NOT_FOUND, + ALREADY_WARMING_UP, ECONOMY_ACTION_FAILED, WARMUP_ALREADY_MOVING, CANNOT_TELEPORT_TO_SELF + } +} 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 c7bfc695..67a07973 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -9,11 +9,9 @@ import net.william278.huskhomes.position.Position; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; -import java.util.Set; +import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; public class TimedTeleport extends Teleport { @@ -22,12 +20,11 @@ public class TimedTeleport extends Teleport { private final Position startLocation; private final double startHealth; private int timeLeft; - private boolean cancelled = false; - protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target, - @NotNull TeleportType type, int warmupTime, @NotNull Set economyActions, - final boolean updateLastPosition, @NotNull HuskHomes plugin) { - super(teleporter, executor, target, type, economyActions, updateLastPosition, plugin); + protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target, + @NotNull Type type, int warmupTime, boolean updateLastPosition, + @NotNull List actions, @NotNull HuskHomes plugin) { + super(teleporter, executor, target, type, updateLastPosition, actions, plugin); this.plugin = plugin; this.startLocation = teleporter.getPosition(); this.startHealth = teleporter.getHealth(); @@ -41,60 +38,38 @@ public class TimedTeleport extends Teleport { * @return a {@link CompletableFuture} that completes when the teleport is complete or has been cancelled */ @Override - public CompletableFuture execute() { - // If the target has not been resolved, fail the teleport - if (target == null) { - return CompletableFuture.completedFuture(TeleportResult.FAILED_TARGET_NOT_RESOLVED) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); - } - + public void execute() throws TeleportationException { // Check if the teleporter can bypass warmup if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) { - return super.execute(); + super.execute(); + return; } // Check if the teleporter is already warming up to teleport if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) { - return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); + throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP); } // Check economy actions - for (EconomyHook.EconomyAction economyAction : economyActions) { - if (!plugin.validateEconomyCheck(executor, economyAction)) { - return CompletableFuture.completedFuture(TeleportResult.CANCELLED_ECONOMY) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); + for (EconomyHook.Action action : economyActions) { + if (!plugin.validateEconomyCheck(executor, action)) { + throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED); } } // Check if they are moving at the start of the teleport if (teleporter.isMoving()) { - return CompletableFuture.completedFuture(TeleportResult.FAILED_MOVING) - .thenApply(resultState -> CompletedTeleport.from(resultState, this)); + throw new TeleportationException(TeleportationException.Type.WARMUP_ALREADY_MOVING); } // Process the warmup and execute the teleport - return process().thenApplyAsync(ignored -> { - if (cancelled) { - return CompletedTeleport.from(TeleportResult.CANCELLED, this); - } - return super.execute().join(); - }); + this.process(); } - /** - * Start the processing of a {@link TimedTeleport} warmup - * - * @return a future, returning when the teleport has finished - */ - private CompletableFuture process() { - final CompletableFuture timedTeleportFuture = new CompletableFuture<>(); - + private void process() { // Execute the warmup start event plugin.getEventDispatcher().dispatchTeleportWarmupEvent(this, timeLeft).thenAccept(event -> { - // Handle event cancellation if (event.isCancelled()) { - this.cancelled = true; return; } @@ -103,9 +78,9 @@ public class TimedTeleport extends Teleport { plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft)) .ifPresent(teleporter::sendMessage); - // Create a scheduled executor to tick the timed teleport - final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - executor.scheduleAtFixedRate(() -> { + // Run the warmup + final AtomicInteger warmupTaskId = new AtomicInteger(); + final Runnable delayRunnable = (() -> { // Display countdown action bar message if (timeLeft > 0) { plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP) @@ -115,17 +90,17 @@ public class TimedTeleport extends Teleport { } else { plugin.getLocales().getLocale("teleporting_action_bar_processing") .ifPresent(this::sendStatusMessage); + super.execute(); } // Tick (decrement) the timed teleport timer and end it if done - if (tickWarmup()) { + if (tickAndGetIfDone()) { plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid()); - timedTeleportFuture.complete(null); - executor.shutdown(); + plugin.cancelTask(warmupTaskId.get()); } - }, 0, 1, TimeUnit.SECONDS); + }); + warmupTaskId.set(plugin.runAsyncRepeating(delayRunnable, 20)); }); - return timedTeleportFuture; } /** @@ -141,7 +116,7 @@ public class TimedTeleport extends Teleport { * * @return {@code true} if the warmup is complete, {@code false} otherwise */ - private boolean tickWarmup() { + private boolean tickAndGetIfDone() { if (timeLeft <= 0) { return true; } @@ -154,7 +129,6 @@ public class TimedTeleport extends Teleport { .ifPresent(this::sendStatusMessage); plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED) .ifPresent(teleporter::playSound); - cancelled = true; return true; } @@ -166,7 +140,6 @@ public class TimedTeleport extends Teleport { .ifPresent(this::sendStatusMessage); plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_CANCELLED) .ifPresent(teleporter::playSound); - cancelled = true; return true; } @@ -175,11 +148,6 @@ public class TimedTeleport extends Teleport { return false; } - /** - * Send a teleport warmup status message to the configured slot - * - * @param message the message to send - */ private void sendStatusMessage(@NotNull MineDown message) { switch (plugin.getSettings().getTeleportWarmupDisplay()) { case ACTION_BAR -> teleporter.sendActionBar(message); @@ -189,24 +157,14 @@ public class TimedTeleport extends Teleport { } } - /** - * Returns if the player has moved since the timed teleport started - * - * @return {@code true} if the player has moved; {@code false} otherwise - */ private boolean hasTeleporterMoved() { final double maxMovementDistance = 0.1d; double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) + - Math.abs(startLocation.getY() - teleporter.getPosition().getY()) + - Math.abs(startLocation.getZ() - teleporter.getPosition().getZ()); + Math.abs(startLocation.getY() - teleporter.getPosition().getY()) + + Math.abs(startLocation.getZ() - teleporter.getPosition().getZ()); return movementDistance > maxMovementDistance; } - /** - * Returns if the player has taken damage since the timed teleport started - * - * @return {@code true} if the player has taken damage - */ private boolean hasTeleporterTakenDamage() { return teleporter.getHealth() < startHealth; } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Username.java b/common/src/main/java/net/william278/huskhomes/teleport/Username.java new file mode 100644 index 00000000..5a1abcdc --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/teleport/Username.java @@ -0,0 +1,16 @@ +package net.william278.huskhomes.teleport; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public record Username(@NotNull String name) implements Teleportable, Target { + + @NotNull + public Optional findLocally(@NotNull HuskHomes plugin) throws TeleportationException { + return plugin.findOnlinePlayer(name); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java index f653e168..f7ebeccb 100644 --- a/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/OnlineUser.java @@ -11,6 +11,7 @@ import net.kyori.adventure.title.TitlePart; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.TeleportResult; +import net.william278.huskhomes.teleport.Teleportable; import org.intellij.lang.annotations.Subst; import org.jetbrains.annotations.NotNull; @@ -20,7 +21,7 @@ import java.util.concurrent.CompletableFuture; /** * A cross-platform representation of a logged-in {@link User} */ -public abstract class OnlineUser extends User { +public abstract class OnlineUser extends User implements Teleportable { public OnlineUser(@NotNull UUID uuid, @NotNull String username) { super(uuid, username); diff --git a/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java b/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java deleted file mode 100644 index bb4030ae..00000000 --- a/common/src/main/java/net/william278/huskhomes/util/RegexUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -package net.william278.huskhomes.util; - -import java.util.Optional; -import java.util.regex.Pattern; - -import net.william278.huskhomes.position.PositionMeta; -import org.jetbrains.annotations.NotNull; - -/** - * Provides a number of utility regular expressions for checking home name patterns - */ -public final class RegexUtil { - - /** - * Pattern for checking home and warp {@link PositionMeta} description fields - */ - public static final Pattern DESCRIPTION_PATTERN = Pattern.compile("[a-zA-Z\\d\\-_\\s]*"); - - /** - * Pattern for checking home and warp {@link PositionMeta} name fields - */ - public static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z\\d_\\-]+"); - - /** - * Pattern for checking home input fields disambiguated by the owner's name - *

- * e.g. {@code ownerName.homeName} - */ - private static final Pattern OWNER_DISAMBIGUATED_HOME_IDENTIFIER_PATTERN = Pattern.compile("\\w+\\.[^.]{1,16}$"); - - /** - * Match pattern for checking home input fields disambiguated by the owner's name - * - * @param input input string to match - * @return An optional containing the {@link DisambiguatedHomeIdentifier} if matched, otherwise empty if not - */ - public static Optional matchDisambiguatedHomeIdentifier(@NotNull String input) { - if (OWNER_DISAMBIGUATED_HOME_IDENTIFIER_PATTERN.matcher(input).matches()) { - final String[] separatedInput = input.split(Pattern.quote(".")); - return Optional.of(new DisambiguatedHomeIdentifier(separatedInput[0], separatedInput[1])); - } else { - return Optional.empty(); - } - } - - /** - * Represents an identifier for a home or warp {@link PositionMeta} that is disambiguated by the owner's name - * - * @param ownerName the username of a home's owner - * @param homeName the name of a home - */ - public record DisambiguatedHomeIdentifier(String ownerName, String homeName) { - - - /** - * Get the period-separated formatted disambiguated home identifier - * - * @return the formatted disambiguated home identifier (e.g. {@code ownerName.homeName}) - */ - public String toString() { - return ownerName + "." + homeName; - } - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java b/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java index e01b7f34..5fbe57d6 100644 --- a/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java +++ b/common/src/main/java/net/william278/huskhomes/util/TaskRunner.java @@ -7,9 +7,11 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; public interface TaskRunner { - void runAsync(@NotNull Runnable runnable); + int runAsync(@NotNull Runnable runnable); CompletableFuture supplyAsync(@NotNull Supplier supplier); - void runSync(@NotNull Runnable runnable); + int runSync(@NotNull Runnable runnable); + int runAsyncRepeating(@NotNull Runnable runnable, long delay); + void cancelTask(int taskId); @NotNull HuskHomes getPlugin(); diff --git a/common/src/main/java/net/william278/huskhomes/ValidationException.java b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java similarity index 67% rename from common/src/main/java/net/william278/huskhomes/ValidationException.java rename to common/src/main/java/net/william278/huskhomes/util/ValidationException.java index f8411bb8..611ee796 100644 --- a/common/src/main/java/net/william278/huskhomes/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java @@ -1,14 +1,14 @@ -package net.william278.huskhomes; +package net.william278.huskhomes.util; import org.jetbrains.annotations.NotNull; public class ValidationException extends IllegalArgumentException { - public ValidationException(@NotNull ValidationError error) { + public ValidationException(@NotNull ValidationException.Type error) { super("Error validating position: " + error.name()); } - public enum ValidationError { + public enum Type { NOT_FOUND, NAME_TAKEN, NAME_INVALID, diff --git a/common/src/main/java/net/william278/huskhomes/util/Validator.java b/common/src/main/java/net/william278/huskhomes/util/Validator.java index dab0baeb..168afc0f 100644 --- a/common/src/main/java/net/william278/huskhomes/util/Validator.java +++ b/common/src/main/java/net/william278/huskhomes/util/Validator.java @@ -3,6 +3,7 @@ package net.william278.huskhomes.util; import net.william278.huskhomes.HuskHomes; import org.jetbrains.annotations.NotNull; +@SuppressWarnings("BooleanMethodIsAlwaysInverted") public class Validator { public static final int MAX_NAME_LENGTH = 16; diff --git a/common/src/test/java/net/william278/huskhomes/network/MessageTests.java b/common/src/test/java/net/william278/huskhomes/network/MessageTests.java new file mode 100644 index 00000000..4ed55a5c --- /dev/null +++ b/common/src/test/java/net/william278/huskhomes/network/MessageTests.java @@ -0,0 +1,58 @@ +package net.william278.huskhomes.network; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.World; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +public class MessageTests { + + private final static Gson GSON = new GsonBuilder().create(); + private final static Message DUMMY_NO_PAYLOAD = Message.builder() + .type(Message.Type.TELEPORT_REQUEST) + .target("TestTarget") + .payload(Payload.empty()) + .build(); + + private final static Message DUMMY_PAYLOAD = Message.builder() + .type(Message.Type.TELEPORT_REQUEST) + .target("TestTarget") + .payload(Payload.withPosition( + new Position(63.25, 127.43, -32, 180f, -94.3f, + new World("TestWorld", UUID.randomUUID()), "TestServer"))) + .build(); + + @Test + @DisplayName("Test message serialization with empty payload") + public void testMessageSerializationWithEmptyPayload() { + Assertions.assertNotNull(GSON.toJson(DUMMY_NO_PAYLOAD)); + + final Message readMessage = GSON.fromJson(GSON.toJson(DUMMY_NO_PAYLOAD), Message.class); + Assertions.assertEquals(DUMMY_NO_PAYLOAD.getUuid(), readMessage.getUuid()); + Assertions.assertEquals(DUMMY_NO_PAYLOAD.getTarget(), readMessage.getTarget()); + Assertions.assertEquals(DUMMY_NO_PAYLOAD.getType(), readMessage.getType()); + } + + @Test + @DisplayName("Test message serialization with position payload") + public void testMessageSerializationWithPositionPayload() { + Assertions.assertNotNull(GSON.toJson(DUMMY_PAYLOAD)); + + final Message readMessage = GSON.fromJson(GSON.toJson(DUMMY_PAYLOAD), Message.class); + Assertions.assertEquals(DUMMY_PAYLOAD.getUuid(), readMessage.getUuid()); + Assertions.assertNotNull(readMessage.getPayload().getPosition()); + + assert readMessage.getPayload().getPosition().isPresent() && DUMMY_PAYLOAD.getPayload().getPosition().isPresent(); + Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().get().getX(), + readMessage.getPayload().getPosition().get().getX()); + Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().get().getY(), + readMessage.getPayload().getPosition().get().getY()); + Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().get().getZ(), + readMessage.getPayload().getPosition().get().getZ()); + } +} diff --git a/common/src/test/java/net/william278/huskhomes/network/RequestTests.java b/common/src/test/java/net/william278/huskhomes/network/RequestTests.java deleted file mode 100644 index 6e3bcfbf..00000000 --- a/common/src/test/java/net/william278/huskhomes/network/RequestTests.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.william278.huskhomes.network; - -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Server; -import net.william278.huskhomes.position.World; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.UUID; - -public class RequestTests { - - private final static Request DUMMY_NO_PAYLOAD = Request.builder() - .withType(Request.MessageType.TELEPORT_REQUEST) - .withTargetPlayer("TestTarget") - .withPayload(Payload.empty()) - .build(); - - private final static Request DUMMY_PAYLOAD = Request.builder() - .withType(Request.MessageType.TELEPORT_REQUEST) - .withTargetPlayer("TestTarget") - .withPayload(Payload.withPosition( - new Position(63.25, 127.43, -32, 180f, -94.3f, - new World("TestWorld", UUID.randomUUID()), new Server("TestServer")))) - .build(); - - @Test - public void testMessageSerializationWithEmptyPayload() { - Assertions.assertNotNull(DUMMY_NO_PAYLOAD.toJson()); - - final Request readRequest = Request.fromJson(DUMMY_NO_PAYLOAD.toJson()); - Assertions.assertEquals(DUMMY_NO_PAYLOAD.getUuid(), readRequest.getUuid()); - Assertions.assertEquals(DUMMY_NO_PAYLOAD.getTargetPlayer(), readRequest.getTargetPlayer()); - Assertions.assertEquals(DUMMY_NO_PAYLOAD.getType(), readRequest.getType()); - } - - @Test - public void testMessageSerializationWithPositionPayload() { - Assertions.assertNotNull(DUMMY_PAYLOAD.toJson()); - - final Request readRequest = Request.fromJson(DUMMY_PAYLOAD.toJson()); - Assertions.assertEquals(DUMMY_PAYLOAD.getUuid(), readRequest.getUuid()); - Assertions.assertNotNull(readRequest.getPayload().getPosition()); - - assert readRequest.getPayload().getPosition() != null && DUMMY_PAYLOAD.getPayload().getPosition() != null; - Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().getX(), readRequest.getPayload().getPosition().getX()); - Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().getY(), readRequest.getPayload().getPosition().getY()); - Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().getPosition().getZ(), readRequest.getPayload().getPosition().getZ()); - } -}