diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 0c1870c9..f7bf0656 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -54,7 +54,6 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.stream.Collectors; @@ -468,34 +467,29 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { return server; } + @Override public CompletableFuture fetchServer(@NotNull OnlineUser requester) { - if (!getSettings().crossServer || server != null) { + if (!getSettings().crossServer || this.server != null) { return CompletableFuture.completedFuture(null); } - assert networkMessenger != null; - getLoggingAdapter().log(Level.INFO, "Fetching server information from the proxy..."); - final AtomicInteger attempts = new AtomicInteger(0); - return CompletableFuture.runAsync(() -> { - String serverName = null; - while (serverName == null) { - attempts.getAndIncrement(); - serverName = networkMessenger.getServerName(requester) - .orTimeout(1, TimeUnit.SECONDS) - .exceptionally(throwable -> null).join(); + return getNetworkMessenger() + .fetchServerName(requester) + .orTimeout(5, TimeUnit.SECONDS) + .exceptionally(throwable -> null) + .thenAccept(serverName -> { + if (serverName == null) { + throw new HuskHomesException("GetServer plugin message call operation timed out"); } - getLoggingAdapter().log(Level.INFO, "Successfully fetched server information from the proxy (name: " - + serverName + ", attempts: " + attempts.get() + ")"); - server = new Server(serverName); try { + this.server = new Server(serverName); Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName)); + getLoggingAdapter().log(Level.INFO, "Successfully cached server name to disk (" + serverName + ")"); } catch (IOException e) { - throw new HuskHomesException("Failed to save server information", e); + throw new HuskHomesException("Failed to write cached server name to disk", e); } }) - .orTimeout(5, TimeUnit.SECONDS) .exceptionally(throwable -> { - getLoggingAdapter().log(Level.SEVERE, "Failed to fetch server name from the proxy (attempts: " - + attempts.get() + ") - Is your proxy server online?", throwable); + getLoggingAdapter().log(Level.SEVERE, "Failed to fetch and cache server name", throwable); return null; }); } 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 f00e1715..cb0164a3 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/BukkitEventDispatcher.java @@ -2,6 +2,7 @@ package net.william278.huskhomes.event; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.player.OnlineUser; +import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.teleport.Teleport; @@ -106,4 +107,26 @@ public class BukkitEventDispatcher implements EventDispatcher { return dispatchFuture; } + @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; + } + } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllHomesEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllHomesEvent.java new file mode 100644 index 00000000..b9c76bb6 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllHomesEvent.java @@ -0,0 +1,47 @@ +package net.william278.huskhomes.event; + +import net.william278.huskhomes.player.User; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class DeleteAllHomesEvent extends Event implements IDeleteAllHomesEvent, Cancellable { + + private static final HandlerList HANDLER_LIST = new HandlerList(); + + private boolean cancelled; + + @NotNull + private final User homeOwner; + + public DeleteAllHomesEvent(@NotNull User homeOwner) { + this.homeOwner = homeOwner; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLER_LIST; + } + + @SuppressWarnings("unused") + public static HandlerList getHandlerList() { + return HANDLER_LIST; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public @NotNull User getHomeOwner() { + return homeOwner; + } +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsEvent.java new file mode 100644 index 00000000..a364fc35 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/event/DeleteAllWarpsEvent.java @@ -0,0 +1,38 @@ +package net.william278.huskhomes.event; + +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class DeleteAllWarpsEvent extends Event implements IDeleteAllWarpsEvent, Cancellable { + + private static final HandlerList HANDLER_LIST = new HandlerList(); + + private boolean cancelled; + + public DeleteAllWarpsEvent() { + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLER_LIST; + } + + @SuppressWarnings("unused") + public static HandlerList getHandlerList() { + return HANDLER_LIST; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/HomeDeleteEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/HomeDeleteEvent.java index 3f7f3b7a..9c74a958 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/HomeDeleteEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/HomeDeleteEvent.java @@ -24,6 +24,7 @@ public class HomeDeleteEvent extends Event implements IHomeDeleteEvent, Cancella return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/HomeListEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/HomeListEvent.java index 872f682b..e343f93f 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/HomeListEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/HomeListEvent.java @@ -31,6 +31,7 @@ public class HomeListEvent extends Event implements IHomeListEvent, Cancellable return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/HomeSaveEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/HomeSaveEvent.java index 08991f41..b3042a52 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/HomeSaveEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/HomeSaveEvent.java @@ -24,6 +24,7 @@ public class HomeSaveEvent extends Event implements IHomeSaveEvent, Cancellable return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/TeleportEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/TeleportEvent.java index e24a57ea..c1089960 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/TeleportEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/TeleportEvent.java @@ -26,6 +26,7 @@ public class TeleportEvent extends Event implements ITeleportEvent { return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/TeleportWarmupEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/TeleportWarmupEvent.java index 628f6494..7079c91d 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/TeleportWarmupEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/TeleportWarmupEvent.java @@ -24,6 +24,7 @@ public class TeleportWarmupEvent extends Event implements ITeleportWarmupEvent, return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/WarpDeleteEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/WarpDeleteEvent.java index 682b7654..b3faa0d4 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/WarpDeleteEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/WarpDeleteEvent.java @@ -24,6 +24,7 @@ public class WarpDeleteEvent extends Event implements IWarpDeleteEvent, Cancella return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/WarpListEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/WarpListEvent.java index c1d4ef43..6c12a08e 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/WarpListEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/WarpListEvent.java @@ -29,6 +29,7 @@ public class WarpListEvent extends Event implements IWarpListEvent, Cancellable return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/event/WarpSaveEvent.java b/bukkit/src/main/java/net/william278/huskhomes/event/WarpSaveEvent.java index 286ce420..44c5abd4 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/event/WarpSaveEvent.java +++ b/bukkit/src/main/java/net/william278/huskhomes/event/WarpSaveEvent.java @@ -24,6 +24,7 @@ public class WarpSaveEvent extends Event implements IWarpSaveEvent, Cancellable return HANDLER_LIST; } + @SuppressWarnings("unused") public static HandlerList getHandlerList() { return HANDLER_LIST; } diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java index b93d2e5b..690cd2e1 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/DynMapHook.java @@ -3,13 +3,14 @@ package net.william278.huskhomes.hook; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.command.BukkitCommandType; +import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Warp; import org.apache.commons.lang.StringEscapeUtils; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.dynmap.DynmapAPI; -import org.dynmap.markers.GenericMarker; +import org.dynmap.markers.Marker; import org.dynmap.markers.MarkerAPI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -69,7 +70,7 @@ public class DynMapHook extends MapHook { final CompletableFuture updatedFuture = new CompletableFuture<>(); removeHome(home).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).createMarker( - home.uuid.toString(), home.meta.name, home.world.name, + home.owner.uuid + ":" + home.uuid, home.meta.name, home.world.name, home.x, home.y, home.z, dynmapAPI.getMarkerAPI().getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME), false) .setDescription(MarkerInformationPopup.create(home.meta.name) .setThumbnailMarker(PUBLIC_HOME_MARKER_IMAGE_NAME) @@ -88,16 +89,27 @@ public class DynMapHook extends MapHook { final CompletableFuture removedFuture = new CompletableFuture<>(); Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { - dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers() - .stream() - .filter(marker -> marker.getMarkerID().equals(home.uuid.toString())) + dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers().stream() + .filter(marker -> marker.getMarkerID().equals(home.owner.uuid + ":" + home.uuid)) .findFirst() - .ifPresent(GenericMarker::deleteMarker); + .ifPresent(Marker::deleteMarker); removedFuture.complete(null); }); return removedFuture; } + @Override + public CompletableFuture clearHomes(@NotNull User user) { + final CompletableFuture clearedFuture = new CompletableFuture<>(); + Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { + dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers().stream() + .filter(marker -> marker.getMarkerID().startsWith(user.uuid.toString())) + .forEach(Marker::deleteMarker); + clearedFuture.complete(null); + }); + return clearedFuture; + } + @Override public CompletableFuture updateWarp(@NotNull Warp warp) { if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null); @@ -123,16 +135,26 @@ public class DynMapHook extends MapHook { final CompletableFuture removedFuture = new CompletableFuture<>(); CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { - dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers() - .stream() + dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers().stream() .filter(marker -> marker.getMarkerID().equals(warp.uuid.toString())) .findFirst() - .ifPresent(GenericMarker::deleteMarker); + .ifPresent(Marker::deleteMarker); removedFuture.complete(null); })); return removedFuture; } + @Override + public CompletableFuture clearWarps() { + final CompletableFuture clearedFuture = new CompletableFuture<>(); + Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> { + dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers() + .forEach(Marker::deleteMarker); + clearedFuture.complete(null); + }); + return clearedFuture; + } + /** * Creates an HTML Dynmap marker information popup widget */ diff --git a/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java b/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java index 9bc289da..150d2b67 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java @@ -14,6 +14,7 @@ import org.jetbrains.annotations.NotNull; import java.io.*; import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; @@ -71,7 +72,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture getServerName(@NotNull OnlineUser requester) { + public CompletableFuture fetchServerName(@NotNull OnlineUser requester) { final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; final CompletableFuture future = new CompletableFuture<>(); serverNameRequests.add(future); @@ -87,7 +88,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture getOnlineServers(@NotNull OnlineUser requester) { + public CompletableFuture fetchOnlineServerList(@NotNull OnlineUser requester) { final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; final CompletableFuture future = new CompletableFuture<>(); onlineServersRequests.add(future); @@ -105,7 +106,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @SuppressWarnings("UnstableApiUsage") public CompletableFuture sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server) { final BukkitHuskHomes plugin = (BukkitHuskHomes) this.plugin; - return getOnlineServers(onlineUser).thenApplyAsync(onlineServers -> { + return fetchOnlineServerList(onlineUser).thenApplyAsync(onlineServers -> { final Optional targetServer = Arrays.stream(onlineServers) .filter(serverName -> serverName.equals(server.name)) .findFirst(); @@ -126,7 +127,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } @Override - public CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { + public CompletableFuture dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message) { final CompletableFuture repliedMessage = new CompletableFuture<>(); processingMessages.put(message.uuid, repliedMessage); sendPluginMessage((BukkitPlayer) sender, message); @@ -172,7 +173,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } @Override - @SuppressWarnings("UnstableApiUsage") + @SuppressWarnings({"UnstableApiUsage", "ForLoopReplaceableByForEach"}) public void onPluginMessageReceived(@NotNull String channel, @NotNull org.bukkit.entity.Player player, final byte[] messageBytes) { if (!channel.equals(BUNGEE_PLUGIN_CHANNEL_NAME)) { @@ -203,18 +204,29 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } case "GetServer" -> { final String serverName = pluginMessage.readUTF(); - serverNameRequests.forEach(future -> future.complete(serverName)); + for (int i = 0; i < serverNameRequests.size(); i++) { + final CompletableFuture future = serverNameRequests.get(i); + future.complete(serverName); + } + serverNameRequests.clear(); } case "PlayerList" -> { pluginMessage.readUTF(); // Read the server name (unused) - final String[] playerNames = pluginMessage.readUTF().split(", "); - onlinePlayerNamesRequests.forEach(future -> future.complete(playerNames)); - } - case "GetServers" -> { - final String[] serverNames = pluginMessage.readUTF().split(", "); - onlineServersRequests.forEach(future -> future.complete(serverNames)); + handleArrayPluginMessage(pluginMessage, onlinePlayerNamesRequests); } + case "GetServers" -> handleArrayPluginMessage(pluginMessage, onlineServersRequests); } } + @SuppressWarnings("ForLoopReplaceableByForEach") + private void handleArrayPluginMessage(@NotNull ByteArrayDataInput pluginMessage, + @NotNull List> requests) { + final String[] fetchedData = pluginMessage.readUTF().split(", "); + for (int i = 0; i < requests.size(); i++) { + final CompletableFuture request = requests.get(i); + request.complete(fetchedData); + } + requests.clear(); + } + } diff --git a/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java b/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java index e04d45b3..08f0cc89 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java @@ -53,7 +53,7 @@ public class RedisMessenger extends PluginMessenger { } @Override - public CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { + public CompletableFuture dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message) { final CompletableFuture repliedMessage = new CompletableFuture<>(); processingMessages.put(message.uuid, repliedMessage); redisWorker.sendMessage(message); diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 86fd7509..e20dd324 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -53,13 +53,13 @@ public interface HuskHomes { List getOnlinePlayers(); /** - * Finds a {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match + * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match * * @param playerName 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 Optional findPlayer(@NotNull String playerName) { + default Optional findOnlinePlayer(@NotNull String playerName) { return getOnlinePlayers().stream() .filter(user -> user.username.equalsIgnoreCase(playerName)) .findFirst() @@ -68,6 +68,29 @@ public interface HuskHomes { .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.username.equalsIgnoreCase(targetPlayerName)) { + return CompletableFuture.completedFuture(Optional.of(requester.username)); + } + final Optional localPlayer = findOnlinePlayer(targetPlayerName); + if (localPlayer.isPresent()) { + return CompletableFuture.completedFuture(Optional.of(localPlayer.get().username)); + } + if (getSettings().crossServer) { + return getNetworkMessenger().findPlayer(requester, targetPlayerName); + } + return CompletableFuture.completedFuture(Optional.empty()); + } + /** * The plugin {@link Settings} loaded from file * 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 bb76d355..8bac4805 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -3,7 +3,6 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; -import net.william278.huskhomes.position.Home; import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; @@ -12,7 +11,6 @@ import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class DelHomeCommand extends CommandBase implements TabCompletable { @@ -76,7 +74,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable { plugin.getLocales().getLocale("home_deleted", homeName).ifPresent(deleter::sendMessage); return; } - if (homeName.equals("all")) { + if (homeName.equalsIgnoreCase("all")) { deleteAllHomes(deleter, homeOwner, delHomeAllConfirm); return; } @@ -86,7 +84,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable { plugin.getLocales().getLocale("home_deleted_other", homeOwner.username, homeName).ifPresent(deleter::sendMessage); return; } - if (homeName.equals("all")) { + if (homeName.equalsIgnoreCase("all")) { deleteAllHomes(deleter, homeOwner, delHomeAllConfirm); return; } @@ -104,26 +102,21 @@ public class DelHomeCommand extends CommandBase implements TabCompletable { */ private void deleteAllHomes(@NotNull OnlineUser deleter, @NotNull User homeOwner, final boolean confirm) { - plugin.getDatabase().getHomes(homeOwner).thenAccept(homes -> { - if (homes.isEmpty()) { + if (!confirm) { + plugin.getLocales().getLocale("delete_all_homes_confirm") + .ifPresent(deleter::sendMessage); + return; + } + + plugin.getSavedPositionManager().deleteAllHomes(homeOwner).thenAccept(deleted -> { + if (deleted == 0) { plugin.getLocales().getLocale("error_no_warps_set") .ifPresent(deleter::sendMessage); return; } - if (!confirm) { - plugin.getLocales().getLocale("delete_all_homes_confirm") - .ifPresent(deleter::sendMessage); - return; - } - - final List> homeDeletionFuture = new ArrayList<>(); - for (final Home toDelete : homes) { - homeDeletionFuture.add(plugin.getSavedPositionManager().deleteHome(homeOwner, toDelete.meta.name)); - } - CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])) - .thenRun(() -> plugin.getLocales().getLocale("delete_all_homes_success", - Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage)); + plugin.getLocales().getLocale("delete_all_homes_success", Integer.toString(deleted)) + .ifPresent(deleter::sendMessage); }); } diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index 4c75088b..b2f6a9b5 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -2,15 +2,12 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.OnlineUser; -import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class DelWarpCommand extends CommandBase implements TabCompletable { @@ -21,6 +18,11 @@ public class DelWarpCommand extends CommandBase implements TabCompletable { @Override public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + if (args.length == 0) { + plugin.getLocales().getLocale("error_invalid_syntax", "/delwarp ") + .ifPresent(onlineUser::sendMessage); + return; + } if (args.length <= 2) { final String warpName = args[0]; final boolean confirm = args.length == 2 && args[1].equalsIgnoreCase("confirm"); @@ -30,7 +32,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable { .ifPresent(onlineUser::sendMessage); return; } - if (warpName.equals("all")) { + if (warpName.equalsIgnoreCase("all")) { deleteAllWarps(onlineUser, confirm); return; } @@ -51,26 +53,21 @@ public class DelWarpCommand extends CommandBase implements TabCompletable { * @param confirm whether to skip the confirmation prompt */ private void deleteAllWarps(@NotNull OnlineUser deleter, final boolean confirm) { - plugin.getDatabase().getWarps().thenAccept(warps -> { - if (warps.isEmpty()) { + if (!confirm) { + plugin.getLocales().getLocale("delete_all_warps_confirm") + .ifPresent(deleter::sendMessage); + return; + } + + plugin.getSavedPositionManager().deleteAllWarps().thenAccept(deleted -> { + if (deleted == 0) { plugin.getLocales().getLocale("error_no_warps_set") .ifPresent(deleter::sendMessage); return; } - if (!confirm) { - plugin.getLocales().getLocale("confirm_delete_all_warps") - .ifPresent(deleter::sendMessage); - return; - } - - final List> homeDeletionFuture = new ArrayList<>(); - for (final Warp toDelete : warps) { - homeDeletionFuture.add(plugin.getSavedPositionManager().deleteWarp(toDelete.meta.name)); - } - CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])) - .thenRun(() -> plugin.getLocales().getLocale("delete_all_warps_success", - Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage)); + plugin.getLocales().getLocale("delete_all_warps_success", Integer.toString(deleted)) + .ifPresent(deleter::sendMessage); }); } 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 e2635865..baddc6c6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -90,7 +90,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE return; } CompletableFuture.runAsync(() -> { - final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null); + final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; 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 2243fe9c..a629a274 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -96,16 +96,16 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable { return; } final List homes = plugin.getDatabase().getHomes(userData.get().user()).join(); - StringJoiner rowJoiner = new StringJoiner(" "); + StringJoiner rowJoiner = new StringJoiner("\t"); plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().username + "'s " + homes.size() + " homes:"); - for (int i = 1; i <= homes.size(); i++) { - final String home = homes.get(i - 1).meta.name; + for (int i = 0; i < homes.size(); i++) { + final String home = homes.get(i).meta.name; rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home); - if (i % 3 == 0) { + if ((i + 1) % 3 == 0) { plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); - rowJoiner = new StringJoiner(" "); + rowJoiner = new StringJoiner("\t"); } } plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); 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 2d4263b8..b5634598 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -102,7 +102,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co return; } CompletableFuture.runAsync(() -> { - final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null); + final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java index 15cb28d3..20b6bc93 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java @@ -64,18 +64,18 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta public void onConsoleExecute(@NotNull String[] args) { CompletableFuture.runAsync(() -> { final List homes = plugin.getDatabase().getPublicHomes().join(); - StringJoiner rowJoiner = new StringJoiner(" "); + StringJoiner rowJoiner = new StringJoiner("\t"); plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:"); - for (int i = 1; i <= homes.size(); i++) { - final String ownerUsername = homes.get(i - 1).owner.username; - final String homeName = homes.get(i - 1).meta.name; + for (int i = 0; i < homes.size(); i++) { + final String ownerUsername = homes.get(i).owner.username; + final String homeName = homes.get(i).meta.name; final String home = ownerUsername + "." + homeName; int spacingSize = (16 - ownerUsername.length()) + 17; rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home); - if (i % 3 == 0) { + if ((i + 1) % 3 == 0) { plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); - rowJoiner = new StringJoiner(" "); + rowJoiner = new StringJoiner("\t"); } } plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); 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 dadb03ae..839c35ce 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -31,7 +31,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); return; } - Optional foundUser = plugin.findPlayer(args[0]); + final Optional foundUser = plugin.findOnlinePlayer(args[0]); if (foundUser.isEmpty()) { plugin.getLocales().getLocale("error_player_not_found", args[0]) .ifPresent(onlineUser::sendMessage); @@ -102,7 +102,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: rtp [player]"); return; } - final Optional foundUser = plugin.findPlayer(args[0]); + final Optional foundUser = plugin.findOnlinePlayer(args[0]); if (foundUser.isEmpty()) { plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; 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 cc8a5ef9..ad4e4eff 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -165,7 +165,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp "); return; } - final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null); + final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java index 97d08fc9..ec51dd63 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java @@ -27,18 +27,27 @@ public class TpHereCommand extends CommandBase implements TabCompletable { return; } final String targetPlayerName = args[0]; - Teleport.builder(plugin, onlineUser) - .setTeleporter(targetPlayerName) - .setTarget(onlineUser.getPosition()) - .toTeleport() - .thenAccept(teleport -> teleport.execute().thenAccept(result -> { - if (result.successful()) { - result.getTeleporter() - .flatMap(teleporter -> plugin.getLocales().getLocale("teleporting_other_complete", - teleporter.username, onlineUser.username)) - .ifPresent(onlineUser::sendMessage); - } - })); + plugin.findPlayer(onlineUser, targetPlayerName).thenAccept(teleporterName -> { + if (teleporterName.isEmpty()) { + plugin.getLocales().getLocale("error_player_not_found", targetPlayerName) + .ifPresent(onlineUser::sendMessage); + return; + } + + Teleport.builder(plugin, onlineUser) + .setTeleporter(teleporterName.get()) + .setTarget(onlineUser.getPosition()) + .toTeleport() + .thenAccept(teleport -> teleport.execute().thenAccept(result -> { + if (result.successful()) { + result.getTeleporter() + .flatMap(teleporter -> plugin.getLocales().getLocale("teleporting_other_complete", + teleporter.username, onlineUser.username)) + .ifPresent(onlineUser::sendMessage); + } + })); + }); + }); } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index ab3315f6..0219da05 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -77,7 +77,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: warp "); return; } - final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null); + final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index dce27676..82b2e642 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -2,13 +2,10 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.OnlineUser; -import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; -import java.util.List; import java.util.StringJoiner; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; public class WarpListCommand extends CommandBase implements ConsoleExecutable { @@ -66,13 +63,13 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable { plugin.getDatabase().getWarps().thenAccept(warps -> { plugin.getLoggingAdapter().log(Level.INFO, "List of " + warps.size() + " warps:"); - StringJoiner rowJoiner = new StringJoiner(" "); - for (int i = 1; i <= warps.size(); i++) { - final String warp = warps.get(i - 1).meta.name; + StringJoiner rowJoiner = new StringJoiner("\t"); + for (int i = 0; i < warps.size(); i++) { + final String warp = warps.get(i).meta.name; rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp); - if (i % 3 == 0) { + if ((i + 1) % 3 == 0) { plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); - rowJoiner = new StringJoiner(" "); + rowJoiner = new StringJoiner("\t"); } } plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); 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 edca3e05..b3dfd209 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -443,6 +443,14 @@ public abstract class Database { */ public abstract CompletableFuture deleteHome(@NotNull UUID uuid); + /** + * Deletes all {@link Home}s of a {@link User} from the home table on the database. + * + * @param user The {@link User} to delete all homes of + * @return A future returning an integer; the number of deleted homes + */ + public abstract CompletableFuture deleteAllHomes(@NotNull User user); + /** * Deletes a {@link Warp} by the given unique id from the warp table on the database. * @@ -451,6 +459,13 @@ public abstract class Database { */ public abstract CompletableFuture deleteWarp(@NotNull UUID uuid); + /** + * Deletes all {@link Warp}s set on the database table + * + * @return A future returning an integer; the number of deleted warps + */ + public abstract CompletableFuture deleteAllWarps(); + /** * Close any remaining connection to the database source */ diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index 5be3f515..3ab61e44 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -634,6 +634,7 @@ public class MySqlDatabase extends Database { new Server(resultSet.getString("server_name")))) .setType(TeleportType.getTeleportType(resultSet.getInt("type")) .orElse(TeleportType.TELEPORT)) + .doUpdateLastPosition(false) .toTeleport() .join()); } @@ -1011,6 +1012,32 @@ public class MySqlDatabase extends Database { }); } + @Override + public CompletableFuture deleteAllHomes(@NotNull User user) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `owner_uuid`=? + ) + );"""))) { + + statement.setString(1, user.uuid.toString()); + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); + } + return 0; + }); + } + @Override public CompletableFuture deleteWarp(@NotNull UUID uuid) { return CompletableFuture.runAsync(() -> { @@ -1036,6 +1063,29 @@ public class MySqlDatabase extends Database { }); } + @Override + public CompletableFuture deleteAllWarps() { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%warps_table%` + ) + );"""))) { + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + } + return 0; + }); + } + @Override public void terminate() { if (dataSource != null) { diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 22b0f3f3..bafda450 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -630,6 +630,7 @@ public class SqLiteDatabase extends Database { new Server(resultSet.getString("server_name")))) .setType(TeleportType.getTeleportType(resultSet.getInt("type")) .orElse(TeleportType.TELEPORT)) + .doUpdateLastPosition(false) .toTeleport() .join()); } @@ -1011,6 +1012,32 @@ public class SqLiteDatabase extends Database { }); } + @Override + public CompletableFuture deleteAllHomes(@NotNull User user) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `owner_uuid`=? + ) + );"""))) { + + statement.setString(1, user.uuid.toString()); + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); + } + return 0; + }); + } + @Override public CompletableFuture deleteWarp(@NotNull UUID uuid) { return CompletableFuture.runAsync(() -> { @@ -1036,6 +1063,29 @@ public class SqLiteDatabase extends Database { }); } + @Override + public CompletableFuture deleteAllWarps() { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%warps_table%` + ) + );"""))) { + return statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + } + return 0; + }); + } + @Override public void terminate() { try { 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 b64938b2..6323661d 100644 --- a/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java +++ b/common/src/main/java/net/william278/huskhomes/event/EventDispatcher.java @@ -1,6 +1,7 @@ package net.william278.huskhomes.event; import net.william278.huskhomes.player.OnlineUser; +import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.teleport.Teleport; @@ -32,4 +33,7 @@ public interface EventDispatcher { CompletableFuture dispatchViewWarpListEvent(@NotNull List homes, @NotNull OnlineUser user); + CompletableFuture dispatchDeleteAllHomesEvent(@NotNull User user); + + 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 new file mode 100644 index 00000000..10f57a99 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllHomesEvent.java @@ -0,0 +1,19 @@ +package net.william278.huskhomes.event; + +import net.william278.huskhomes.player.User; +import org.jetbrains.annotations.NotNull; + +/** + * Representation of an event that fires when all homes are deleted + */ +public interface IDeleteAllHomesEvent extends CancellableEvent { + + /** + * Get the player whose homes are being deleted + * + * @return the {@link User} whose homes are being deleted + */ + @NotNull + User getHomeOwner(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java new file mode 100644 index 00000000..fbeef111 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/event/IDeleteAllWarpsEvent.java @@ -0,0 +1,8 @@ +package net.william278.huskhomes.event; + +/** + * Representation of an event that fires when all warps are deleted + */ +public interface IDeleteAllWarpsEvent extends CancellableEvent { + +} 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 5d7243b1..ce921830 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IHomeDeleteEvent.java @@ -4,7 +4,7 @@ import net.william278.huskhomes.position.Home; import org.jetbrains.annotations.NotNull; /** - * Representation of an event that fires when a home is deleted + * Representation of an event that fires when a single home is deleted */ public interface IHomeDeleteEvent extends CancellableEvent { 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 f02a6dc0..cf139669 100644 --- a/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java +++ b/common/src/main/java/net/william278/huskhomes/event/IWarpDeleteEvent.java @@ -4,7 +4,7 @@ import net.william278.huskhomes.position.Warp; import org.jetbrains.annotations.NotNull; /** - * Representation of an event that fires when a warp is deleted + * Representation of an event that fires when a single warp is deleted */ public interface IWarpDeleteEvent extends CancellableEvent { diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java index 8e8132e1..18c398e7 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java @@ -6,6 +6,7 @@ import de.bluecolored.bluemap.api.BlueMapWorld; import de.bluecolored.bluemap.api.markers.MarkerSet; import de.bluecolored.bluemap.api.markers.POIMarker; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.position.World; @@ -73,7 +74,7 @@ public class BlueMapHook extends MapHook { blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world)).ifPresent(blueMapWorld -> blueMapWorld.getMaps() .forEach(blueMapMap -> blueMapMap.getMarkerSets() .computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> { - markerSet.getMarkers().put(home.uuid.toString(), + markerSet.getMarkers().put(home.owner.uuid + ":" + home.uuid, POIMarker.toBuilder() .label("/phome" + home.owner.username + "." + home.meta.name) .position((int) home.x, (int) home.y, (int) home.z) @@ -91,12 +92,25 @@ public class BlueMapHook extends MapHook { BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world)) .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets() .computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> { - markerSet.getMarkers().remove(home.uuid.toString()); + markerSet.getMarkers().remove(home.owner.uuid + ":" + home.uuid); return markerSet; }))); return CompletableFuture.completedFuture(null); } + @Override + public CompletableFuture clearHomes(@NotNull User user) { + BlueMapAPI.getInstance().ifPresent((BlueMapAPI blueMapAPI) -> blueMapAPI.getWorlds() + .forEach(blueMapWorld -> blueMapWorld.getMaps() + .forEach(blueMapMap -> blueMapMap.getMarkerSets() + .computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> { + markerSet.getMarkers().keySet().removeIf(key -> key.startsWith(user.uuid.toString())); + return markerSet; + })))); + + return CompletableFuture.completedFuture(null); + } + @Override public CompletableFuture updateWarp(@NotNull Warp warp) { if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null); @@ -128,6 +142,19 @@ public class BlueMapHook extends MapHook { return CompletableFuture.completedFuture(null); } + @Override + public CompletableFuture clearWarps() { + BlueMapAPI.getInstance().ifPresent((BlueMapAPI blueMapAPI) -> blueMapAPI.getWorlds() + .forEach(blueMapWorld -> blueMapWorld.getMaps() + .forEach(blueMapMap -> blueMapMap.getMarkerSets() + .computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> { + markerSet.getMarkers().clear(); + return markerSet; + })))); + + return CompletableFuture.completedFuture(null); + } + /** * Get the {@link BlueMapWorld} for a world * diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java index 3af01f94..22f8cc5d 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java @@ -2,6 +2,7 @@ package net.william278.huskhomes.hook; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomesException; +import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.SavedPosition; import net.william278.huskhomes.position.Warp; @@ -60,6 +61,14 @@ public abstract class MapHook extends PluginHook { */ public abstract CompletableFuture removeHome(@NotNull Home home); + /** + * Clears homes owned by a player from the map + * + * @param user the player whose homes to clear + * @return a {@link CompletableFuture} that completes when the homes have been cleared + */ + public abstract CompletableFuture clearHomes(@NotNull User user); + /** * Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't * @@ -75,6 +84,13 @@ public abstract class MapHook extends PluginHook { */ public abstract CompletableFuture removeWarp(@NotNull Warp warp); + /** + * Clears all warps from the map + * + * @return a {@link CompletableFuture} that completes when the warps have been cleared + */ + public abstract CompletableFuture clearWarps(); + /** * Returns if the position is valid to be set on this server * diff --git a/common/src/main/java/net/william278/huskhomes/messenger/Message.java b/common/src/main/java/net/william278/huskhomes/messenger/Message.java index 1bf9e035..3346af37 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/Message.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/Message.java @@ -24,7 +24,7 @@ public class Message { public MessageType type; /** - * The kind of message this is - {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message. + * Represents the context under which this message is being relayed; an outbound {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to one. */ @SerializedName("relay_type") @NotNull @@ -91,7 +91,13 @@ public class Message { * Identifies the source of the message being relayed - a {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message. */ public enum RelayType { + /** + * An outbound message to/from a server + */ MESSAGE, + /** + * A reply to an outbound message + */ REPLY } diff --git a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java index 98f2d71a..505918b7 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java @@ -8,6 +8,8 @@ import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; public abstract class NetworkMessenger { @@ -22,7 +24,7 @@ public abstract class NetworkMessenger { protected HashMap> processingMessages; /** - * List of pending futures for processing {@link #getServerName(OnlineUser)} requests + * List of pending futures for processing {@link #fetchServerName(OnlineUser)} requests */ protected List> serverNameRequests; @@ -32,7 +34,7 @@ public abstract class NetworkMessenger { protected List> onlinePlayerNamesRequests; /** - * List of pending futures for processing {@link #getOnlineServers(OnlineUser)} requests + * List of pending futures for processing {@link #fetchOnlineServerList(OnlineUser)} requests */ protected List> onlineServersRequests; @@ -46,6 +48,11 @@ public abstract class NetworkMessenger { */ protected HuskHomes plugin; + /** + * The time-to-live of a message before it expires and the {@link CompletableFuture} is cancelled + */ + private final long MESSAGE_TIME_OUT = 5L; + /** * Initialize the network messenger * @@ -93,7 +100,7 @@ public abstract class NetworkMessenger { * @param requester {@link OnlineUser} to send the request * @return Future returning the name of this server on the network */ - public abstract CompletableFuture getServerName(@NotNull OnlineUser requester); + public abstract CompletableFuture fetchServerName(@NotNull OnlineUser requester); /** * Fetch a list of online server names proxy @@ -101,7 +108,7 @@ public abstract class NetworkMessenger { * @param requester {@link OnlineUser} to send the request * @return Future returning a {@link List} of online servers connected to the proxy network */ - public abstract CompletableFuture getOnlineServers(@NotNull OnlineUser requester); + public abstract CompletableFuture fetchOnlineServerList(@NotNull OnlineUser requester); /** * Send a {@link OnlineUser} to a target {@link Server} on the proxy network @@ -113,12 +120,34 @@ public abstract class NetworkMessenger { public abstract CompletableFuture sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server); /** - * Send a network {@link Message} to a target player on the proxy + * Send a network message * - * @param message The {@link Message} to send + * @param sender {@link OnlineUser} sending the message + * @param message {@link Message} to send + * @return Future returning the {@link Message} sent, that will time out after + * @apiNote This method invokes {@link #dispatchMessage(OnlineUser, Message)}, applying a time-to-live timeOut + */ + public final CompletableFuture> sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { + return dispatchMessage(sender, message) + .orTimeout(MESSAGE_TIME_OUT, TimeUnit.SECONDS) + .exceptionally(e -> { + plugin.getLoggingAdapter().log(Level.WARNING, "Message dispatch after " + MESSAGE_TIME_OUT + " seconds", e); + return null; + }) + .thenApply(result -> { + processingMessages.remove(message.uuid); + return Optional.ofNullable(result); + }); + } + + /** + * Dispatch a {@link Message} via the appropriate handler + * + * @param sender The {@link OnlineUser} that sent the {@link Message} + * @param message The {@link Message} to dispatch * @return A future containing a reply to the {@link Message} that was sent */ - public abstract CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message); + protected abstract CompletableFuture dispatchMessage(@NotNull OnlineUser sender, @NotNull Message message); /** * Send a reply to a received {@link Message} @@ -142,14 +171,23 @@ public abstract class NetworkMessenger { if (processingMessages.containsKey(message.uuid)) { final Message finalMessage = message; processingMessages.get(message.uuid).completeAsync(() -> finalMessage); + return; } + plugin.getLoggingAdapter().log(Level.WARNING, "Received a reply to a message that was not sent by this server"); } } } + /** + * Handle different message types, executed needed operations and dispatches a reply message + * to the sender + * + * @param receiver The {@link OnlineUser} receiving the message + * @param message The received {@link Message} + * @return A future containing the reply {@link Message} + */ private CompletableFuture prepareReply(@NotNull final OnlineUser receiver, @NotNull final Message message) { return CompletableFuture.supplyAsync(() -> { - // Handle different message types and apply changes for reply message switch (message.type) { case TELEPORT_TO_POSITION_REQUEST -> { if (message.payload.position != null) { @@ -176,15 +214,29 @@ public abstract class NetworkMessenger { } } } - - // Prepare reply message - message.targetPlayer = message.sender; - message.sender = receiver.username; - message.relayType = Message.RelayType.REPLY; return message; + }).exceptionally(exception -> { + plugin.getLoggingAdapter().log(Level.WARNING, "Failed to prepare message reply", exception); + message.payload = MessagePayload.empty(); + return message; + }).thenApply(reply -> { + formatReplyMessage(message, receiver); + return reply; }); } + /** + * Prepare a {@link Message} to be sent as a reply to a received {@link Message} + * + * @param message The received {@link Message} + * @param receiver The {@link OnlineUser} receiving the message + */ + private void formatReplyMessage(@NotNull Message message, @NotNull OnlineUser receiver) { + message.targetPlayer = message.sender; + message.sender = receiver.username; + message.relayType = Message.RelayType.REPLY; + } + /** * Close the network messenger */ diff --git a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java index 19956710..fdc1ea47 100644 --- a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java +++ b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java @@ -152,6 +152,20 @@ public class SavedPositionManager { }); } + public CompletableFuture deleteAllHomes(@NotNull User user) { + return CompletableFuture.supplyAsync(() -> eventDispatcher.dispatchDeleteAllHomesEvent(user).join().isCancelled()) + .thenApply(cancelled -> database.deleteAllHomes(user) + .thenApply(result -> { + cache.homes.remove(user.uuid); + cache.privateHomeLists.remove(user.username); + cache.publicHomeLists.clear(); + if (mapHook != null) { + mapHook.clearHomes(user); + } + return result; + }).join()); + } + /** * Tries to update an existing home with new metadata * @@ -320,6 +334,18 @@ public class SavedPositionManager { }); } + public CompletableFuture deleteAllWarps() { + return CompletableFuture.supplyAsync(() -> eventDispatcher.dispatchDeleteAllWarpsEvent().join().isCancelled()) + .thenApply(cancelled -> database.deleteAllWarps() + .thenApply(result -> { + cache.warps.clear(); + if (mapHook != null) { + mapHook.clearWarps(); + } + return result; + }).join()); + } + /** * Tries to update an existing warp with new metadata * diff --git a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java index 63dc082d..4ad86237 100644 --- a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java +++ b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java @@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; /** * Manages {@link TeleportRequest}s between players @@ -129,7 +128,7 @@ public class RequestManager { @NotNull TeleportRequest.RequestType requestType) { final TeleportRequest request = new TeleportRequest(requester, requestType, Instant.now().getEpochSecond() + plugin.getSettings().teleportRequestExpiryTime); - final Optional localTarget = plugin.findPlayer(targetUser); + final Optional localTarget = plugin.findOnlinePlayer(targetUser); if (localTarget.isPresent()) { if (localTarget.get().uuid.equals(requester.uuid)) { return CompletableFuture.completedFuture(Optional.empty()); @@ -148,26 +147,25 @@ public class RequestManager { // Use the network messenger to send the request request.recipientName = networkedTarget.get(); - return Optional.ofNullable(plugin.getNetworkMessenger().sendMessage(requester, - new Message(Message.MessageType.TELEPORT_REQUEST, - requester.username, - networkedTarget.get(), - MessagePayload.withTeleportRequest(request), - Message.RelayType.MESSAGE, - plugin.getSettings().clusterId)) - .orTimeout(3, TimeUnit.SECONDS) - .exceptionally(throwable -> null) + return plugin.getNetworkMessenger() + .sendMessage(requester, new Message(Message.MessageType.TELEPORT_REQUEST, + requester.username, + networkedTarget.get(), + MessagePayload.withTeleportRequest(request), + Message.RelayType.MESSAGE, + plugin.getSettings().clusterId)) .thenApply(reply -> { - if (reply == null || reply.payload.teleportRequest == null) { - return null; - } - - // If the message was ignored by the recipient, return false - if (reply.payload.teleportRequest.status == TeleportRequest.RequestStatus.PENDING) { - return request; + if (reply.isPresent()) { + final TeleportRequest result = reply.get().payload.teleportRequest; + if (result == null || result.status == TeleportRequest.RequestStatus.IGNORED) { + return null; + } + return result; } return null; - }).join()); + }) + .thenApply(Optional::ofNullable) + .join(); }); } return CompletableFuture.completedFuture(Optional.empty()); @@ -280,7 +278,7 @@ public class RequestManager { request.status = accepted ? TeleportRequest.RequestStatus.ACCEPTED : TeleportRequest.RequestStatus.DECLINED; // Send request response to the sender - final Optional localRequester = plugin.findPlayer(request.requesterName); + final Optional localRequester = plugin.findOnlinePlayer(request.requesterName); if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); } else if (plugin.getSettings().crossServer) { @@ -294,16 +292,15 @@ public class RequestManager { return false; } - return plugin.getNetworkMessenger().sendMessage(recipient, - new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE, - recipient.username, - networkedTarget.get(), - MessagePayload.withTeleportRequest(request), - Message.RelayType.MESSAGE, - plugin.getSettings().clusterId)) - .thenApply(reply -> true) - .orTimeout(3, TimeUnit.SECONDS) - .exceptionally(throwable -> false).join(); + return plugin.getNetworkMessenger() + .sendMessage(recipient, new Message(Message.MessageType.TELEPORT_REQUEST_RESPONSE, + recipient.username, + networkedTarget.get(), + MessagePayload.withTeleportRequest(request), + Message.RelayType.MESSAGE, + plugin.getSettings().clusterId)) + .thenApply(Optional::isPresent) + .join(); }) .thenAccept(online -> { if (!online) { 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 8555e557..43975985 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -60,18 +60,24 @@ public class Teleport { @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, - @NotNull HuskHomes plugin) { + final boolean updateLastPosition, @NotNull HuskHomes plugin) { this.teleporter = teleporter; this.executor = executor; this.target = target; this.type = type; this.economyActions = economyActions; this.plugin = plugin; + this.updateLastPosition = updateLastPosition; } /** @@ -167,7 +173,7 @@ public class Teleport { // Dispatch the teleport event and update the player's last position plugin.getEventDispatcher().dispatchTeleportEvent(this); - if (!plugin.getSettings().backCommandSaveOnTeleportEvent && type == TeleportType.TELEPORT) { + if (updateLastPosition && !plugin.getSettings().backCommandSaveOnTeleportEvent && type == TeleportType.TELEPORT) { plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); } @@ -217,13 +223,14 @@ public class Teleport { MessagePayload.withPosition(target), Message.RelayType.MESSAGE, plugin.getSettings().clusterId)) - .orTimeout(3, TimeUnit.SECONDS) - .exceptionally(throwable -> null) .thenApply(result -> { - if (result == null || result.payload.resultState == null) { - return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED; + if (result.isPresent()) { + final Message reply = result.get(); + if (reply.payload.resultState != null) { + return reply.payload.resultState; + } } - return result.payload.resultState; + return TeleportResult.FAILED_TELEPORTER_NOT_RESOLVED; }); } 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 c53512cf..95f88794 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; import java.util.logging.Level; /** @@ -57,6 +56,11 @@ public class TeleportBuilder { */ private TeleportType type = TeleportType.TELEPORT; + /** + * Whether this teleport should update the user's last position (i.e. their {@code /back} position) + */ + private boolean updateLastPosition = true; + protected TeleportBuilder(@NotNull HuskHomes plugin, @NotNull OnlineUser executor) { this.plugin = plugin; this.executor = executor; @@ -83,7 +87,7 @@ public class TeleportBuilder { */ public TeleportBuilder setTeleporter(@NotNull String teleporterUsername) { this.teleporter = CompletableFuture.supplyAsync(() -> plugin - .findPlayer(teleporterUsername) + .findOnlinePlayer(teleporterUsername) .map(onlineUser -> (User) onlineUser) .or(() -> { if (plugin.getSettings().crossServer) { @@ -168,6 +172,17 @@ public class TeleportBuilder { 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) { + this.updateLastPosition = updateLastPosition; + return this; + } + /** * Resolve the teleporter and target, and construct as an instantly-completing {@link Teleport} * @@ -178,7 +193,7 @@ public class TeleportBuilder { final User teleporter = this.teleporter.join(); final Position target = this.target.join(); - return new Teleport(teleporter, executor, target, type, economyActions, plugin); + return new Teleport(teleporter, executor, target, type, economyActions, updateLastPosition, plugin); }).exceptionally(e -> { plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create teleport", e); return null; @@ -200,7 +215,7 @@ public class TeleportBuilder { throw new IllegalStateException("Timed teleports can only be executed for local users"); } - return new TimedTeleport(onlineUser, executor, target, type, warmupTime, economyActions, plugin); + 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; @@ -214,24 +229,22 @@ public class TeleportBuilder { * @return future optionally supplying the player's position, if the player could be found */ private CompletableFuture> getPlayerPosition(@NotNull String playerName) { - final Optional localPlayer = plugin.findPlayer(playerName); + final Optional localPlayer = plugin.findOnlinePlayer(playerName); if (localPlayer.isPresent()) { return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition())); } if (plugin.getSettings().crossServer) { return plugin.getNetworkMessenger() .findPlayer(executor, playerName) - .thenApply(foundPlayer -> { + .thenApplyAsync(foundPlayer -> { if (foundPlayer.isEmpty()) { return Optional.empty(); } return plugin.getNetworkMessenger() - .sendMessage(executor, new Message(Message.MessageType.POSITION_REQUEST, executor.username, - playerName, MessagePayload.empty(), Message.RelayType.MESSAGE, - plugin.getSettings().clusterId)) - .orTimeout(3, TimeUnit.SECONDS) - .exceptionally(throwable -> null) - .thenApply(reply -> Optional.ofNullable(reply.payload.position)).join(); + .sendMessage(executor, new Message(Message.MessageType.POSITION_REQUEST, + executor.username, playerName, MessagePayload.empty(), + Message.RelayType.MESSAGE, plugin.getSettings().clusterId)) + .thenApply(reply -> reply.map(message -> message.payload.position)).join(); }); } return CompletableFuture.supplyAsync(Optional::empty); 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 c6e52d9a..c4c7ee4f 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -25,12 +25,12 @@ public class TimedTeleport extends Teleport { protected TimedTeleport(@NotNull OnlineUser teleporter, @NotNull OnlineUser executor, @NotNull Position target, @NotNull TeleportType type, int warmupTime, @NotNull Set economyActions, - @NotNull HuskHomes plugin) { - super(teleporter, executor, target, type, economyActions, plugin); + final boolean updateLastPosition, @NotNull HuskHomes plugin) { + super(teleporter, executor, target, type, economyActions, updateLastPosition, plugin); this.plugin = plugin; this.startLocation = teleporter.getPosition(); this.startHealth = teleporter.getHealth(); - this.timeLeft = warmupTime; + this.timeLeft = Math.max(warmupTime, 0); this.teleporter = teleporter; } @@ -47,17 +47,17 @@ public class TimedTeleport extends Teleport { .thenApply(resultState -> CompletedTeleport.from(resultState, this)); } + // Check if the teleporter can bypass warmup + if (timeLeft == 0 || teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) { + return super.execute(); + } + // Check if the teleporter is already warming up to teleport if (plugin.getCache().currentlyOnWarmup.contains(teleporter.uuid)) { return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING) .thenApply(resultState -> CompletedTeleport.from(resultState, this)); } - // Check if the teleporter can bypass warmup - if (teleporter.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node)) { - return super.execute(); - } - // Check economy actions for (Settings.EconomyAction economyAction : economyActions) { if (!plugin.validateEconomyCheck(executor, economyAction)) { diff --git a/gradle.properties b/gradle.properties index 58ad9d6a..9da213dc 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true javaVersion=16 -plugin_version=3.1.1 +plugin_version=3.2 plugin_archive=huskhomes jedis_version=4.2.3