diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 23747a85..a3742822 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -56,7 +56,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.stream.Collectors; -public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMessageListener, BukkitTaskRunner { +public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTaskRunner, BukkitEventDispatcher, PluginMessageListener { /** * Metrics ID for HuskHomes on Bukkit. @@ -72,7 +72,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess private RandomTeleportEngine randomTeleportEngine; private Spawn serverSpawn; private UnsafeBlocks unsafeBlocks; - private EventDispatcher eventDispatcher; private Set pluginHooks; private List registeredCommands; private Server server; @@ -141,9 +140,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Prepare the validator this.validator = new Validator(this); - // Prepare the event dispatcher - this.eventDispatcher = new BukkitEventDispatcher(this); - // Initialize the cache this.cache = new Cache(this); @@ -337,12 +333,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess this.randomTeleportEngine = randomTeleportEngine; } - @Override - @NotNull - public EventDispatcher getEventDispatcher() { - return eventDispatcher; - } - @Override public Optional getLocalCachedSpawn() { return Optional.ofNullable(serverSpawn); diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java index e6b49b59..90180f11 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java @@ -1,6 +1,5 @@ package net.william278.huskhomes.event; -import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; @@ -13,120 +12,64 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.concurrent.CompletableFuture; -public class BukkitEventDispatcher implements EventDispatcher { +public interface BukkitEventDispatcher extends EventDispatcher { - private final BukkitHuskHomes plugin; - public BukkitEventDispatcher(@NotNull BukkitHuskHomes implementor) { - this.plugin = implementor; + @Override + default boolean fireIsCancelled(@NotNull T event) { + Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); + return event instanceof Cancellable cancellable && cancellable.isCancelled(); } @Override - public void dispatchTeleportEvent(@NotNull Teleport teleport) { - Bukkit.getScheduler().runTask(plugin, () -> { - final TeleportEvent event = new TeleportEvent(teleport); - Bukkit.getPluginManager().callEvent(event); - }); + default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { + return new TeleportEvent(teleport); } @Override - public CompletableFuture dispatchTeleportWarmupEvent(TimedTeleport teleport, int duration) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final TeleportWarmupEvent event = new TeleportWarmupEvent(teleport, duration); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { + return new TeleportWarmupEvent(teleport, duration); + } + + + @Override + default IHomeSaveEvent getHomeSaveEvent(@NotNull Home home) { + return new HomeSaveEvent(home); } @Override - public CompletableFuture dispatchHomeSaveEvent(@NotNull Home home) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final HomeSaveEvent event = new HomeSaveEvent(home); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home) { + return new HomeDeleteEvent(home); } @Override - public CompletableFuture dispatchHomeDeleteEvent(@NotNull Home home) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final HomeDeleteEvent event = new HomeDeleteEvent(home); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IWarpSaveEvent getWarpSaveEvent(@NotNull Warp warp) { + return new WarpSaveEvent(warp); } @Override - public CompletableFuture dispatchWarpSaveEvent(@NotNull Warp warp) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final WarpSaveEvent event = new WarpSaveEvent(warp); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp) { + return new WarpDeleteEvent(warp); } @Override - public CompletableFuture dispatchWarpDeleteEvent(@NotNull Warp warp) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final WarpDeleteEvent event = new WarpDeleteEvent(warp); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull OnlineUser user, boolean publicHomeList) { + return new HomeListEvent(homes, user, publicHomeList); } @Override - public CompletableFuture dispatchViewHomeListEvent(@NotNull List homes, @NotNull OnlineUser user, - boolean publicHomeList) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final HomeListEvent event = new HomeListEvent(homes, user, publicHomeList); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IWarpListEvent getViewWarpListEvent(@NotNull List warps, @NotNull OnlineUser user) { + return new WarpListEvent(warps, user); } @Override - public CompletableFuture dispatchViewWarpListEvent(@NotNull List warps, @NotNull OnlineUser user) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final WarpListEvent event = new WarpListEvent(warps, user); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user) { + return new DeleteAllHomesEvent(user); } @Override - public CompletableFuture dispatchDeleteAllHomesEvent(@NotNull User user) { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final DeleteAllHomesEvent event = new DeleteAllHomesEvent(user); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; - } - - @Override - public CompletableFuture dispatchDeleteAllWarpsEvent() { - final CompletableFuture dispatchFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - final DeleteAllWarpsEvent event = new DeleteAllWarpsEvent(); - Bukkit.getPluginManager().callEvent(event); - dispatchFuture.complete(event); - }); - return dispatchFuture; + default IDeleteAllWarpsEvent getDeleteAllWarpsEvent() { + return new DeleteAllWarpsEvent(); } } diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java index 6f930461..b62d8c1f 100644 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -115,12 +115,12 @@ public class Cache { } @NotNull - public Optional getHomeList(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull Locales locales, + public Optional getHomeList(@NotNull CommandUser executor, @NotNull User homeOwner, @NotNull Locales locales, @NotNull List homes, final int itemsPerPage, final int page) { - if (plugin.getEventDispatcher().dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) { + if (executor instanceof OnlineUser user && plugin.getEventDispatcher().getViewHomeListEvent(homes, user, false).join().isCancelled()) { return Optional.empty(); } - final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.getUsername() : ""; + final String homeListArguments = !executor.equals(homeOwner) ? " " + homeOwner.getUsername() : ""; final PaginatedList homeList = PaginatedList.of(homes.stream().map(home -> locales.getRawLocale("home_list_item", Locales.escapeText(home.getMeta().getName()), @@ -138,7 +138,7 @@ public class Cache { @NotNull public Optional getPublicHomeList(@NotNull OnlineUser onlineUser, @NotNull Locales locales, @NotNull List publicHomes, final int itemsPerPage, final int page) { - if (plugin.getEventDispatcher().dispatchViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) { + if (plugin.getEventDispatcher().getViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) { return Optional.empty(); } final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home -> @@ -159,7 +159,7 @@ public class Cache { @NotNull public Optional getWarpList(@NotNull OnlineUser onlineUser, @NotNull Locales locales, @NotNull List warps, final int itemsPerPage, final int page) { - if (plugin.getEventDispatcher().dispatchViewWarpListEvent(warps, onlineUser).join().isCancelled()) { + if (plugin.getEventDispatcher().getViewWarpListEvent(warps, onlineUser).join().isCancelled()) { return Optional.empty(); } final PaginatedList warpList = PaginatedList.of(warps.stream() diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index c3fd7ff2..d18628f8 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -39,7 +39,7 @@ import java.util.logging.Level; /** * Represents a cross-platform instance of the plugin */ -public interface HuskHomes extends TaskRunner { +public interface HuskHomes extends TaskRunner, EventDispatcher { int SPIGOT_RESOURCE_ID = 83767; @@ -141,14 +141,6 @@ public interface HuskHomes extends TaskRunner { */ void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine); - /** - * The {@link EventDispatcher} that dispatches API events - * - * @return the {@link EventDispatcher} implementation - */ - @NotNull - EventDispatcher getEventDispatcher(); - /** * The local {@link Spawn} location of this server, as cached to disk * 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 b6f2aebb..c52e8a93 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -30,14 +30,17 @@ public class DelHomeCommand extends SavedPositionCommand { .ifPresent(user::sendMessage); return; } - try { - plugin.getManager().homes().deleteHome(home); - } catch (ValidationException e) { - e.dispatchHomeError(executor, !home.getOwner().equals(executor), plugin, home.getName()); - return; - } - plugin.getLocales().getLocale("home_deleted", home.getName()) - .ifPresent(executor::sendMessage); + + plugin.fireEvent(plugin.getHomeDeleteEvent(home), (event) -> { + try { + plugin.getManager().homes().deleteHome(home); + } catch (ValidationException e) { + e.dispatchHomeError(executor, !home.getOwner().equals(executor), plugin, home.getName()); + return; + } + plugin.getLocales().getLocale("home_deleted", home.getName()) + .ifPresent(executor::sendMessage); + }); } private boolean handleDeleteAll(@NotNull OnlineUser user, @NotNull String[] args) { @@ -50,15 +53,17 @@ public class DelHomeCommand extends SavedPositionCommand { return true; } - final int deleted = plugin.getManager().homes().deleteAllHomes(user); - if (deleted == 0) { - plugin.getLocales().getLocale("error_no_homes_set") - .ifPresent(user::sendMessage); - return true; - } + plugin.fireEvent(plugin.getDeleteAllHomesEvent(user), (event) -> { + final int deleted = plugin.getManager().homes().deleteAllHomes(user); + if (deleted == 0) { + plugin.getLocales().getLocale("error_no_homes_set") + .ifPresent(user::sendMessage); + return; + } - plugin.getLocales().getLocale("delete_all_homes_success", Integer.toString(deleted)) - .ifPresent(user::sendMessage); + plugin.getLocales().getLocale("delete_all_homes_success", Integer.toString(deleted)) + .ifPresent(user::sendMessage); + }); return true; } return false; diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index 480e9f53..6d9c2e05 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -30,14 +30,18 @@ public class DelWarpCommand extends SavedPositionCommand { .ifPresent(user::sendMessage); return; } - try { - plugin.getManager().warps().deleteWarp(warp); - } catch (ValidationException e) { - e.dispatchWarpError(executor, plugin, warp.getName()); - return; - } - plugin.getLocales().getLocale("warp_deleted", warp.getName()) - .ifPresent(executor::sendMessage); + + plugin.fireEvent(plugin.getWarpDeleteEvent(warp), (event) -> { + try { + plugin.getManager().warps().deleteWarp(warp); + } catch (ValidationException e) { + e.dispatchWarpError(executor, plugin, warp.getName()); + return; + } + plugin.getLocales().getLocale("warp_deleted", warp.getName()) + .ifPresent(executor::sendMessage); + }); + } private boolean handleDeleteAll(@NotNull CommandUser executor, @NotNull String[] args) { @@ -50,15 +54,17 @@ public class DelWarpCommand extends SavedPositionCommand { return true; } - final int deleted = plugin.getManager().warps().deleteAllWarps(); - if (deleted == 0) { - plugin.getLocales().getLocale("error_no_warps_set") - .ifPresent(executor::sendMessage); - return true; - } + plugin.fireEvent(plugin.getDeleteAllWarpsEvent(), (event) -> { + final int deleted = plugin.getManager().warps().deleteAllWarps(); + if (deleted == 0) { + plugin.getLocales().getLocale("error_no_warps_set") + .ifPresent(executor::sendMessage); + return; + } - plugin.getLocales().getLocale("delete_all_warps_success", Integer.toString(deleted)) - .ifPresent(executor::sendMessage); + plugin.getLocales().getLocale("delete_all_warps_success", Integer.toString(deleted)) + .ifPresent(executor::sendMessage); + }); return true; } return false; 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 f8e9ad79..c7cdd947 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -7,7 +7,6 @@ import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; @@ -36,8 +35,8 @@ public class EditHomeCommand extends SavedPositionCommand { final Optional operation = parseStringArg(args, 0); if (operation.isEmpty()) { getHomeEditorWindow(home, true, !ownerEditing, - !ownerEditing || executor.hasPermission(Permission.COMMAND_HOME_OTHER.node), - executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) + !ownerEditing || executor.hasPermission(getOtherPermission()), + executor.hasPermission(getPermission("privacy"))) .forEach(executor::sendMessage); return; } @@ -66,21 +65,23 @@ public class EditHomeCommand extends SavedPositionCommand { return; } - try { - plugin.getManager().homes().setHomeName(home, newName.get()); - } catch (ValidationException e) { - e.dispatchHomeError(executor, false, plugin, newName.get()); - return; - } + plugin.fireEvent(plugin.getHomeSaveEvent(home), (event) -> { + try { + plugin.getManager().homes().setHomeName(home, newName.get()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, newName.get()); + return; + } - if (ownerEditing) { - plugin.getLocales().getLocale("edit_home_update_name", home.getName(), newName.get()) - .ifPresent(executor::sendMessage); - } else { - plugin.getLocales().getLocale("edit_home_update_name_other", home.getOwner().getUsername(), - home.getName(), newName.get()) - .ifPresent(executor::sendMessage); - } + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_name", home.getName(), newName.get()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_name_other", home.getOwner().getUsername(), + home.getName(), newName.get()) + .ifPresent(executor::sendMessage); + } + }); } private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) { @@ -92,21 +93,23 @@ public class EditHomeCommand extends SavedPositionCommand { return; } - try { - plugin.getManager().homes().setHomeDescription(home, newDescription.get()); - } catch (ValidationException e) { - e.dispatchHomeError(executor, false, plugin, newDescription.get()); - return; - } + plugin.fireEvent(plugin.getHomeSaveEvent(home), (event) -> { + try { + plugin.getManager().homes().setHomeDescription(home, newDescription.get()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, newDescription.get()); + return; + } - if (ownerEditing) { - plugin.getLocales().getLocale("edit_home_update_description", home.getName(), newDescription.get()) - .ifPresent(executor::sendMessage); - } else { - plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(), - home.getName(), newDescription.get()) - .ifPresent(executor::sendMessage); - } + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_description", home.getName(), newDescription.get()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(), + home.getName(), newDescription.get()) + .ifPresent(executor::sendMessage); + } + }); } private void setHomePosition(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing) { @@ -116,24 +119,26 @@ public class EditHomeCommand extends SavedPositionCommand { return; } - try { - plugin.getManager().homes().setHomePosition(home, user.getPosition()); - } catch (ValidationException e) { - e.dispatchHomeError(executor, false, plugin, home.getName()); - return; - } + plugin.fireEvent(plugin.getHomeDeleteEvent(home), (event) -> { + try { + plugin.getManager().homes().setHomePosition(home, user.getPosition()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, home.getName()); + return; + } - if (ownerEditing) { - plugin.getLocales().getLocale("edit_home_update_location", home.getName()) - .ifPresent(executor::sendMessage); - } else { - plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName()) - .ifPresent(executor::sendMessage); - } + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_location", home.getName()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName()) + .ifPresent(executor::sendMessage); + } + }); } private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) { - if (!executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) { + if (!executor.hasPermission(getPermission("privacy"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); return; @@ -152,40 +157,42 @@ public class EditHomeCommand extends SavedPositionCommand { return; } - try { - plugin.getManager().homes().setHomePrivacy(home, privacyArg.get().equals("public")); - } catch (ValidationException e) { - int maxHomes = executor instanceof OnlineUser user ? - user.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), - plugin.getSettings().doStackPermissionLimits()) : - plugin.getSettings().getMaxPublicHomes(); - e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes)); - return; - } - - // Perform transaction - if (executor instanceof OnlineUser user) { - plugin.performEconomyTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC); - } - - if (ownerEditing) { - plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success", - home.getMeta().getName()) - .ifPresent(executor::sendMessage); - } else { - plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success_other", - home.getOwner().getUsername(), home.getMeta().getName()) - .ifPresent(executor::sendMessage); - } - - // Show the menu if the menu flag is set - parseStringArg(args, 2).ifPresent(arg -> { - if (arg.equalsIgnoreCase("-m")) { - getHomeEditorWindow(home, false, !ownerEditing, - ownerEditing || executor.hasPermission(Permission.COMMAND_HOME_OTHER.node), - executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) - .forEach(executor::sendMessage); + plugin.fireEvent(plugin.getHomeSaveEvent(home), (event) -> { + try { + plugin.getManager().homes().setHomePrivacy(home, privacyArg.get().equals("public")); + } catch (ValidationException e) { + int maxHomes = executor instanceof OnlineUser user ? + user.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), + plugin.getSettings().doStackPermissionLimits()) : + plugin.getSettings().getMaxPublicHomes(); + e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes)); + return; } + + // Perform transaction + if (executor instanceof OnlineUser user) { + plugin.performEconomyTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC); + } + + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success", + home.getMeta().getName()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success_other", + home.getOwner().getUsername(), home.getMeta().getName()) + .ifPresent(executor::sendMessage); + } + + // Show the menu if the menu flag is set + parseStringArg(args, 2).ifPresent(arg -> { + if (arg.equalsIgnoreCase("-m")) { + getHomeEditorWindow(home, false, !ownerEditing, + ownerEditing || executor.hasPermission(getOtherPermission()), + executor.hasPermission(getPermission("privacy"))) + .forEach(executor::sendMessage); + } + }); }); } diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java index a19a52a9..a39edbef 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -1,114 +1,71 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.util.Permission; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; -import java.util.StringJoiner; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; -public class HomeListCommand extends Command implements ConsoleExecutable { +public class HomeListCommand extends Command { - protected HomeListCommand(@NotNull HuskHomes implementor) { - super("homelist", Permission.COMMAND_HOME, implementor, "homes"); + protected HomeListCommand(@NotNull HuskHomes plugin) { + super("homelist", List.of("homes"), "[player] [page]", plugin); } @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - switch (args.length) { - case 0 -> showHomeList(onlineUser, onlineUser.getUsername(), 1); - case 1 -> { - try { - int pageNumber = Integer.parseInt(args[0]); - showHomeList(onlineUser, onlineUser.getUsername(), pageNumber); - } catch (NumberFormatException e) { - showHomeList(onlineUser, args[0], 1); - } - } - case 2 -> { - try { - int pageNumber = Integer.parseInt(args[1]); - showHomeList(onlineUser, args[0], pageNumber); - } catch (NumberFormatException e) { - plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [player] [page]") - .ifPresent(onlineUser::sendMessage); - } - } - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [page]") - .ifPresent(onlineUser::sendMessage); + public void execute(@NotNull CommandUser executor, @NotNull String[] args) { + final Optional homeOwner = args.length == 2 ? parseStringArg(args, 0) + : executor instanceof OnlineUser user ? Optional.of(user.getUsername()) : Optional.empty(); + final int pageNumber = parseIntArg(args, args.length > 0 ? args.length - 1 : 0).orElse(1); + if (homeOwner.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); + return; } + + showHomeList(executor, homeOwner.get(), pageNumber); } - /** - * Show a (cached) list of a {@link OnlineUser}'s homes - * - * @param onlineUser the user to display the homes to - * @param homeOwner the user whose homes should be displayed - * @param pageNumber page number to display - */ - private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) { + private void showHomeList(@NotNull CommandUser executor, @NotNull String homeOwner, int pageNumber) { if (plugin.getCache().getPrivateHomeLists().containsKey(homeOwner)) { - onlineUser.sendMessage(plugin.getCache().getPrivateHomeLists().get(homeOwner).getNearestValidPage(pageNumber)); + executor.sendMessage(plugin.getCache().getPrivateHomeLists().get(homeOwner).getNearestValidPage(pageNumber)); return; } - plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> { - if (!userData.getUserUuid().equals(onlineUser.getUuid())) { - if (!onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); - return; - } - } - plugin.getDatabase().getHomes(userData.user()).thenAcceptAsync(homes -> { - if (homes.isEmpty()) { - if (!onlineUser.equals(userData.user())) { - plugin.getLocales().getLocale("error_no_homes_set_other", - userData.user().username).ifPresent(onlineUser::sendMessage); - } else { - plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage); - } - return; - } - plugin.getCache().getHomeList(onlineUser, userData.user(), - plugin.getLocales(), homes, - plugin.getSettings().getListItemsPerPage(), pageNumber) - .ifPresent(onlineUser::sendMessage); - }); - }, () -> plugin.getLocales().getLocale("error_player_not_found", homeOwner).ifPresent(onlineUser::sendMessage))); - } - - @Override - public void onConsoleExecute(@NotNull String[] args) { - if (args.length != 1) { - plugin.log(Level.WARNING, "Invalid syntax. Usage: homelist "); + final Optional targetUser = plugin.getDatabase().getUserDataByName(homeOwner).map(SavedUser::getUser); + if (targetUser.isEmpty()) { + plugin.getLocales().getLocale("error_player_not_found", homeOwner) + .ifPresent(executor::sendMessage); return; } - CompletableFuture.runAsync(() -> { - final Optional userData = plugin.getDatabase().getUserDataByName(args[0]).join(); - if (userData.isEmpty()) { - plugin.log(Level.WARNING, "Player not found: " + args[0]); + + final User user = targetUser.get(); + if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid())) { + if (!executor.hasPermission(getPermission("other"))) { + plugin.getLocales().getLocale("error_no_permission").ifPresent(executor::sendMessage); return; } - final List homes = plugin.getDatabase().getHomes(userData.get().user()).join(); - StringJoiner rowJoiner = new StringJoiner("\t"); + } - plugin.log(Level.INFO, "List of " + userData.get().user().getUsername() + "'s " - + homes.size() + " homes:"); - for (int i = 0; i < homes.size(); i++) { - final String home = homes.get(i).getMeta().getName(); - rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home); - if ((i + 1) % 3 == 0) { - plugin.log(Level.INFO, rowJoiner.toString()); - rowJoiner = new StringJoiner("\t"); - } + final List homes = plugin.getDatabase().getHomes(user); + if (homes.isEmpty()) { + if (!executor.equals(user)) { + plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("error_no_homes_set").ifPresent(executor::sendMessage); } - plugin.log(Level.INFO, rowJoiner.toString()); - }); + return; + } + plugin.getCache().getHomeList(executor, user, + plugin.getLocales(), homes, + plugin.getSettings().getListItemsPerPage(), pageNumber) + .ifPresent(executor::sendMessage); } + } diff --git a/common/src/main/java/net/william278/huskhomes/event/CancellableEvent.java b/common/src/main/java/net/william278/huskhomes/event/Cancellable.java similarity index 90% rename from common/src/main/java/net/william278/huskhomes/event/CancellableEvent.java rename to common/src/main/java/net/william278/huskhomes/event/Cancellable.java index f548a479..68a671aa 100644 --- a/common/src/main/java/net/william278/huskhomes/event/CancellableEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/Cancellable.java @@ -3,7 +3,7 @@ package net.william278.huskhomes.event; /** * Base interface for a cancellable event */ -public interface CancellableEvent { +public interface Cancellable extends Event { /** * Set whether the event should be cancelled diff --git a/common/src/main/java/net/william278/huskhomes/event/Event.java b/common/src/main/java/net/william278/huskhomes/event/Event.java new file mode 100644 index 00000000..88f3538e --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/event/Event.java @@ -0,0 +1,7 @@ +package net.william278.huskhomes.event; + +/** + * Interface for an event fired by HuskHomes + */ +public interface Event { +} diff --git a/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java b/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java index e17d2321..cc615fb4 100644 --- a/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java +++ b/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java @@ -1,5 +1,6 @@ package net.william278.huskhomes.event; +import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; @@ -7,33 +8,61 @@ import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TimedTeleport; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; /** * An abstract dispatcher of events */ public interface EventDispatcher { - void dispatchTeleportEvent(@NotNull Teleport teleport); + /** + * Fire an event synchronously, then run a callback asynchronously + * + * @param event The event to fire + * @param callback The callback to run after the event has been fired + * @param The type of event to fire + */ + default void fireEvent(@NotNull T event, @Nullable Consumer callback) { + getPlugin().runSync(() -> { + if (!fireIsCancelled(event) && callback != null) { + getPlugin().runAsync(() -> callback.accept(event)); + } + }); + } - CompletableFuture dispatchTeleportWarmupEvent(TimedTeleport teleport, int duration); + /** + * Fire an event on this thread, and return whether the event was cancelled + * + * @param event The event to fire + * @param The type of event to fire + * @return Whether the event was cancelled + */ + boolean fireIsCancelled(@NotNull T event); - CompletableFuture dispatchHomeSaveEvent(@NotNull Home home); + ITeleportEvent getTeleportEvent(@NotNull Teleport teleport); - CompletableFuture dispatchHomeDeleteEvent(@NotNull Home home); + ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration); - CompletableFuture dispatchWarpSaveEvent(@NotNull Warp warp); + IHomeSaveEvent getHomeSaveEvent(@NotNull Home home); - CompletableFuture dispatchWarpDeleteEvent(@NotNull Warp warp); + IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home); - CompletableFuture dispatchViewHomeListEvent(@NotNull List homes, @NotNull OnlineUser user, - boolean publicHomeList); + IWarpSaveEvent getWarpSaveEvent(@NotNull Warp warp); - CompletableFuture dispatchViewWarpListEvent(@NotNull List homes, @NotNull OnlineUser user); + IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp); - CompletableFuture dispatchDeleteAllHomesEvent(@NotNull User user); + IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull OnlineUser user, boolean publicHomeList); + + IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull OnlineUser user); + + IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user); + + IDeleteAllWarpsEvent getDeleteAllWarpsEvent(); + + @NotNull + HuskHomes getPlugin(); - CompletableFuture dispatchDeleteAllWarpsEvent(); } diff --git a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java index 7d1dfc6b..07452da5 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when all homes are deleted */ -public interface IDeleteAllHomesEvent extends CancellableEvent { +public interface IDeleteAllHomesEvent extends Cancellable { /** * Get the player whose homes are being deleted diff --git a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java index fbeef111..640b8549 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java @@ -3,6 +3,6 @@ package net.william278.huskhomes.event; /** * Representation of an event that fires when all warps are deleted */ -public interface IDeleteAllWarpsEvent extends CancellableEvent { +public interface IDeleteAllWarpsEvent extends Cancellable { } diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java index ce921830..ecf257a4 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a single home is deleted */ -public interface IHomeDeleteEvent extends CancellableEvent { +public interface IHomeDeleteEvent extends Cancellable { /** * Get the home being deleted diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java index 0a4bd21f..48b4ce7f 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeListEvent.java @@ -9,7 +9,7 @@ import java.util.List; /** * Represents an event that fires when a player requests to view a list of homes */ -public interface IHomeListEvent extends CancellableEvent { +public interface IHomeListEvent extends Cancellable { /** * Get the list of homes to be displayed diff --git a/common/src/main/java/net/william278/huskhomes/event/IHomeSaveEvent.java b/common/src/main/java/net/william278/huskhomes/event/IHomeSaveEvent.java index cd05f7d7..6c333b4e 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeSaveEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeSaveEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a home is created or updated */ -public interface IHomeSaveEvent extends CancellableEvent { +public interface IHomeSaveEvent extends Cancellable { /** * Get the home being created or updated diff --git a/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java b/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java index 081a2645..a9acd612 100644 --- a/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/ITeleportEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a teleport is about to occur */ -public interface ITeleportEvent { +public interface ITeleportEvent extends Event { /** * Get the teleport being carried out diff --git a/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java b/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java index db158464..53e56f0e 100644 --- a/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/ITeleportWarmupEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a timed teleport warmup starts */ -public interface ITeleportWarmupEvent extends CancellableEvent { +public interface ITeleportWarmupEvent extends Cancellable { /** * The duration of the timed teleport before the user is teleported diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java index cf139669..a08eb0b9 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a single warp is deleted */ -public interface IWarpDeleteEvent extends CancellableEvent { +public interface IWarpDeleteEvent extends Cancellable { /** * Get the warp being deleted diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java index 625b2b7e..7bb84ae5 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpListEvent.java @@ -9,7 +9,7 @@ import java.util.List; /** * Represents an event that fires when a player requests to view a list of warps */ -public interface IWarpListEvent extends CancellableEvent { +public interface IWarpListEvent extends Cancellable { /** * Get the list of warps to be displayed diff --git a/common/src/main/java/net/william278/huskhomes/event/IWarpSaveEvent.java b/common/src/main/java/net/william278/huskhomes/event/IWarpSaveEvent.java index 43324eb0..e932979e 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpSaveEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpSaveEvent.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** * Representation of an event that fires when a warp is created or updated */ -public interface IWarpSaveEvent extends CancellableEvent { +public interface IWarpSaveEvent extends Cancellable { /** * Get the warp being created or updated 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 8b45b14b..05457571 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -41,7 +41,7 @@ public class EventListener { // Set their ignoring requests state plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> { - final boolean ignoringRequests = userData.ignoringTeleports(); + final boolean ignoringRequests = userData.isIgnoringTeleports(); plugin.getManager().requests().setIgnoringRequests(onlineUser, ignoringRequests); // Send a reminder message if they are still ignoring requests @@ -82,7 +82,8 @@ public class EventListener { plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)); return; } - teleport.execute(); + + onlineUser.teleportLocally((Position) teleport.getTarget(), plugin.getSettings().isAsynchronousTeleports()); plugin.getDatabase().setCurrentTeleport(onlineUser, null); }); } @@ -94,7 +95,7 @@ public class EventListener { */ protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) { // Remove this user's home cache - plugin.getCache().getHomes().remove(onlineUser.getUuid()); + plugin.getCache().getHomes().remove(onlineUser.getUsername()); // Update the cached player list using another online player if possible plugin.getOnlineUsers() @@ -116,7 +117,7 @@ public class EventListener { protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) { // Set the player's last position to where they died if (plugin.getSettings().isBackCommandReturnByDeath() - && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { + && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition()); } } @@ -130,8 +131,8 @@ public class EventListener { plugin.runAsync(() -> { // Display the return by death via /back notification if (plugin.getSettings().isBackCommandReturnByDeath() - && onlineUser.hasPermission(Permission.COMMAND_BACK.node) - && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { + && onlineUser.hasPermission(Permission.COMMAND_BACK.node) + && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { plugin.getLocales().getLocale("return_by_death_notification") .ifPresent(onlineUser::sendMessage); } @@ -164,7 +165,7 @@ public class EventListener { } plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.getUuid()) - .ifPresent(data -> plugin.getDatabase().setLastPosition(data.user(), sourcePosition))); + .ifPresent(data -> plugin.getDatabase().setLastPosition(data.getUser(), sourcePosition))); } /** 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 4adb2275..e2b1c8d9 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/Manager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/Manager.java @@ -5,17 +5,13 @@ import org.jetbrains.annotations.NotNull; public class Manager { - private final HuskHomes plugin; 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); } @@ -29,11 +25,6 @@ public class Manager { return warps; } - @NotNull - public UsersManager users() { - return users; - } - @NotNull public RequestsManager requests() { return requests; diff --git a/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java b/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java deleted file mode 100644 index 573beba0..00000000 --- a/common/src/main/java/net/william278/huskhomes/manager/UsersManager.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.william278.huskhomes.manager; - -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.user.User; -import org.jetbrains.annotations.NotNull; - -public class UsersManager { - protected UsersManager(@NotNull HuskHomes plugin) { - } - - public void ensureUser(@NotNull User user) { - - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/network/Message.java b/common/src/main/java/net/william278/huskhomes/network/Message.java index 680a4343..54ab01e3 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Message.java +++ b/common/src/main/java/net/william278/huskhomes/network/Message.java @@ -12,8 +12,6 @@ import java.util.UUID; */ public class Message { - public static final String TARGET_ALL = "ALL"; - @Expose private UUID id; @Expose @@ -121,7 +119,8 @@ public class Message { TELEPORT_TO_POSITION, TELEPORT_TO_NETWORKED_POSITION, TELEPORT_REQUEST, - POSITION_RESPONSE, TELEPORT_TO_NETWORKED_USER, TELEPORT_REQUEST_RESPONSE + TELEPORT_TO_NETWORKED_USER, + TELEPORT_REQUEST_RESPONSE } } \ No newline at end of file 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 5a73a3a9..672884c5 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -1,6 +1,7 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.event.ITeleportEvent; import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; @@ -11,10 +12,11 @@ import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.function.Consumer; public class Teleport { - private final HuskHomes plugin; + protected final HuskHomes plugin; protected final OnlineUser executor; protected final Teleportable teleporter; protected final Target target; @@ -54,20 +56,23 @@ public class Teleport { 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; - } + fireEvent((event) -> { + executeEconomyActions(); + 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); + Message.builder() + .type(Message.Type.TELEPORT_TO_POSITION) + .target(teleporter.name()) + .payload(Payload.withPosition((Position) target)) + .build().send(plugin.getMessenger(), executor); + }); return; } @@ -76,24 +81,31 @@ public class Teleport { if (target instanceof Username username) { final Optional localTarget = username.findLocally(plugin); if (localTarget.isPresent()) { - economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action)); - teleporter.teleportLocally(localTarget.get().getPosition(), async); + fireEvent((event) -> { + executeEconomyActions(); + teleporter.teleportLocally(localTarget.get().getPosition(), async); + }); return; } if (plugin.getSettings().isCrossServer()) { - economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action)); - Message.builder() - .type(Message.Type.TELEPORT_TO_NETWORKED_POSITION) - .target(username.name()) - .build().send(plugin.getMessenger(), executor); + fireEvent((event) -> { + executeEconomyActions(); + 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); } - economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action)); - teleporter.teleportLocally((Position) target, async); + + fireEvent((event) -> { + executeEconomyActions(); + teleporter.teleportLocally((Position) target, async); + }); } @NotNull @@ -104,14 +116,23 @@ public class Teleport { return Optional.of((OnlineUser) this.teleporter); } + // Fire the teleport event + private void fireEvent(@NotNull Consumer afterFired) { + plugin.fireEvent(plugin.getTeleportEvent(this), afterFired); + } + // Check economy actions protected void validateEconomyActions() throws TeleportationException { - economyActions.stream() + if (economyActions.stream() .map(action -> plugin.validateEconomyCheck(executor, action)) - .filter(result -> !result).findFirst() - .ifPresent(result -> { - throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED); - }); + .anyMatch(result -> !result)) { + throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED); + } + } + + // Perform transactions on economy actions + private void executeEconomyActions() { + economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action)); } @NotNull 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 92782b58..a7a5fade 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -10,12 +10,10 @@ import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; public class TimedTeleport extends Teleport { - private final HuskHomes plugin; private final OnlineUser teleporter; private final Position startLocation; private final double startHealth; @@ -25,14 +23,13 @@ public class TimedTeleport extends Teleport { @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(); this.timeLeft = Math.max(warmupTime, 0); this.teleporter = teleporter; } - @Override + @Override public void execute() throws TeleportationException { // Check if the teleporter can bypass warmup if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) { @@ -57,14 +54,9 @@ public class TimedTeleport extends Teleport { this.process(); } + // Execute the warmup, fire the event, then execute the teleport if warmup completes normally private void process() { - // Execute the warmup start event - plugin.getEventDispatcher().dispatchTeleportWarmupEvent(this, timeLeft).thenAccept(event -> { - if (event.isCancelled()) { - return; - } - - // Mark the player as warming up and display the message + plugin.fireEvent(plugin.getTeleportWarmupEvent(this, timeLeft), (event) -> { plugin.getCache().getCurrentlyOnWarmup().add(teleporter.getUuid()); plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft)) .ifPresent(teleporter::sendMessage); @@ -151,8 +143,8 @@ public class TimedTeleport extends Teleport { 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; }