feat: Improve /rtp with world+server args, fix x-server /rtp (#719)

* feat: enhance /rtp command with flexible world and server options, and fix cross-server compatibility

* I'm not sure about the permission.

* Revert "I'm not sure about the permission."

This reverts commit c11942d0187690bf46dbcd21f2f6242f929f928b.

* revert accident reformat.

* change from review request
This commit is contained in:
Sinon authored and GitHub committed 2024-11-12 20:32:52 +00:00
1 parent 419f1e2f08
commit 3705b3288d
5 files changed
+136 -56

No files matched your search

@@ -810,7 +810,7 @@ public class BaseHuskHomesAPI {
@NotNull String... rtpArgs) { @NotNull String... rtpArgs) {
if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled() && if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled() &&
plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) { plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) {
List<String> allowedServers = plugin.getSettings().getRtp().getRandomTargetServers(); List<String> allowedServers = new ArrayList<>(plugin.getSettings().getRtp().getRandomTargetServers().keySet());
String randomServer = allowedServers.get(random.nextInt(allowedServers.size())); String randomServer = allowedServers.get(random.nextInt(allowedServers.size()));
if (randomServer.equals(plugin.getServerName())) { if (randomServer.equals(plugin.getServerName())) {
randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs); randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs);
@@ -32,10 +32,7 @@ import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.*;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
public class RtpCommand extends Command implements UserListTabCompletable { public class RtpCommand extends Command implements UserListTabCompletable {
@@ -44,7 +41,7 @@ public class RtpCommand extends Command implements UserListTabCompletable {
protected RtpCommand(@NotNull HuskHomes plugin) { protected RtpCommand(@NotNull HuskHomes plugin) {
super( super(
List.of("rtp"), List.of("rtp"),
"[player] [world]", "[player] [<world> [server]|<world>]",
plugin plugin
); );
@@ -69,10 +66,29 @@ public class RtpCommand extends Command implements UserListTabCompletable {
return; return;
} }
// Validate, then execute the RTP
final OnlineUser teleporter = optionalTeleporter.get(); final OnlineUser teleporter = optionalTeleporter.get();
this.validateRtp(teleporter, executor, args.length > 1 ? removeFirstArg(args) : args)
.ifPresent(world -> this.executeRtp(teleporter, executor, world, args)); // Determine the target world and server based on the command arguments
String worldName = teleporter.getPosition().getWorld().getName();
String targetServer = null;
if (args.length == 2) {
// If there's only one argument after the player name, it could be either a world or a server
if (plugin.getSettings().getRtp().getRandomTargetServers().containsKey(args[1])) {
targetServer = args[1];
worldName = teleporter.getPosition().getWorld().getName();
} else {
worldName = args[1];
}
} else if (args.length > 2) {
// If two arguments are provided after the player name, treat them as world and server
worldName = args[1];
targetServer = args[2];
}
// Validate world and server, and execute RTP
Optional<Map.Entry<World, String>> validatedTarget = validateRtp(teleporter, executor, worldName, targetServer);
validatedTarget.ifPresent(entry -> executeRtp(teleporter, executor, entry.getKey(), entry.getValue(), args));
} }
@Nullable @Nullable
@@ -82,24 +98,72 @@ public class RtpCommand extends Command implements UserListTabCompletable {
case 0, 1 -> user.hasPermission(getPermission("other")) case 0, 1 -> user.hasPermission(getPermission("other"))
? UserListTabCompletable.super.suggest(user, args) ? UserListTabCompletable.super.suggest(user, args)
: user instanceof OnlineUser online ? List.of(online.getName()) : List.of(); : user instanceof OnlineUser online ? List.of(online.getName()) : List.of();
case 2 -> plugin.getWorlds().stream()
.filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world)) case 2 -> {
.map(World::getName) String input = args[1].toLowerCase();
.filter(world -> user.hasPermission(getPermission(world))).toList();
// Check if the input could be a world or a server name
List<String> possibleSuggestions = new ArrayList<>();
// Suggest available servers if user has permission
possibleSuggestions.addAll(plugin.getSettings().getRtp().getRandomTargetServers().keySet().stream()
.filter(server -> user.hasPermission(getPermission(server)))
.toList());
// Additionally suggest worlds that the user has permission to RTP into
possibleSuggestions.addAll(plugin.getWorlds().stream()
.filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world))
.map(World::getName)
.filter(world -> user.hasPermission(getPermission(world)))
.toList());
if (!input.isEmpty()) {
yield possibleSuggestions.stream()
.filter(suggestion -> suggestion.toLowerCase().startsWith(input))
.toList();
}
yield possibleSuggestions;
}
case 3 -> {
// If worldName is a world, suggest servers that contain the world
String worldName = args[1];
List<String> possibleSuggestions = new ArrayList<>(plugin.getWorlds().stream()
.filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world))
.map(World::getName)
.filter(world -> user.hasPermission(getPermission(world)))
.toList());
if (possibleSuggestions.contains(worldName)) {
yield plugin.getSettings().getRtp().getRandomTargetServers().entrySet().stream()
.filter(entry -> entry.getValue().contains(worldName))
.map(Map.Entry::getKey)
.toList();
}
yield List.of();
}
default -> null; default -> null;
}; };
} }
/** /**
* Validates the RTP command, returning the world to randomly teleport in if successful. * Validates the RTP target world and server based on arguments, ensuring the server contains the target world.
* - If no server is specified, randomly selects a server containing the world.
* - Returns both the validated world and server as a pair.
* *
* @param teleporter The user to teleport * @param teleporter The player to teleport
* @param executor The user executing the command * @param executor The player executing the command
* @param args The command arguments * @param worldName The world name to teleport to
* @return The world to randomly teleport in, if successful * @param targetServer The server name to teleport to (optional)
* @return A pair of the target world and server to use for teleportation, if valid
*/ */
private Optional<World> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, private Optional<Map.Entry<World, String>> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor,
@NotNull String[] args) { @NotNull String worldName, @Nullable String targetServer) {
// Check permissions if the user is being teleported by another player // Check permissions if the user is being teleported by another player
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) { if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
@@ -112,58 +176,59 @@ public class RtpCommand extends Command implements UserListTabCompletable {
return Optional.empty(); return Optional.empty();
} }
// Determine the world to carry out the RTP in Map<String, List<String>> randomTargetServers = plugin.getSettings().getRtp().getRandomTargetServers();
final World teleporterWorld = teleporter.getPosition().getWorld();
final Optional<World> optionalWorld = args.length >= 1 ? plugin.getWorlds().stream().filter(w -> w.getName() // Get a list of servers that have the specified world
.equalsIgnoreCase(args[0])).findFirst() : Optional.of(teleporterWorld); List<String> eligibleServers = randomTargetServers.entrySet().stream()
if (optionalWorld.isEmpty()) { .filter(entry -> entry.getValue().contains(worldName))
plugin.getLocales().getLocale("error_invalid_world", args[0]) .map(Map.Entry::getKey)
.toList();
// If targetServer is specified, validate it; otherwise, pick a random eligible server
String selectedServer = targetServer != null ? targetServer :
(!eligibleServers.isEmpty() ? eligibleServers.get(random.nextInt(eligibleServers.size())) : null);
// If no server found or the specified server is invalid, return an error
if (selectedServer == null || (targetServer != null && !eligibleServers.contains(targetServer))) {
plugin.getLocales().getLocale("error_invalid_world", worldName)
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return Optional.empty(); return Optional.empty();
} }
// Ensure the user has permission to randomly teleport in the world Optional<World> targetWorld = plugin.getWorlds().stream()
final World world = optionalWorld.get(); .filter(world -> world.getName().equalsIgnoreCase(worldName))
if (!world.equals(teleporterWorld) && !executor.hasPermission(getPermission(world.getName()))) { .findFirst()
plugin.getLocales().getLocale("error_no_permission") .or(() -> Optional.of(World.from(worldName, UUID.randomUUID())));
.ifPresent(executor::sendMessage);
return Optional.empty();
}
if (plugin.getSettings().getRtp().isWorldRtpRestricted(world)) {
plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(executor::sendMessage);
return Optional.empty();
}
return Optional.of(world); return targetWorld.map(world -> new AbstractMap.SimpleEntry<>(world, selectedServer));
} }
/** /**
* Executes the random teleport. * Executes the RTP, handling both local and cross-server teleportation.
* Uses the validated world-server pair from validateRtp.
* *
* @param teleporter The player to teleport * @param teleporter The player to teleport
* @param executor The player executing the command * @param executor The player executing the command
* @param world The world to teleport in * @param world The validated world to teleport to
* @param targetServer The validated server to teleport to
* @param args Arguments to pass to the RTP engine * @param args Arguments to pass to the RTP engine
*/ */
private void executeRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull World world, private void executeRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor,
@NotNull String[] args) { @NotNull World world, @NotNull String targetServer, @NotNull String[] args) {
// Generate a random position // Generate a random position
plugin.getLocales().getLocale("teleporting_random_generation") plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(teleporter::sendMessage); .ifPresent(teleporter::sendMessage);
if (plugin.getSettings().getRtp().isCrossServer() && plugin.getSettings().getCrossServer().isEnabled() if (plugin.getSettings().getRtp().isCrossServer() && plugin.getSettings().getCrossServer().isEnabled()
&& plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) { && plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
List<String> allowedServers = plugin.getSettings().getRtp().getRandomTargetServers(); if (targetServer.equals(plugin.getServerName())) {
String randomServer = allowedServers.get(random.nextInt(allowedServers.size()));
if (randomServer.equals(plugin.getServerName())) {
performLocalRTP(teleporter, executor, world, args); performLocalRTP(teleporter, executor, world, args);
return; return;
} }
plugin.getBroker().ifPresent(b -> Message.builder() plugin.getBroker().ifPresent(b -> Message.builder()
.type(Message.MessageType.REQUEST_RTP_LOCATION) .type(Message.MessageType.REQUEST_RTP_LOCATION)
.target(randomServer, Message.TargetType.SERVER) .target(targetServer, Message.TargetType.SERVER)
.payload(Payload.string(world.getName())) .payload(Payload.string(world.getName()))
.build().send(b, teleporter)); .build().send(b, teleporter));
return; return;
@@ -346,7 +346,9 @@ public final class Settings {
@Comment({"List of server in which /rtp is allowed. (Only relevant when using cross server mode WITH REDIS)", @Comment({"List of server in which /rtp is allowed. (Only relevant when using cross server mode WITH REDIS)",
"If a server is not defined here the RTP logic has no way of knowing its existence."}) "If a server is not defined here the RTP logic has no way of knowing its existence."})
private List<String> randomTargetServers = List.of("server-01", "server-02"); private Map<String, List<String>> randomTargetServers = new HashMap<>(
Map.of("survival_server", List.of("world", "world_nether", "world_the_end"))
);
} }
@Comment("Action cooldown settings. Docs: https://william278.net/docs/huskhomes/cooldowns") @Comment("Action cooldown settings. Docs: https://william278.net/docs/huskhomes/cooldowns")
@@ -130,6 +130,7 @@ public interface MessageHandler {
.orElse(CompletableFuture.completedFuture(Optional.empty())) .orElse(CompletableFuture.completedFuture(Optional.empty()))
.thenAccept( .thenAccept(
(teleport) -> Message.builder() (teleport) -> Message.builder()
.type(Message.MessageType.RTP_LOCATION)
.target(message.getSender(), Message.TargetType.PLAYER) .target(message.getSender(), Message.TargetType.PLAYER)
.payload(Payload.position(teleport.orElse(null))) .payload(Payload.position(teleport.orElse(null)))
.build().send(getBroker(), null) .build().send(getBroker(), null)
+17 -5
View File
@@ -322,21 +322,33 @@ This is a table of HuskHomes commands, how to use them, and their required permi
<!-- /rtp command --> <!-- /rtp command -->
<tr><th colspan="5">Random teleport command</th></tr> <tr><th colspan="5">Random teleport command</th></tr>
<tr> <tr>
<td rowspan="3"><code>/rtp</code></td> <td rowspan="5"><code>/rtp</code></td>
<td><code>/rtp</code></td> <td><code>/rtp</code></td>
<td>Teleport randomly into the wild</td> <td>Teleport randomly into the wild in the current world</td>
<td><code>huskhomes.command.rtp</code></td> <td><code>huskhomes.command.rtp</code></td>
<td align="center">✅</td> <td align="center">✅</td>
</tr> </tr>
<tr> <tr>
<td><code>/rtp &lt;player&gt;</code></td> <td><code>/rtp &lt;player&gt;</code></td>
<td>Teleport another user randomly into the wild</td> <td>Teleport another player randomly into the wild</td>
<td><code>huskhomes.command.rtp.other</code></td> <td><code>huskhomes.command.rtp.other</code></td>
<td align="center">❌</td> <td align="center">❌</td>
</tr> </tr>
<tr> <tr>
<td><code>/rtp &lt;player&gt; &lt;world&gt;</code></td> <td><code>/rtp &lt;world&gt;</code></td>
<td>Teleport randomly in a specific world</td> <td>Teleport randomly in a specified world</td>
<td><code>huskhomes.command.rtp.world</code></td>
<td align="center">❌</td>
</tr>
<tr>
<td><code>/rtp &lt;world&gt; &lt;server&gt;</code></td>
<td>Teleport randomly in a specified world on a specified server</td>
<td><code>huskhomes.command.rtp.world</code></td>
<td align="center">❌</td>
</tr>
<tr>
<td><code>/rtp &lt;server&gt;</code></td>
<td>Teleport randomly in the current world on a specified server</td>
<td><code>huskhomes.command.rtp.world</code></td> <td><code>huskhomes.command.rtp.world</code></td>
<td align="center">❌</td> <td align="center">❌</td>
</tr> </tr>