From 11d05efcfaaecab4ce5fc8d3408d923d985cce47 Mon Sep 17 00:00:00 2001 From: William Date: Thu, 18 Aug 2022 22:08:21 +0100 Subject: [PATCH] Add RequestManager, handle networked requests, new locales --- .../william278/huskhomes/BukkitHuskHomes.java | 11 +- .../huskhomes/messenger/PluginMessenger.java | 22 +- .../huskhomes/{cache => }/Cache.java | 8 +- .../net/william278/huskhomes/HuskHomes.java | 27 +- .../william278/huskhomes/config/Settings.java | 3 + .../huskhomes/messenger/Message.java | 7 +- .../huskhomes/messenger/MessagePayload.java | 21 ++ .../huskhomes/messenger/NetworkMessenger.java | 44 +++- .../position/SavedPositionManager.java | 2 +- .../huskhomes/request/RequestManager.java | 244 ++++++++++++++++++ .../huskhomes/request/TeleportRequest.java | 87 +++++++ .../huskhomes/teleport/TeleportManager.java | 2 +- common/src/main/resources/locales/en-gb.yml | 29 ++- 13 files changed, 464 insertions(+), 43 deletions(-) rename common/src/main/java/net/william278/huskhomes/{cache => }/Cache.java (98%) create mode 100644 common/src/main/java/net/william278/huskhomes/request/RequestManager.java create mode 100644 common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 8877a42c..9c5e5115 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -2,7 +2,6 @@ package net.william278.huskhomes; import net.william278.annotaml.Annotaml; import net.william278.annotaml.AnnotamlException; -import net.william278.huskhomes.cache.Cache; import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.BukkitCommandType; import net.william278.huskhomes.config.Locales; @@ -20,6 +19,7 @@ import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.position.Server; +import net.william278.huskhomes.request.RequestManager; import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.*; import org.bstats.bukkit.Metrics; @@ -56,6 +56,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { private Database database; private Cache cache; private TeleportManager teleportManager; + private RequestManager requestManager; private SavedPositionManager savedPositionManager; private EventListener eventListener; @@ -152,6 +153,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Prepare the teleport manager this.teleportManager = new TeleportManager(this); + // Prepare the request manager + this.requestManager = new RequestManager(this); + // Prepare the home and warp position manager this.savedPositionManager = new SavedPositionManager(database, cache); @@ -263,6 +267,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { return teleportManager; } + @Override + public @NotNull RequestManager getRequestManager() { + return requestManager; + } + @NotNull @Override public SavedPositionManager getSavedPositionManager() { 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 cc828413..6acc2b4c 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java @@ -48,7 +48,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("PlayerList"); pluginMessageWriter.writeUTF("ALL"); - ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage((BukkitHuskHomes) plugin, BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return onlinePlayerNamesRequest; @@ -60,7 +60,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi serverNameRequest = new CompletableFuture<>(); final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("GetServer"); - ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage((BukkitHuskHomes) plugin, BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return serverNameRequest; @@ -72,7 +72,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi onlineServersRequest = new CompletableFuture<>(); final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("GetServers"); - ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage((BukkitHuskHomes) plugin, BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return onlineServersRequest; @@ -87,7 +87,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("Connect"); pluginMessageWriter.writeUTF(server.name); - ((BukkitPlayer) onlineUser).sendPluginMessage(BukkitHuskHomes.getInstance(), + ((BukkitPlayer) onlineUser).sendPluginMessage((BukkitHuskHomes) plugin, BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return true; @@ -126,26 +126,26 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi messageWriter.write(messageByteOutputStream.toByteArray()); } } catch (IOException e) { - BukkitHuskHomes.getInstance().getLoggingAdapter().log(Level.SEVERE, + plugin.getLoggingAdapter().log(Level.SEVERE, "An error occurred dispatching a plugin message", e); } // Send the written message - player.sendPluginMessage(BukkitHuskHomes.getInstance(), + player.sendPluginMessage((BukkitHuskHomes) plugin, BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray()); }); } @Override public void terminate() { - Bukkit.getMessenger().unregisterIncomingPluginChannel(BukkitHuskHomes.getInstance()); - Bukkit.getMessenger().unregisterIncomingPluginChannel(BukkitHuskHomes.getInstance()); + Bukkit.getMessenger().unregisterIncomingPluginChannel((BukkitHuskHomes) plugin); + Bukkit.getMessenger().unregisterIncomingPluginChannel((BukkitHuskHomes) plugin); } @Override @SuppressWarnings("UnstableApiUsage") public void onPluginMessageReceived(@NotNull String channel, @NotNull org.bukkit.entity.Player player, - @NotNull byte[] messageBytes) { + final byte[] messageBytes) { if (!channel.equals(BUNGEE_PLUGIN_CHANNEL_NAME)) { return; } @@ -168,7 +168,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi handleMessage(BukkitPlayer.adapt(player), message); } catch (IOException e) { - BukkitHuskHomes.getInstance().getLoggingAdapter().log(Level.SEVERE, + plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to read an inbound plugin message", e); } } @@ -179,7 +179,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } } case "PlayerList" -> { - final String serverName = pluginMessage.readUTF(); + pluginMessage.readUTF(); // Read the server name (unused) final String[] playerNames = pluginMessage.readUTF().split(", "); if (onlinePlayerNamesRequest != null) { onlinePlayerNamesRequest.completeAsync(() -> playerNames); diff --git a/common/src/main/java/net/william278/huskhomes/cache/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java similarity index 98% rename from common/src/main/java/net/william278/huskhomes/cache/Cache.java rename to common/src/main/java/net/william278/huskhomes/Cache.java index f649cfa1..01bcf990 100644 --- a/common/src/main/java/net/william278/huskhomes/cache/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -1,7 +1,6 @@ -package net.william278.huskhomes.cache; +package net.william278.huskhomes; import de.themoep.minedown.MineDown; -import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.database.Database; import net.william278.huskhomes.player.OnlineUser; @@ -12,7 +11,10 @@ import net.william278.paginedown.ListOptions; import net.william278.paginedown.PaginatedList; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 82679349..409d61f6 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -1,6 +1,5 @@ package net.william278.huskhomes; -import net.william278.huskhomes.cache.Cache; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.database.Database; @@ -9,6 +8,7 @@ import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.SavedPositionManager; +import net.william278.huskhomes.request.RequestManager; import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.Logger; import net.william278.huskhomes.util.Version; @@ -16,6 +16,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -40,6 +41,21 @@ public interface HuskHomes { @NotNull List getOnlinePlayers(); + /** + * Finds a {@link OnlineUser} by their name. Auto-completes partially typed names for a 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 + */ + default Optional findPlayer(@NotNull String playerName) { + return Optional.ofNullable(getOnlinePlayers().stream() + .filter(user -> user.username.equalsIgnoreCase(playerName)) + .findFirst() + .orElse(getOnlinePlayers().stream() + .filter(user -> user.username.toLowerCase().startsWith(playerName.toLowerCase())) + .findFirst().orElse(null))); + } + /** * The plugin {@link Settings} loaded from file * @@ -75,11 +91,18 @@ public interface HuskHomes { /** * The {@link TeleportManager} that manages player teleports * - * @return the {@link TeleportManager} implementation + * @return the plugin {@link TeleportManager} */ @NotNull TeleportManager getTeleportManager(); + /** + * The {@link RequestManager} that manages player requests + * + * @return the plugin {@link RequestManager} + */ + @NotNull RequestManager getRequestManager(); + /** * The {@link SavedPositionManager} that manages setting homes and warps * diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index 84b38bce..4a150cd1 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -93,6 +93,9 @@ public class Settings { @KeyPath("general.list_items_per_page") public int listItemsPerPage = 12; + @KeyPath("general.strict_tpa_here_requests") + public boolean strictTpaHereRequests = true; + @KeyPath("general.allow_unicode_names") public boolean allowUnicodeNames = false; 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 7fe468cd..1bf9e035 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/Message.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/Message.java @@ -81,9 +81,10 @@ public class Message { * Identifies the type of message or reply */ public enum MessageType { - TP_REQUEST, - TP_TO_POSITION_REQUEST, - POSITION_REQUEST + TELEPORT_TO_POSITION_REQUEST, + POSITION_REQUEST, + TELEPORT_REQUEST, + TELEPORT_REQUEST_RESPONSE } /** diff --git a/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java b/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java index 9614aeb5..60522649 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/MessagePayload.java @@ -2,6 +2,7 @@ package net.william278.huskhomes.messenger; import com.google.gson.annotations.SerializedName; import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.request.TeleportRequest; import net.william278.huskhomes.teleport.TeleportResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,6 +25,13 @@ public class MessagePayload { @SerializedName("teleport_result") public TeleportResult teleportResult; + /** + * A teleport request field + */ + @Nullable + @SerializedName("teleport_request") + public TeleportRequest teleportRequest; + /** * Returns an empty cross-server message payload * @@ -60,6 +68,19 @@ public class MessagePayload { return payload; } + /** + * Returns a payload containing a {@link TeleportRequest} + * + * @param teleportRequest the teleport to send + * @return a payload containing the teleport request + */ + @NotNull + public static MessagePayload withTeleportRequest(@NotNull TeleportRequest teleportRequest) { + final MessagePayload payload = new MessagePayload(); + payload.teleportRequest = teleportRequest; + return payload; + } + private MessagePayload() { } 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 9f9fe8f7..ca0ef6ff 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java @@ -5,9 +5,7 @@ import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Server; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CompletableFuture; public abstract class NetworkMessenger { @@ -45,7 +43,7 @@ public abstract class NetworkMessenger { /** * The implementing HuskHomes plugin instance */ - private HuskHomes plugin; + protected HuskHomes plugin; /** * Initialize the network messenger @@ -66,6 +64,25 @@ public abstract class NetworkMessenger { */ public abstract CompletableFuture getOnlinePlayerNames(@NotNull OnlineUser requester); + /** + * Find a player on the proxy network by username to validate if they exist. + * + * @param requester {@link OnlineUser} to send the request + * @param playerName Approximate name of the player to find. If an exact match is not found, + * this will attempt to return the closest match + * @return Future returning an {@link Optional} of the player's canonical username if found; + * otherwise an empty {@link Optional} + */ + public final CompletableFuture> findPlayer(@NotNull OnlineUser requester, @NotNull String playerName) { + return getOnlinePlayerNames(requester).thenApply(networkedPlayers -> + Optional.ofNullable(Arrays.stream(networkedPlayers) + .filter(user -> user.equalsIgnoreCase(playerName)) + .findFirst() + .orElse(Arrays.stream(networkedPlayers) + .filter(user -> user.toLowerCase().startsWith(playerName)) + .findFirst().orElse(null)))); + } + /** * Fetch the name of this server on the proxy network * @@ -130,10 +147,7 @@ public abstract class NetworkMessenger { return CompletableFuture.supplyAsync(() -> { // Handle different message types and apply changes for reply message switch (message.type) { - case TP_REQUEST -> { - //todo - } - case TP_TO_POSITION_REQUEST -> { + case TELEPORT_TO_POSITION_REQUEST -> { if (message.payload.position != null) { message.payload = MessagePayload.withTeleportResult(plugin.getTeleportManager() .teleport(receiver, message.payload.position).join()); @@ -142,6 +156,20 @@ public abstract class NetworkMessenger { } } case POSITION_REQUEST -> message.payload = MessagePayload.withPosition(receiver.getPosition().join()); + case TELEPORT_REQUEST -> { + if (message.payload.teleportRequest != null) { + plugin.getRequestManager().sendLocalTeleportRequest(message.payload.teleportRequest, receiver); + } else { + message.payload = MessagePayload.empty(); + } + } + case TELEPORT_REQUEST_RESPONSE -> { + if (message.payload.teleportRequest != null) { + plugin.getRequestManager().handleLocalRequestResponse(receiver, message.payload.teleportRequest); + } else { + message.payload = MessagePayload.empty(); + } + } } // Prepare reply message 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 7ed228f0..429690a8 100644 --- a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java +++ b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java @@ -1,6 +1,6 @@ package net.william278.huskhomes.position; -import net.william278.huskhomes.cache.Cache; +import net.william278.huskhomes.Cache; import net.william278.huskhomes.database.Database; import net.william278.huskhomes.player.User; import net.william278.huskhomes.util.RegexUtil; diff --git a/common/src/main/java/net/william278/huskhomes/request/RequestManager.java b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java new file mode 100644 index 00000000..45a93157 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/request/RequestManager.java @@ -0,0 +1,244 @@ +package net.william278.huskhomes.request; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.messenger.Message; +import net.william278.huskhomes.messenger.MessagePayload; +import net.william278.huskhomes.player.OnlineUser; +import net.william278.huskhomes.player.User; +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 + */ +public class RequestManager { + + @NotNull + private final HuskHomes plugin; + + /** + * Map of user UUIDs to a list of received teleport requests + */ + private final Map> requests; + + /** + * Set of users who are ignoring tpa requests + */ + private final Set ignoringRequests; + + public RequestManager(@NotNull HuskHomes implementation) { + this.plugin = implementation; + this.requests = new HashMap<>(); + this.ignoringRequests = new HashSet<>(); + } + + public void addTeleportRequest(@NotNull TeleportRequest request, @NotNull User recipient) { + this.requests.computeIfAbsent(recipient.uuid, uuid -> new ArrayList<>()).add(request); + } + + public void removeTeleportRequest(@NotNull TeleportRequest request, @NotNull User recipient) { + this.requests.computeIfPresent(recipient.uuid, (uuid, set) -> { + set.remove(request); + return set.isEmpty() ? null : set; + }); + } + + public Optional getLastTeleportRequest(@NotNull User recipient) { + return this.requests.getOrDefault(recipient.uuid, Collections.emptyList()).stream().reduce((a, b) -> b); + } + + public Optional getTeleportRequest(@NotNull String requesterName, @NotNull User recipient) { + return this.requests.getOrDefault(recipient.uuid, Collections.emptyList()).stream().filter(request -> + request.requester.username.equals(requesterName)).findFirst(); + } + + /** + * Sends a teleport request of the given type to the specified user, by name, if they exist. + * + * @param requester The user making the request + * @param targetUser The user to send the request to + * @param requestType The type of request to send + * @return A {@link CompletableFuture} that will return {@code true} if the request was successfully sent, or + * {@code false} if it was not as the user was not found + */ + public CompletableFuture sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, + @NotNull TeleportRequest.RequestType requestType) { + final TeleportRequest request = new TeleportRequest(requester, requestType, + Instant.now().getEpochSecond() + plugin.getSettings().teleportRequestExpiryTime); + final Optional localTarget = plugin.findPlayer(targetUser); + if (localTarget.isPresent()) { + request.recipientName = localTarget.get().username; + return CompletableFuture.supplyAsync(() -> sendLocalTeleportRequest(request, localTarget.get())); + } + + // If the player couldn't be found locally, send the request cross-server + if (plugin.getSettings().crossServer) { + assert plugin.getNetworkMessenger() != null; + + // Find the matching networked target + return plugin.getNetworkMessenger().findPlayer(requester, targetUser).thenApply(networkedTarget -> { + if (networkedTarget.isEmpty()) { + return false; + } + + // Use the network messenger to send the request + request.recipientName = networkedTarget.get(); + 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(message -> { + if (message.payload.teleportRequest == null) { + return false; + } + + // If the message was ignored by the recipient, return false + return message.payload.teleportRequest.status == TeleportRequest.RequestStatus.PENDING; + }) + .orTimeout(3, TimeUnit.SECONDS) + .exceptionally(throwable -> false).join(); + }); + } + return CompletableFuture.supplyAsync(() -> false); + } + + /** + * Sends a teleport request locally on this server asking the recipient to accept or deny the request. + * + * @param request The {@link TeleportRequest} to send + * @param recipient The online recipient of the request + * @return {@code true} if the request was sent, {@code false} if it was not sent because the recipient is ignoring requests + */ + public boolean sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) { + if (ignoringRequests.contains(recipient.uuid)) { + request.status = TeleportRequest.RequestStatus.IGNORED; + return false; + } + + // Add the request and display a message to the recipient + addTeleportRequest(request, recipient); + plugin.getLocales().getLocale((request.type == TeleportRequest.RequestType.TPA ? "tpa" : "tpahere") + + "_request_received", request.requester.username) + .ifPresent(recipient::sendMessage); + plugin.getLocales().getLocale("teleport_request_buttons", request.requester.username) + .ifPresent(recipient::sendMessage); + return true; + } + + public void respondToTeleportRequestBySenderName(@NotNull OnlineUser recipient, @NotNull String senderName, + boolean accepted) { + // Check the recipient is not ignoring teleport requests + if (ignoringRequests.contains(recipient.uuid)) { + plugin.getLocales().getLocale("error_ignoring_teleport_requests").ifPresent(recipient::sendMessage); + return; + } + + // Get the sender-named request and handle the response + final Optional namedRequest = getTeleportRequest(senderName, recipient); + if (namedRequest.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_teleport_request", senderName) + .ifPresent(recipient::sendMessage); + return; + } + handleRequestResponse(namedRequest.get(), recipient, accepted); + } + + public void respondToTeleportRequest(@NotNull OnlineUser recipient, boolean accepted) { + // Check the recipient is not ignoring teleport requests + if (ignoringRequests.contains(recipient.uuid)) { + plugin.getLocales().getLocale("error_ignoring_teleport_requests").ifPresent(recipient::sendMessage); + return; + } + + // Get the latest request and handle the response + final Optional lastRequest = getLastTeleportRequest(recipient); + if (lastRequest.isEmpty()) { + plugin.getLocales().getLocale("error_no_teleport_requests").ifPresent(recipient::sendMessage); + return; + } + handleRequestResponse(lastRequest.get(), recipient, accepted); + } + + private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient, + boolean accepted) { + removeTeleportRequest(request, recipient); + + // Check if the request has expired + if (request.hasExpired()) { + plugin.getLocales().getLocale("error_teleport_request_expired").ifPresent(recipient::sendMessage); + return; + } + + // Send request response confirmation to the recipient + plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined") + "_confirmation", + request.requester.username) + .ifPresent(recipient::sendMessage); + request.status = accepted ? TeleportRequest.RequestStatus.ACCEPTED : TeleportRequest.RequestStatus.DECLINED; + + // Send request response to the sender + CompletableFuture.runAsync(() -> { + final Optional localSender = plugin.findPlayer(request.requester.username); + if (localSender.isPresent()) { + handleLocalRequestResponse(localSender.get(), request); + } else if (plugin.getSettings().crossServer) { + assert plugin.getNetworkMessenger() != null; + // Ensure the sender is still online + if (!plugin.getNetworkMessenger().findPlayer(recipient, request.requester.username).thenApply(networkedTarget -> { + if (networkedTarget.isEmpty()) { + plugin.getLocales().getLocale("error_teleport_request_sender_not_online") + .ifPresent(recipient::sendMessage); + 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(); + }).join()) { + plugin.getLocales().getLocale("error_teleport_request_sender_not_online") + .ifPresent(recipient::sendMessage); + return; + } + } else { + plugin.getLocales().getLocale("error_teleport_request_sender_not_online") + .ifPresent(recipient::sendMessage); + return; + } + + // If the request is a tpa here request, teleport the recipient to the sender + if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) { + // Strict /tpahere requests will teleport to where the sender was when typing the command + if (plugin.getSettings().strictTpaHereRequests) { + plugin.getTeleportManager().teleport(recipient, request.requesterPosition); + } else { + plugin.getTeleportManager().teleportToPlayerByName(recipient, request.requester.username); + } + } + }); + } + + public void handleLocalRequestResponse(@NotNull OnlineUser requester, @NotNull TeleportRequest request) { + boolean accepted = request.status == TeleportRequest.RequestStatus.ACCEPTED; + plugin.getLocales().getLocale("teleport_request_" + (accepted ? "accepted" : "declined"), + request.recipientName).ifPresent(requester::sendMessage); + + // If the request is a tpa request, teleport the sender to the recipient + if (accepted && (request.type == TeleportRequest.RequestType.TPA)) { + plugin.getTeleportManager().teleportToPlayerByName(requester, request.recipientName); + } + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java new file mode 100644 index 00000000..1e159967 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/request/TeleportRequest.java @@ -0,0 +1,87 @@ +package net.william278.huskhomes.request; + +import com.google.gson.annotations.SerializedName; +import net.william278.huskhomes.player.OnlineUser; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.Position; +import org.jetbrains.annotations.NotNull; + +import java.time.Instant; + +/** + * Represents a request between players for one user to teleport to another, or vice versa + */ +public class TeleportRequest { + + /** + * The user making the request + */ + protected User requester; + + /** + * The position of the requester, relevant in the case of a {@link RequestType#TPA_HERE} request + */ + @SerializedName("requester_position") + protected Position requesterPosition; + + /** + * Epoch timestamp when the request will expire + */ + @SerializedName("expiry_time") + protected long expiryTime; + + /** + * The type of request; a {@link RequestType#TPA} or {@link RequestType#TPA_HERE} + */ + protected RequestType type; + + /** + * The status of the request; a {@link RequestStatus#PENDING}, {@link RequestStatus#ACCEPTED} + * or {@link RequestStatus#DECLINED} + */ + protected RequestStatus status; + + /** + * The name of the request recipient + */ + protected String recipientName; + + /** + * Create a teleport request + * + * @param requester The user making the request + */ + protected TeleportRequest(@NotNull OnlineUser requester, @NotNull RequestType requestType, + final long expiryTime) { + this.requester = requester; + this.requesterPosition = requester.getPosition().join(); + this.type = requestType; + this.status = RequestStatus.PENDING; + this.expiryTime = expiryTime; + } + + private TeleportRequest() { + } + + /** + * Returns if the request has now expired + * + * @return {@code true} the request has passed its expiry time + */ + public boolean hasExpired() { + return Instant.now().isAfter(Instant.ofEpochSecond(expiryTime)); + } + + public enum RequestType { + TPA, + TPA_HERE + } + + protected enum RequestStatus { + PENDING, + ACCEPTED, + DECLINED, + IGNORED + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java index c2bcf31f..05d6aaaf 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -136,7 +136,7 @@ public class TeleportManager { if (plugin.getSettings().crossServer) { assert plugin.getNetworkMessenger() != null; return plugin.getNetworkMessenger().sendMessage(requester, - new Message(Message.MessageType.TP_TO_POSITION_REQUEST, + new Message(Message.MessageType.TELEPORT_TO_POSITION_REQUEST, requester.username, playerName, MessagePayload.withPosition(position), diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index c98a37f1..cc7214ad 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -69,21 +69,23 @@ home_deleted: '[Successfully deleted your home,](#00fb9a) [%1%](#00fb9a bold)' home_deleted_other: '[Successfully deleted %1%''s home,](#00fb9a) [%2%](#00fb9a bold)' warp_deleted: '[Successfully deleted the warp,](#00fb9a) [%1%](#00fb9a bold)' +tpa_request_sent: '[You sent a teleport request asking to teleport to](#00fb9a) [%1%](#00fb9a bold)[.](#00fb9a)' +tpahere_request_sent: '[You sent a teleport request asking](#00fb9a) [%1%](#00fb9a bold) [to teleport to you.](#00fb9a)' +tpaall_request_sent: '[You sent a teleport request asking everyone to teleport to you.](#00fb9a)' +tpa_request_received: '[%1%](#00fb9a bold) [has requested to teleport to you.](#00fb9a)' +tpahere_request_received: '[%1%](#00fb9a bold) [has requested that you teleport to them.](#00fb9a)' +teleport_request_buttons: '[Options:](gray) [[✔ Accept…]](#00fb9a show_text=�fb9a&Accept teleport request\n&8Click to accept %1%''s request run_command=/tpaccept %1%) [[❌ Decline…]](#ff3300 show_text=&#ff3300&Decline teleport request\n&8Click to decline %1%''s request run_command=/tpdeny %1%)' +teleport_request_accepted_confirmation: '[You accepted %1%''s teleport request!](#00fb9a)' +teleport_request_declined_confirmation: '[You declined %1%''s teleport request.](#ff7e5e)' +teleport_request_accepted: '[%1% has accepted your teleport request!](#00fb9a)' +teleport_request_declined: '[%1% has declined your teleport request.](#ff7e5e)' + set_home_spent_money: '[Successfully spent %1% to set an additional home!](gray)' set_home_used_free_slots: '[You''ve used all of your free set home slots (%1%); setting additional homes will cost %2% each.](gray)' set_home_success: '[Successfully set a new home called](#00fb9a) [%1%](#00fb9a bold)' set_warp_success: '[Successfully set a new warp called](#00fb9a) [%1%](#00fb9a bold)' set_spawn_success: '[Updated spawn position for this server to your current location.](#00fb9a)' return_by_death: '[Return to where you died?](gray) [/back](#00fb9a show_text=�fb9a&Click to return to where you died run_command=/back)' -teleport_request_options: '[Click an option:](gray) [[Accept]](#00fb9a show_text=�fb9a&Accept the teleport request; /tpaccept %1% run_command=/tpaccept %1%) [•](gray) [[Decline]](#ff7e5e show_text=&#ff7e5e&Decline the teleport request; /tpdeny %1% run_command=/tpdeny %1%)' -tpa_you_accepted: '[You accepted %1%''s teleport request](#00fb9a)' -tpa_you_declined: '[You declined %1%''s teleport request](#ff7e5e)' -tpa_has_accepted: '[%1% accepted your teleport request](#00fb9a)' -tpa_has_declined: '[%1% declined your teleport request](#ff7e5e)' -tpa_request_sent: '[You sent a teleport request to teleport to](#00fb9a) [%1%](#00fb9a bold)' -tpa_request_ask: '[%1%](#00fb9a bold) [has requested to teleport to you](#00fb9a)' -tpahere_request_sent: '[You sent a teleport request asking](#00fb9a) [%1%](#00fb9a bold) [to teleport to you](#00fb9a)' -tpahere_request_ask: '[%1%](#00fb9a bold) [has requested that you teleport to them](#00fb9a)' rtp_spent_money: '[Spent %1% to randomly teleport.](gray)' back_spent_money: '[Spent %1% to return to your last position.](gray)' home_default_description: '%1%''s home' @@ -97,7 +99,6 @@ spawn_warp_default_description: 'The /spawn position of the server' tpignore_toggle_on: '[You are now](#00fb9a) [ignoring](#00fb9a bold) [incoming teleport requests.](#00fb9a) [(Click to toggle)](gray show_text=&7Click to listen for incoming teleport requests run_command=/huskhomes:tpignore)' tpignore_toggle_off: '[You are now](#00fb9a) [listening](#00fb9a bold) [to any incoming teleport requests.](#00fb9a) [(Click to toggle)](gray show_text=&7Click to ignore incoming teleport requests run_command=/huskhomes:tpignore)' tpignore_on_reminder: '[You are currently ignoring incoming teleport requests!](gray) [(Click to toggle)](gray show_text=&7Click to listen for incoming teleport requests run_command=/huskhomes:tpignore)' -tpaall_request_sent: '[You sent a teleport request asking everyone to teleport to you!](#00fb9a)' teleporting_all_players: '[Teleporting all players to your position…](#00fb9a)' error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)' @@ -130,8 +131,11 @@ error_public_home_invalid: '[Error:](#ff3300) [Could not find a public home owne error_set_home_maximum_homes: '[Error:](#ff3300) [You can only set a maximum of %1% homes!](#ff7e5e)' error_insufficient_funds: '[Error:](#ff3300) [You do not have enough money! (Cost: %1%)](#ff7e5e)' error_spawn_undefined: '[Error:](#ff3300) [There is no spawn position defined on this server.](#ff7e5e)' -error_tpa_no_pending_request: '[Error:](#ff3300) [You do not have a pending teleport request.](#ff7e5e)' -error_tpa_request_expired: '[Error:](#ff3300) [Your pending teleport request has expired.](#ff7e5e)' +error_no_teleport_requests: '[Error:](#ff3300) [You do not have a pending teleport request.](#ff7e5e)' +error_teleport_request_expired: '[Error:](#ff3300) [Your pending teleport request has expired.](#ff7e5e)' +error_teleport_request_sender_not_online: '[Error:](#ff3300) [The sender of your pending teleport request is no longer online.](#ff7e5e)' +error_ignoring_teleport_requests: '[Error:](#ff3300) [You are currently ignoring teleport requests.](#ff7e5e) [[Stop Ignoring…]](#ff7e5e show_text=&#ff7e5e&Click to listen for incoming teleport requests run_command=/huskhomes:tpignore)' +error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending request from %1%.](#ff7e5e)' error_player_not_found: '[Error:](#ff3300) [Could not find the player %1%.](#ff7e5e)' error_tp_self: '[Error:](#ff3300) [You cannot teleport to yourself!](#ff7e5e)' error_rtp_invalid_dimension: '[Error:](#ff3300) [You can only randomly teleport in the overworld!](#ff7e5e)' @@ -143,7 +147,6 @@ error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe rando error_permission_restricted_warp: '[Error:](#ff3300) [You do not have permission to warp to %1%!](#ff7e5e)' error_invalid_page_number: '[Error:](#ff3300) [Please specify a valid page number.](#ff7e5e)' error_invalid_on_arrival: '[Error:](#ff3300) [Failed to finish teleportation as the target world could not be found.](#ff7e5e)' -error_ignoring_teleport_requests: '[Error:](#ff3300) [You are currently ignoring teleport requests!](#ff7e5e) [(Click to toggle)](#ff7e5e show_text=&#ff7e5e&Click to listen for incoming teleport requests run_command=/huskhomes:tpignore)' error_no_offline_position: '[Error:](#ff3300) [Could not find where %1% last logged out.](#ff7e5e)' error_invalid_player: '[Error:](#ff3300) [Please specify the name of a valid player!](#ff7e5e)' error_no_homes_set_other: '[Error:](#ff3300) [%1% has not set any homes!](#ff7e5e)'