More command refactoring

This commit is contained in:
William278 committed 2023-03-20 00:01:09 +00:00
1 parent 3bde5305d7
commit 34eb2c1f54
17 files changed
+382 -540

No files matched your search

@@ -6,12 +6,14 @@ import net.william278.huskhomes.user.ConsoleUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public abstract class Command extends Node implements TabProvider {
private final String usage;
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) {
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, plugin);
this.usage = usage;
}
@@ -24,7 +26,7 @@ public abstract class Command extends Node implements TabProvider {
return;
}
if (executor instanceof ConsoleUser && !isConsoleExecutable()) {
plugin.getLocales().getLocale("error_command_in_game_only")
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
@@ -58,4 +60,9 @@ public abstract class Command extends Node implements TabProvider {
.orElse(getUsage());
}
@NotNull
public Map<String, Boolean> getAdditionalPermissions() {
return Map.of();
}
}
@@ -2,130 +2,101 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import org.apache.commons.lang3.ArrayUtils;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class RtpCommand extends Command implements ConsoleExecutable {
public class RtpCommand extends Command {
protected RtpCommand(@NotNull HuskHomes implementor) {
super("rtp", Permission.COMMAND_RTP, implementor);
protected RtpCommand(@NotNull HuskHomes plugin) {
super("rtp", List.of(), "[player]", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
OnlineUser target = onlineUser;
if (args.length >= 1) {
if (!onlineUser.hasPermission(Permission.COMMAND_RTP_OTHER.node)) {
plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage);
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
final Optional<OnlineUser> optionalTeleporter = args.length >= 1 ? plugin.findOnlinePlayer(args[0])
: executor instanceof OnlineUser ? Optional.of((OnlineUser) executor) : Optional.empty();
if (optionalTeleporter.isEmpty()) {
if (args.length == 0) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
final Optional<OnlineUser> foundUser = plugin.findOnlinePlayer(args[0]);
if (foundUser.isEmpty()) {
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(onlineUser::sendMessage);
return;
}
target = foundUser.get();
plugin.getLocales().getLocale("error_player_not_found", args[0])
.ifPresent(executor::sendMessage);
return;
}
final Position userPosition = target.getPosition();
final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args;
final OnlineUser teleporter = optionalTeleporter.get();
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
this.executeRtp(teleporter, executor, args);
}
private void executeRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull String[] args) {
if (!plugin.validateEconomyCheck(teleporter, EconomyHook.Action.RANDOM_TELEPORT)) {
return;
}
if (plugin.getSettings().getRtpRestrictedWorlds().stream()
.anyMatch(worldName -> worldName.equals(userPosition.getWorld().getName()))) {
.anyMatch(worldName -> worldName.equals(teleporter.getPosition().getWorld().getName()))) {
plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(onlineUser::sendMessage);
.ifPresent(executor::sendMessage);
return;
}
// Perform economy check if necessary
if (!plugin.validateEconomyCheck(onlineUser, EconomyHook.Action.RANDOM_TELEPORT)) {
final SavedUser user = plugin.getDatabase().getUserData(teleporter.getUuid())
.orElseThrow(() -> new IllegalStateException("No user data found for " + teleporter.getUsername()));
final Instant currentTime = Instant.now();
if (executor.equals(teleporter) && !currentTime.isAfter(user.getRtpCooldown()) &&
!executor.hasPermission(getPermission("bypass_cooldown"))) {
plugin.getLocales().getLocale("error_rtp_cooldown",
Long.toString(currentTime.until(user.getRtpCooldown(), ChronoUnit.MINUTES) + 1))
.ifPresent(executor::sendMessage);
return;
}
final OnlineUser userToTeleport = target;
final boolean isExecutorTeleporting = userToTeleport.equals(onlineUser);
plugin.getDatabase().getUserData(onlineUser.getUuid()).thenAccept(userData -> {
// Check the user is not still on /rtp cooldown
if (userData.isEmpty()) {
return;
}
final Instant currentTime = Instant.now();
if (isExecutorTeleporting && !currentTime.isAfter(userData.get().rtpCooldown())
&& !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getLocales().getLocale("error_rtp_cooldown",
Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES) + 1))
.ifPresent(onlineUser::sendMessage);
return;
plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(teleporter::sendMessage);
final Optional<Position> position = plugin.getRandomTeleportEngine()
.getRandomPosition(teleporter.getPosition().getWorld(), removeFirstArg(args));
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(executor::sendMessage);
return;
}
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(teleporter)
.target(position.get());
try {
if (executor.equals(teleporter)) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, plugin, args);
return;
}
// Get a random position and teleport
plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(onlineUser::sendMessage);
final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().getWorld(), rtpArguments);
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(onlineUser::sendMessage);
return;
}
final TeleportBuilder builder = Teleport.builder(plugin, userToTeleport)
.setTarget(position.get());
final CompletableFuture<? extends Teleport> teleportFuture = isExecutorTeleporting
? builder.setEconomyActions(EconomyHook.Action.RANDOM_TELEPORT).toTimedTeleport()
: builder.toTeleport();
teleportFuture.thenAccept(teleport -> teleport.execute()
.thenAccept(result -> {
if (isExecutorTeleporting &&
result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getDatabase().updateUserData(new SavedUser(onlineUser,
userData.get().homeSlots(), userData.get().ignoringTeleports(),
Instant.now().plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES)));
}
}));
});
user.setRtpCooldown(Instant.now().plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES));
plugin.getDatabase().updateUserData(user);
}
@Override
public void onConsoleExecute(@NotNull String[] args) {
if (args.length == 0) {
plugin.log(Level.WARNING, "Invalid syntax. Usage: rtp [player]");
return;
}
final Optional<OnlineUser> foundUser = plugin.findOnlinePlayer(args[0]);
if (foundUser.isEmpty()) {
plugin.log(Level.WARNING, "Player not found: " + args[0]);
return;
}
plugin.log(Level.INFO, "Finding a random position for " + foundUser.get().getUsername() + "...");
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
if (position.isEmpty()) {
plugin.log(Level.WARNING, "Failed to teleport " + foundUser.get().getUsername() + " to a random position; randomization timed out!");
return;
}
Teleport.builder(plugin, foundUser.get())
.setTarget(position.get())
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) {
plugin.log(Level.INFO, "Teleported " + foundUser.get().getUsername() + " to a random position.");
} else {
plugin.log(Level.WARNING, "Failed to teleport" + foundUser.get().getUsername() + " to a random position.");
}
}));
});
}
}
@@ -114,6 +114,12 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
.execute();
}
@Override
@NotNull
public Map<String, Boolean> getAdditionalPermissions() {
return Map.of(getOtherPermission(), true);
}
@Override
@NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
@@ -1,129 +1,48 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.Optional;
public class SetHomeCommand extends Command {
public class SetHomeCommand extends SetPositionCommand {
protected SetHomeCommand(@NotNull HuskHomes implementor) {
super("sethome", Permission.COMMAND_SET_HOME, implementor);
protected SetHomeCommand(@NotNull HuskHomes plugin) {
super("sethome", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
plugin.getDatabase().getHomes(onlineUser).thenAcceptAsync(homes -> {
switch (args.length) {
case 0 -> {
if (homes.isEmpty()) {
setHome(onlineUser, "home", homes);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
}
}
case 1 -> setHome(onlineUser, args[0], homes);
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
}
});
}
/**
* Attempts to set a home by given name for the {@link OnlineUser}.
* <p>
* A number of validation checks will take place before the home is set. If these checks fail, the home won't be set.
* <ul>
* <li>The user's currentHomes must not exceed the permissive maximum home limit</li>
* <li>If economy features are on and the user does not have enough home slots, they must have sufficient funds to buy another</li>
* <li>The home name must not already exist</li>
* <li>The home name must meet the length and character criteria</li>
* </ul>
*
* @param onlineUser The {@link OnlineUser} to set the home for
* @param homeName The name of the home to set
* @param currentHomes The current homes of the {@link OnlineUser}
*/
private void setHome(@NotNull OnlineUser onlineUser, @NotNull String homeName, @NotNull List<Home> currentHomes) {
// Check against maximum homes
final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().getMaxHomes(), plugin.getSettings().doStackPermissionLimits());
if (currentHomes.size() >= maxHomes) {
plugin.getLocales().getLocale("error_set_home_maximum_homes", Integer.toString(maxHomes))
.ifPresent(onlineUser::sendMessage);
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
if (executor instanceof OnlineUser user && args.length == 0 && createDefaultHome(user)) {
return;
}
super.execute(executor, args);
}
// Get their user data
plugin.getDatabase().getUserData(onlineUser.getUuid()).thenAccept(fetchedData -> {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<SavedUser> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().doEconomy()) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().doStackPermissionLimits());
if (fetchedData.isPresent()) {
final EconomyHook.Action action = EconomyHook.Action.ADDITIONAL_HOME_SLOT;
newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots()));
@Override
protected void execute(@NotNull OnlineUser setter, @NotNull String name) {
try {
plugin.getManager().homes().createHome(setter, name, setter.getPosition());
} catch (ValidationException e) {
e.dispatchHomeError(setter, false, plugin, name);
}
}
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded.get()) {
if (!plugin.validateEconomyCheck(onlineUser, action)) {
return;
}
userDataToUpdate.set(new SavedUser(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown()));
} else {
if (currentHomes.size() == freeHomes) {
plugin.getEconomyHook()
.flatMap(economyHook -> plugin.getSettings().getEconomyCost(action)
.map(economyHook::formatCurrency))
.flatMap(formatted -> plugin.getLocales().getLocale("set_home_used_free_slots",
Integer.toString(freeHomes), formatted))
.ifPresent(onlineUser::sendMessage);
}
}
}
}
// Set the home in the saved position manager
plugin.getManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition())
.thenAccept(setResult -> {
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded.get()) {
plugin.performEconomyTransaction(onlineUser, EconomyHook.Action.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate.get());
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case SUCCESS_OVERWRITTEN -> {
assert setResult.savedPosition().isPresent();
yield plugin.getLocales().getLocale("edit_home_update_location",
setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> plugin.getLocales().getLocale("error_home_description_characters");
}).ifPresent(onlineUser::sendMessage);
});
});
private boolean createDefaultHome(@NotNull OnlineUser user) {
final List<Home> homes = plugin.getDatabase().getHomes(user);
final Optional<String> name = homes.isEmpty() ? Optional.of("home") :
(homes.size() == 1 && plugin.getSettings().doOverwriteExistingHomesWarps())
? Optional.of(homes.get(0).getName()) : Optional.empty();
if (name.isPresent()) {
this.execute(user, "home");
return true;
}
return false;
}
}
@@ -0,0 +1,36 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public abstract class SetPositionCommand extends Command {
protected SetPositionCommand(@NotNull String name, @NotNull HuskHomes plugin) {
super(name, List.of(), "<name>", plugin);
}
@Override
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
final Optional<String> name = parseStringArg(args, 0);
if (name.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(user::sendMessage);
return;
}
this.execute(user, name.get());
}
protected abstract void execute(@NotNull OnlineUser setter, @NotNull String name);
}
@@ -1,46 +1,45 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class SetSpawnCommand extends Command {
protected SetSpawnCommand(@NotNull HuskHomes implementor) {
super("setspawn", Permission.COMMAND_SET_SPAWN, implementor);
protected SetSpawnCommand(@NotNull HuskHomes plugin) {
super("setspawn", List.of(), "", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/setspawn")
.ifPresent(onlineUser::sendMessage);
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
final Position position = onlineUser.getPosition();
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalSpawn()) {
plugin.getDatabase().getWarp(plugin.getSettings().getGlobalSpawnName()).thenApply(warp -> {
if (warp.isPresent()) {
return plugin.getManager().updateWarpPosition(warp.get(), position);
} else {
return plugin.getManager().setWarp(new PositionMeta(plugin.getSettings().getGlobalSpawnName(),
plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position)
.thenApply(result -> result.resultType().successful);
}
}).thenAccept(result -> result.thenAccept(successful -> {
if (successful) {
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
}));
} else {
plugin.setServerSpawn(position);
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
final Position position = user.getPosition();
try {
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalSpawn()) {
final String warpName = plugin.getSettings().getGlobalSpawnName();
plugin.getManager().warps().createWarp(warpName, position, true);
plugin.getLocales().getRawLocale("spawn_warp_default_description")
.ifPresent(description -> plugin.getManager().warps().setWarpDescription(warpName, description));
} else {
plugin.setServerSpawn(position);
}
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, plugin.getSettings().getGlobalSpawnName());
return;
}
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(executor::sendMessage);
}
}
@@ -2,45 +2,21 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
public class SetWarpCommand extends Command {
public class SetWarpCommand extends SetPositionCommand {
protected SetWarpCommand(@NotNull HuskHomes implementor) {
super("setwarp", Permission.COMMAND_SET_WARP, implementor);
protected SetWarpCommand(@NotNull HuskHomes plugin) {
super("setwarp", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
setWarp(onlineUser, args[0]);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(onlineUser::sendMessage);
protected void execute(@NotNull OnlineUser setter, @NotNull String name) {
try {
plugin.getManager().warps().createWarp(name, setter.getPosition());
} catch (ValidationException e) {
e.dispatchWarpError(setter, plugin, name);
}
}
private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
plugin.getManager().setWarp(
new PositionMeta(warpName, ""), onlineUser.getPosition()).thenAccept(setResult ->
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
yield plugin.getLocales().getLocale("set_warp_success",
setResult.savedPosition().get().meta.name);
}
case SUCCESS_OVERWRITTEN -> {
assert setResult.savedPosition().isPresent();
yield plugin.getLocales().getLocale("edit_warp_update_location",
setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_warp_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_warp_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_warp_name_characters");
default -> plugin.getLocales().getLocale("error_warp_description_characters");
}).ifPresent(onlineUser::sendMessage));
}
}
@@ -1,38 +1,62 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public class SpawnCommand extends Command {
protected SpawnCommand(@NotNull HuskHomes implementor) {
super("spawn", Permission.COMMAND_SPAWN, implementor);
protected SpawnCommand(@NotNull HuskHomes plugin) {
super("spawn", List.of(), "[player]", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/spawn")
.ifPresent(onlineUser::sendMessage);
return;
}
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
final Optional<? extends Position> spawn = plugin.getSpawn();
if (spawn.isEmpty()) {
plugin.getLocales().getLocale("error_spawn_not_set")
.ifPresent(onlineUser::sendMessage);
.ifPresent(executor::sendMessage);
return;
}
Teleport.builder(plugin, onlineUser)
.setTarget(spawn.get())
.toTimedTeleport()
.thenAccept(TimedTeleport::execute);
final Optional<Teleportable> optionalTeleporter = resolveTeleportable(executor, args);
if (optionalTeleporter.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
this.teleportToSpawn(optionalTeleporter.get(), executor, spawn.get(), args);
}
public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor, @NotNull Position spawn,
@NotNull String[] args) {
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(teleporter)
.target(spawn);
try {
if (teleporter.equals(executor)) {
builder.toTimedTeleport().execute();
} else {
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, plugin, args);
}
}
}
@@ -1,55 +1,74 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class TpOfflineCommand extends Command implements TabProvider {
protected TpOfflineCommand(@NotNull HuskHomes implementor) {
super("tpoffline", Permission.COMMAND_TPOFFLINE, implementor);
protected TpOfflineCommand(@NotNull HuskHomes plugin) {
super("tpoffline", List.of(), "<player>", plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length != 1) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tpoffline <player>")
.ifPresent(onlineUser::sendMessage);
public void execute(@NotNull CommandUser executor, @NotNull String[] args) {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
final String targetUser = args[0];
plugin.getDatabase().getUserDataByName(targetUser).thenAccept(userData -> {
if (userData.isEmpty()) {
plugin.getLocales().getLocale("error_player_not_found", targetUser)
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getDatabase().getOfflinePosition(userData.get().user()).thenAccept(offlinePosition -> {
if (offlinePosition.isEmpty()) {
plugin.getLocales().getLocale("error_no_offline_position", targetUser)
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getLocales().getLocale("teleporting_offline_player", targetUser)
.ifPresent(onlineUser::sendMessage);
Teleport.builder(plugin, onlineUser)
.setTarget(offlinePosition.get())
.toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) {
plugin.getLocales().getLocale("teleporting_offline_complete", targetUser)
.ifPresent(onlineUser::sendMessage);
}
}));
});
});
final Optional<String> optionalUser = parseStringArg(args, 0);
if (optionalUser.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
final Optional<User> targetUserData = plugin.getDatabase()
.getUserDataByName(optionalUser.get())
.map(SavedUser::getUser);
if (targetUserData.isEmpty()) {
plugin.getLocales().getLocale("error_player_not_found", optionalUser.get())
.ifPresent(executor::sendMessage);
return;
}
this.teleportToOfflinePosition(user, targetUserData.get(), args);
}
private void teleportToOfflinePosition(@NotNull OnlineUser user, @NotNull User target, @NotNull String[] args) {
final Optional<Position> position = plugin.getDatabase().getOfflinePosition(target);
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_no_offline_position", target.getUsername())
.ifPresent(user::sendMessage);
return;
}
plugin.getLocales().getLocale("teleporting_offline_player", target.getUsername())
.ifPresent(user::sendMessage);
try {
Teleport.builder(plugin)
.teleporter(user)
.target(position.get())
.toTeleport().execute();
plugin.getLocales().getLocale("teleporting_offline_complete", target.getUsername())
.ifPresent(user::sendMessage);
} catch (TeleportationException e) {
e.displayMessage(user, plugin, args);
}
}
@Override
@@ -59,4 +78,5 @@ public class TpOfflineCommand extends Command implements TabProvider {
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
}