Add RequestManager, handle networked requests, new locales

This commit is contained in:
William committed 2022-08-18 22:08:21 +01:00
1 parent 6149ebe983
commit 11d05efcfa
13 files changed
+464 -43

No files matched your search

@@ -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;
@@ -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<OnlineUser> 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<OnlineUser> 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
*
@@ -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;
@@ -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
}
/**
@@ -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() {
}
@@ -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<String[]> 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<Optional<String>> 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
@@ -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;
@@ -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<UUID, List<TeleportRequest>> requests;
/**
* Set of users who are ignoring tpa requests
*/
private final Set<UUID> 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<TeleportRequest> getLastTeleportRequest(@NotNull User recipient) {
return this.requests.getOrDefault(recipient.uuid, Collections.emptyList()).stream().reduce((a, b) -> b);
}
public Optional<TeleportRequest> 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<Boolean> 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<OnlineUser> 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<TeleportRequest> 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<TeleportRequest> 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<OnlineUser> 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);
}
}
}
@@ -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
}
}
@@ -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),