edit home, warp commands, manager methods that accept warps/homes

This commit is contained in:
William committed 2023-03-14 12:51:31 +00:00
1 parent a72109667a
commit 4ad77a53c1
11 files changed
+299 -443

No files matched your search

@@ -8,7 +8,9 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
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) {
super(name, aliases, plugin);
this.usage = usage;
@@ -38,7 +40,7 @@ public abstract class Command extends Node implements TabProvider {
}
@NotNull
protected String[] removeFirstArg(String[] args) {
protected String[] removeFirstArg(@NotNull String[] args) {
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
return newArgs;
@@ -4,6 +4,7 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Home;
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;
@@ -29,7 +30,12 @@ public class DelHomeCommand extends SavedPositionCommand<Home> {
.ifPresent(user::sendMessage);
return;
}
plugin.getManager().homes().deleteHome(home.getOwner(), home.getName());
try {
plugin.getManager().homes().deleteHome(home);
} catch (ValidationException e) {
e.dispatchHomeError(executor, !home.getOwner().equals(executor), plugin, home.getName());
return;
}
plugin.getLocales().getLocale("home_deleted", home.getName())
.ifPresent(executor::sendMessage);
}
@@ -4,6 +4,7 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Warp;
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;
@@ -29,7 +30,12 @@ public class DelWarpCommand extends SavedPositionCommand<Warp> {
.ifPresent(user::sendMessage);
return;
}
plugin.getManager().warps().deleteWarp(warp.getName());
try {
plugin.getManager().warps().deleteWarp(warp);
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, warp.getName());
return;
}
plugin.getLocales().getLocale("warp_deleted", warp.getName())
.ifPresent(executor::sendMessage);
}
@@ -5,21 +5,17 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
public class EditHomeCommand extends SavedPositionCommand<Home> {
@@ -54,276 +50,143 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
}
switch (operation.get().toLowerCase()) {
case "rename" -> {
final Optional<String> newName = parseStringArg(args, 1);
if (newName.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " rename <name>")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().homes().renameHome(home.getOwner(), home.getName(), newName.get());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, newName.get());
return;
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_name", home.getName(), newName.get())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_name_other", home.getOwner().getUsername(),
home.getName(), newName.get())
.ifPresent(executor::sendMessage);
}
}
case "description" -> {
final Optional<String> newDescription = parseGreedyString(args, 1);
if (newDescription.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " description <text>")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().homes().updateHomeDescription(home.getOwner(), home.getName(), newDescription.get());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, newDescription.get());
return;
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_description", home.getName(), newDescription.get())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(),
home.getName(), newDescription.get())
.ifPresent(executor::sendMessage);
}
}
case "relocate" -> {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().homes().relocateHome(user, home.getName(), user.getPosition());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, home.getName());
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_location", home.getName())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName())
.ifPresent(executor::sendMessage);
}
}
case "privacy" -> {
}
case "rename" -> setHomeName(executor, home, ownerEditing, args);
case "description" -> setHomeDescription(executor, home, ownerEditing, args);
case "relocate" -> setHomePosition(executor, home, ownerEditing);
case "privacy" -> setHomePrivacy(executor, home, ownerEditing, args);
}
}
/**
* Perform the specified EditOperation on the specified home
*
* @param home The home to edit
* @param editor The player who is editing the home
* @param editOperation The edit operation to perform
* @param editArgs Arguments for the edit operation
*/
private void editHome(@NotNull Home home, @NotNull OnlineUser editor,
@Nullable String editOperation, @Nullable String editArgs) {
final AtomicBoolean showMenuFlag = new AtomicBoolean(false);
final boolean otherOwner = !editor.equals(home.getOwner());
if (editOperation == null) {
private void setHomeName(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
final Optional<String> newName = parseStringArg(args, 1);
if (newName.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " rename <name>")
.ifPresent(executor::sendMessage);
return;
}
if (editArgs != null) {
String argToCheck = editArgs;
if (editArgs.contains(Pattern.quote(" "))) {
argToCheck = editArgs.split(Pattern.quote(" "))[0];
}
if (argToCheck.equals("-m")) {
showMenuFlag.set(true);
editArgs = editArgs.replaceFirst("-m", "");
}
try {
plugin.getManager().homes().setHomeName(home, newName.get());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, newName.get());
return;
}
switch (editOperation.toLowerCase()) {
case "rename" -> {
if (editArgs == null || editArgs.contains(Pattern.quote(" "))) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> rename <new name>")
.ifPresent(editor::sendMessage);
return;
}
final String oldHomeName = home.getMeta().getName();
final String newHomeName = editArgs;
plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> {
if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_name",
oldHomeName, newHomeName);
} else {
yield plugin.getLocales().getLocale("edit_home_update_name_other",
home.getOwner().getUsername(), oldHomeName, newHomeName);
}
}
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(editor::sendMessage));
}
case "description" -> {
final String oldHomeDescription = home.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateHomeMeta(home, new PositionMeta(home.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> {
if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_description",
home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : newDescription);
} else {
yield plugin.getLocales().getLocale("edit_home_update_description_other",
home.getOwner().getUsername(),
home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : newDescription);
}
}
case FAILED_DESCRIPTION_LENGTH ->
plugin.getLocales().getLocale("error_home_description_length");
case FAILED_DESCRIPTION_CHARACTERS ->
plugin.getLocales().getLocale("error_home_description_characters");
default -> plugin.getLocales().getLocale("error_home_name_characters");
}).ifPresent(editor::sendMessage));
}
case "relocate" -> plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
home.getMeta().getName()).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other",
home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown("")));
}
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
});
case "privacy" -> {
if (!editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(editor::sendMessage);
return;
}
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic());
if (editArgs != null && !editArgs.isBlank()) {
if (editArgs.equalsIgnoreCase("private")) {
newIsPublic.set(false);
} else if (editArgs.equalsIgnoreCase("public")) {
newIsPublic.set(true);
} else {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> privacy [private|public]")
.ifPresent(editor::sendMessage);
return;
}
}
final String privacyKeyedString = newIsPublic.get() ? "public" : "private";
if (newIsPublic.get() == home.isPublic()) {
plugin.getLocales().getLocale(
"error_edit_home_privacy_already_" + privacyKeyedString)
.ifPresent(editor::sendMessage);
return;
}
// Get the homes of the editor
plugin.getDatabase().getHomes(editor).thenAccept(editorHomes -> {
// Perform checks if making the home public
if (newIsPublic.get() && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = editorHomes.stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(),
plugin.getSettings().doStackPermissionLimits());
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes))
.ifPresent(editor::sendMessage);
return;
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, EconomyHook.Action.MAKE_HOME_PUBLIC)) {
return;
}
}
// Execute the update
plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.getMeta().getName()).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown("")));
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, EconomyHook.Action.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
});
});
}
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]")
.ifPresent(editor::sendMessage);
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_name", home.getName(), newName.get())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_name_other", home.getOwner().getUsername(),
home.getName(), newName.get())
.ifPresent(executor::sendMessage);
}
}
@Nullable
private String getEditArguments(@NotNull String[] args) {
if (args.length > 2) {
final StringJoiner joiner = new StringJoiner(" ");
for (int i = 2; i < args.length; i++) {
joiner.add(args[i]);
}
return joiner.toString();
private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
final Optional<String> newDescription = parseGreedyString(args, 1);
if (newDescription.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " description <text>")
.ifPresent(executor::sendMessage);
return;
}
return null;
try {
plugin.getManager().homes().setHomeDescription(home, newDescription.get());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, newDescription.get());
return;
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_description", home.getName(), newDescription.get())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(),
home.getName(), newDescription.get())
.ifPresent(executor::sendMessage);
}
}
private void setHomePosition(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing) {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().homes().setHomePosition(home, user.getPosition());
} catch (ValidationException e) {
e.dispatchHomeError(executor, false, plugin, home.getName());
return;
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_location", home.getName())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName())
.ifPresent(executor::sendMessage);
}
}
private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
if (!executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
final Optional<String> privacyArg = parseStringArg(args, 1).map(String::toLowerCase);
if (privacyArg.isEmpty() || !(privacyArg.get().equals("public") || privacyArg.get().equals("private"))) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " privacy <public|private>")
.ifPresent(executor::sendMessage);
return;
}
// Check against economy
if (executor instanceof OnlineUser user && !plugin.validateEconomyCheck(user, EconomyHook.Action.MAKE_HOME_PUBLIC)) {
return;
}
try {
plugin.getManager().homes().setHomePrivacy(home, privacyArg.get().equals("public"));
} catch (ValidationException e) {
int maxHomes = executor instanceof OnlineUser user ?
user.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(),
plugin.getSettings().doStackPermissionLimits()) :
plugin.getSettings().getMaxPublicHomes();
e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes));
return;
}
// Perform transaction
if (executor instanceof OnlineUser user) {
plugin.performEconomyTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC);
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success",
home.getMeta().getName())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_privacy_" + privacyArg.get() + "_success_other",
home.getOwner().getUsername(), home.getMeta().getName())
.ifPresent(executor::sendMessage);
}
// Show the menu if the menu flag is set
parseStringArg(args, 2).ifPresent(arg -> {
if (arg.equalsIgnoreCase("-m")) {
getHomeEditorWindow(home, false, !ownerEditing,
ownerEditing || executor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(executor::sendMessage);
}
});
}
/**
@@ -337,8 +200,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
* @return List of {@link MineDown} messages to send to the editor that form the menu
*/
@NotNull
private List<MineDown> getHomeEditorWindow(@NotNull Home home, final boolean showTitle, final boolean otherViewer,
final boolean showTeleportButton, final boolean showPrivacyToggleButton) {
private List<MineDown> getHomeEditorWindow(@NotNull Home home, boolean showTitle, boolean otherViewer,
boolean showTeleportButton, boolean showPrivacyToggleButton) {
return new ArrayList<>() {{
if (showTitle) {
if (!otherViewer) {
@@ -361,7 +224,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
plugin.getLocales().getLocale("edit_home_menu_description",
home.getMeta().getDescription().length() > 50
? home.getMeta().getDescription().substring(0, 49).trim() + "…" : home.getMeta().getDescription(),
plugin.getLocales().wrapText(home.getMeta().getDescription()))
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))
.ifPresent(this::add);
}
@@ -369,7 +232,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer().getName())
plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer())
.ifPresent(this::add);
}
@@ -2,147 +2,107 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class EditWarpCommand extends Command implements TabProvider {
public class EditWarpCommand extends SavedPositionCommand<Warp> {
private final String[] EDIT_WARP_COMPLETIONS = {"rename", "description", "relocate"};
protected EditWarpCommand(@NotNull HuskHomes implementor) {
super("editwarp", Permission.COMMAND_EDIT_WARP, implementor);
public EditWarpCommand(@NotNull HuskHomes plugin) {
super("editwarp", List.of(), Warp.class, List.of("rename", "description", "relocate"), plugin);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length >= 1) {
final String warpName = args[0];
final String editOperation = args.length >= 2 ? args[1] : null;
final String editArgs = getEditArguments(args);
plugin.getDatabase().getWarp(warpName).thenAcceptAsync(optionalWarp -> {
if (optionalWarp.isEmpty()) {
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(onlineUser::sendMessage);
return;
}
editWarp(optionalWarp.get(), onlineUser, editOperation, editArgs);
});
} else {
plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp <name> [" + String.join("|", EDIT_WARP_COMPLETIONS) + "] [args]")
.ifPresent(onlineUser::sendMessage);
}
}
/**
* Perform the specified EditOperation on the specified warp
*
* @param warp The warp to edit
* @param editor The player who is editing the warp
* @param editOperation The edit operation to perform
* @param editArgs Arguments for the edit operation
*/
private void editWarp(@NotNull Warp warp, @NotNull OnlineUser editor,
@Nullable String editOperation, @Nullable String editArgs) {
final AtomicBoolean showMenuFlag = new AtomicBoolean(false);
if (editOperation == null) {
getWarpEditorWindow(warp, true, editor.hasPermission(Permission.COMMAND_WARP.node))
.forEach(editor::sendMessage);
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
final Optional<String> operation = parseStringArg(args, 0);
if (operation.isEmpty()) {
getWarpEditorWindow(warp, true, executor.hasPermission(Permission.COMMAND_WARP.node))
.forEach(executor::sendMessage);
return;
}
if (editArgs != null) {
String argToCheck = editArgs;
if (editArgs.contains(Pattern.quote(" "))) {
argToCheck = editArgs.split(Pattern.quote(" "))[0];
}
if (argToCheck.equals("-m")) {
showMenuFlag.set(true);
editArgs = editArgs.replaceFirst("-m", "");
}
if (!arguments.contains(operation.get().toLowerCase())) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp " + warp.getName() + " <" + String.join("|", arguments) + ">")
.ifPresent(executor::sendMessage);
return;
}
switch (editOperation.toLowerCase()) {
case "rename" -> {
if (editArgs == null || editArgs.contains(Pattern.quote(" "))) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp <name> rename <new name>")
.ifPresent(editor::sendMessage);
return;
}
final String oldWarpName = warp.getMeta().getName();
final String newWarpName = editArgs;
plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS ->
plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName);
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(editor::sendMessage));
}
case "description" -> {
final String oldWarpDescription = warp.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description",
warp.getMeta().getName(),
oldWarpDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldWarpDescription,
newDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : newDescription);
case FAILED_DESCRIPTION_LENGTH ->
plugin.getLocales().getLocale("error_warp_description_length");
case FAILED_DESCRIPTION_CHARACTERS ->
plugin.getLocales().getLocale("error_warp_description_characters");
default -> plugin.getLocales().getLocale("error_warp_name_characters");
}).ifPresent(editor::sendMessage));
}
case "relocate" ->
plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> {
editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location",
warp.getMeta().getName()).orElse(new MineDown("")));
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getWarpEditorWindow(warp, false, editor.hasPermission(Permission.COMMAND_WARP.node))
.forEach(editor::sendMessage);
}
});
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp <name> [" + String.join("|", EDIT_WARP_COMPLETIONS) + "] [args]")
.ifPresent(editor::sendMessage);
switch (operation.get().toLowerCase()) {
case "rename" -> setWarpName(executor, warp, args);
case "description" -> setWarpDescription(executor, warp, args);
case "relocate" -> setWarpPosition(executor, warp);
}
}
@Nullable
private String getEditArguments(@NotNull String[] args) {
if (args.length > 2) {
final StringJoiner joiner = new StringJoiner(" ");
for (int i = 2; i < args.length; i++) {
joiner.add(args[i]);
}
return joiner.toString();
private void setWarpName(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
final Optional<String> newName = parseStringArg(args, 1);
if (newName.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp " + warp.getName() + " rename <name>")
.ifPresent(executor::sendMessage);
return;
}
return null;
try {
plugin.getManager().warps().renameWarp(warp, newName.get());
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, newName.get());
return;
}
plugin.getLocales().getLocale("edit_warp_update_name", warp.getName(), newName.get())
.ifPresent(executor::sendMessage);
}
private void setWarpDescription(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
final Optional<String> newDescription = parseGreedyString(args, 1);
if (newDescription.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/editwarp " + warp.getName() + " description <text>")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().warps().setWarpDescription(warp, newDescription.get());
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, newDescription.get());
return;
}
plugin.getLocales().getLocale("edit_warp_update_description", warp.getName(), newDescription.get())
.ifPresent(executor::sendMessage);
}
private void setWarpPosition(@NotNull CommandUser executor, @NotNull Warp warp) {
if (!(executor instanceof OnlineUser user)) {
plugin.getLocales().getLocale("error_in_game_only")
.ifPresent(executor::sendMessage);
return;
}
try {
plugin.getManager().warps().relocateWarp(warp, user.getPosition());
} catch (ValidationException e) {
e.dispatchWarpError(executor, plugin, warp.getName());
return;
}
plugin.getLocales().getLocale("edit_warp_update_location", warp.getName())
.ifPresent(executor::sendMessage);
}
/**
* Get a formatted warp editor chat window for a supplied {@link Warp}
*
@@ -152,8 +112,7 @@ public class EditWarpCommand extends Command implements TabProvider {
* @return List of {@link MineDown} messages to send to the editor that form the menu
*/
@NotNull
private List<MineDown> getWarpEditorWindow(@NotNull Warp warp, final boolean showTitle,
final boolean showTeleportButton) {
private List<MineDown> getWarpEditorWindow(@NotNull Warp warp, boolean showTitle, boolean showTeleportButton) {
return new ArrayList<>() {{
if (showTitle) {
plugin.getLocales().getLocale("edit_warp_menu_title", warp.getMeta().getName())
@@ -171,14 +130,14 @@ public class EditWarpCommand extends Command implements TabProvider {
plugin.getLocales().getLocale("edit_warp_menu_description",
warp.getMeta().getDescription().length() > 50
? warp.getMeta().getDescription().substring(0, 49).trim() + "…" : warp.getMeta().getDescription(),
plugin.getLocales().wrapText(warp.getMeta().getDescription()))
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))
.ifPresent(this::add);
}
if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer().getName()).ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer()).ifPresent(this::add);
}
plugin.getLocales().getLocale("edit_warp_menu_coordinates",
@@ -197,20 +156,4 @@ public class EditWarpCommand extends Command implements TabProvider {
}};
}
@Override
@NotNull
public final List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
return switch (args.length) {
case 0, 1 -> plugin.getCache().getWarps()
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted()
.collect(Collectors.toList());
case 2 -> Arrays.stream(EDIT_WARP_COMPLETIONS)
.filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase()))
.sorted()
.collect(Collectors.toList());
default -> Collections.emptyList();
};
}
}
@@ -43,7 +43,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final Optional<?> position = (positionType == Home.class
? resolveHome(executor, name.get())
: resolveWarp(executor, name.get()));
position.ifPresent(p -> execute(executor, (T) p, args));
position.ifPresent(p -> execute(executor, (T) p, removeFirstArg(args)));
}
public abstract void execute(@NotNull CommandUser executor, @NotNull T position, @NotNull String[] arguments);
@@ -52,7 +52,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
if (homeName.contains(".")) {
final String[] splitHomeName = homeName.split("\\.");
final Optional<Home> optionalHome = plugin.getDatabase().getUserDataByName(splitHomeName[0])
.flatMap(owner -> plugin.getDatabase().getHome(owner.user(), splitHomeName[1]));
.flatMap(owner -> plugin.getDatabase().getHome(owner.getUser(), splitHomeName[1]));
if (optionalHome.isEmpty()) {
plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission())
@@ -470,8 +470,7 @@ public class MySqlDatabase extends Database {
resultSet.getTimestamp("timestamp").toInstant(),
resultSet.getString("tags")),
UUID.fromString(resultSet.getString("home_uuid")),
new User(UUID.fromString(resultSet.getString("owner_uuid")),
resultSet.getString("owner_username")),
user,
resultSet.getBoolean("public")));
}
}
@@ -629,9 +628,9 @@ public class MySqlDatabase extends Database {
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, savedUser.homeSlots());
statement.setBoolean(2, savedUser.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.rtpCooldown()));
statement.setInt(1, savedUser.getHomeSlots());
statement.setBoolean(2, savedUser.isIgnoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.getRtpCooldown()));
statement.setString(4, savedUser.getUserUuid().toString());
statement.executeUpdate();
}
@@ -466,8 +466,7 @@ public class SqLiteDatabase extends Database {
resultSet.getTimestamp("timestamp").toInstant(),
resultSet.getString("tags")),
UUID.fromString(resultSet.getString("home_uuid")),
new User(UUID.fromString(resultSet.getString("owner_uuid")),
resultSet.getString("owner_username")),
user,
resultSet.getBoolean("public")));
}
}
@@ -624,9 +623,9 @@ public class SqLiteDatabase extends Database {
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, savedUser.homeSlots());
statement.setBoolean(2, savedUser.ignoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.rtpCooldown()));
statement.setInt(1, savedUser.getHomeSlots());
statement.setBoolean(2, savedUser.isIgnoringTeleports());
statement.setTimestamp(3, Timestamp.from(savedUser.getRtpCooldown()));
statement.setString(4, savedUser.getUserUuid().toString());
statement.executeUpdate();
} catch (SQLException e) {
@@ -71,67 +71,84 @@ public class HomesManager {
if (home.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
plugin.getDatabase().deleteHome(home.get().getUuid());
this.deleteHome(home.get());
}
public void deleteHome(@NotNull Home home) {
plugin.getDatabase().deleteHome(home.getUuid());
}
public int deleteAllHomes(@NotNull User owner) {
return plugin.getDatabase().deleteAllHomes(owner);
}
public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
public void setHomePosition(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Home home = optionalHome.get();
this.setHomePosition(optionalHome.get(), position);
}
public void setHomePosition(@NotNull Home home, @NotNull Position position) throws ValidationException {
home.update(position);
plugin.getDatabase().saveHome(home);
}
public void renameHome(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException {
public void setHomeName(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
this.setHomeName(optionalHome.get(), newName);
}
public void setHomeName(@NotNull Home home, @NotNull String newName) throws ValidationException {
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Home home = optionalHome.get();
home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home);
}
public void updateHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException {
public void setHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
this.setHomeDescription(optionalHome.get(), description);
}
public void setHomeDescription(@NotNull Home home, @NotNull String description) {
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID);
}
final Home home = optionalHome.get();
home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home);
}
public void updateHomePrivacy(@NotNull User owner, @NotNull String name, boolean isPublic) throws ValidationException {
public void setHomePrivacy(@NotNull User owner, @NotNull String name, boolean isPublic) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Home home = optionalHome.get();
this.setHomePrivacy(optionalHome.get(), isPublic);
}
public void setHomePrivacy(@NotNull Home home, boolean isPublic) {
if (isPublic == home.isPublic()) {
return;
}
if (isPublic && owner instanceof OnlineUser online) {
final int publicHomes = plugin.getDatabase().getHomes(owner).stream()
if (isPublic && home.getOwner() instanceof OnlineUser online) {
final int publicHomes = plugin.getDatabase().getHomes(home.getOwner()).stream()
.filter(Home::isPublic)
.toList().size();
final int publicSlots = online.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(),
@@ -16,7 +16,7 @@ public class WarpsManager {
this.plugin = plugin;
}
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) {
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException {
final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name);
if (existingWarp.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
@@ -41,51 +41,69 @@ public class WarpsManager {
plugin.getDatabase().saveWarp(warp);
}
public void deleteWarp(@NotNull String name) {
public void deleteWarp(@NotNull String name) throws ValidationException {
final Optional<Warp> warp = plugin.getDatabase().getWarp(name);
if (warp.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
plugin.getDatabase().deleteWarp(warp.get().getUuid());
this.deleteWarp(warp.get());
}
public void deleteWarp(@NotNull Warp warp) {
plugin.getDatabase().deleteWarp(warp.getUuid());
}
public int deleteAllWarps() {
return plugin.getDatabase().deleteAllWarps();
}
public void relocateWarp(@NotNull String name, @NotNull Position position) {
public void relocateWarp(@NotNull String name, @NotNull Position position) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Warp warp = optionalWarp.get();
this.relocateWarp(optionalWarp.get(), position);
}
public void relocateWarp(@NotNull Warp warp, @NotNull Position position) {
warp.update(position);
plugin.getDatabase().saveWarp(warp);
}
public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException {
public void renameWarp(@NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
this.renameWarp(optionalWarp.get(), newName);
}
public void renameWarp(@NotNull Warp warp, @NotNull String newName) throws ValidationException {
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
final Warp warp = optionalWarp.get();
warp.getMeta().setName(newName);
plugin.getDatabase().saveWarp(warp);
}
public void setWarpDescription(@NotNull String name, @NotNull String description) {
public void setWarpDescription(@NotNull String name, @NotNull String description) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
}
final Warp warp = optionalWarp.get();
this.setWarpDescription(optionalWarp.get(), description);
}
public void setWarpDescription(@NotNull Warp warp, @NotNull String description) {
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID);
}
warp.getMeta().setDescription(description);
plugin.getDatabase().saveWarp(warp);
}
@@ -19,19 +19,22 @@ public class ValidationException extends IllegalArgumentException {
case NOT_FOUND -> other ? "error_home_invalid_other" : "error_home_invalid";
case NAME_TAKEN -> "error_home_name_taken";
case NAME_INVALID -> "error_home_name_characters";
case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> "error_set_home_maximum_homes";
case REACHED_MAX_PUBLIC_HOMES -> "error_edit_home_maximum_public_homes";
case DESCRIPTION_INVALID -> "error_home_description_characters";
}, args)
.ifPresent(viewer::sendMessage);
}
public void dispatchWarpError(@NotNull CommandUser viewer, @NotNull HuskHomes plugin) {
public void dispatchWarpError(@NotNull CommandUser viewer, @NotNull HuskHomes plugin, @NotNull String... args) {
plugin.getLocales()
.getLocale(switch (error) {
case NOT_FOUND -> "error_warp_invalid";
case NAME_TAKEN -> "error_warp_name_taken";
case NAME_INVALID -> "error_warp_name_characters";
case DESCRIPTION_INVALID -> "error_warp_description_characters";
})
default -> throw new IllegalStateException("Unexpected value: " + error);
}, args)
.ifPresent(viewer::sendMessage);
}