v4.5: Bulk delete, regex customization, QoL & API work (#486)

* Improve validator error specificity, fix #481

* Add more sanity-checking to cluster IDs, close #482

* Add bulk/player-delete command, close #484, close #257

* Fix checkstyle formatting in tests

* Add missing strings to other locale files

* Use morepaperlib for runtime command registration on spigot

* api: make creation methods return a future, close #473

* Add name/description restriction regex customization

* docs: Update config file with new regex options

* bump version number to 4.5

* fix typo, correct command confirmation logic

* Make confirmation locales more clear

* Fix confirmation checking logic
This commit is contained in:
William authored and GitHub committed 2023-08-28 16:31:48 +01:00
1 parent e2c9a52911
commit 6bfd69f232
38 files changed
+1161 -692

No files matched your search

@@ -321,10 +321,11 @@ public abstract class BaseHuskHomesAPI {
* @param owner The {@link User} to create the home for
* @param name The name of the home
* @param position The {@link Position} of the home
* @since 4.0
* @return a {@link CompletableFuture} that will complete with the created {@link Home}
* @since 4.5
*/
public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position) {
plugin.runAsync(() -> plugin.getManager().homes().createHome(owner, name, position, false, false));
public CompletableFuture<Home> createHome(@NotNull User owner, @NotNull String name, @NotNull Position position) {
return plugin.supplyAsync(() -> plugin.getManager().homes().createHome(owner, name, position, false, false));
}
/**
@@ -527,10 +528,11 @@ public abstract class BaseHuskHomesAPI {
*
* @param name The name of the warp
* @param position The {@link Position} of the warp
* @since 4.0
* @return A {@link CompletableFuture} that will complete with the created {@link Warp}
* @since 4.5
*/
public final void createWarp(@NotNull String name, @NotNull Position position) {
plugin.runAsync(() -> plugin.getManager().warps().createWarp(name, position));
public final CompletableFuture<Warp> createWarp(@NotNull String name, @NotNull Position position) {
return plugin.supplyAsync(() -> plugin.getManager().warps().createWarp(name, position));
}
/**
@@ -28,13 +28,13 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.importer.Importer;
import net.william278.huskhomes.user.CommandUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.paginedown.PaginatedList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -45,6 +45,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
"help", false,
"reload", true,
"import", true,
"delete", true,
"update", true
);
@@ -111,15 +112,6 @@ public class HuskHomesCommand extends Command implements TabProvider {
+ " you need to restart your server for these changes to take effect.](gray)"
));
}
case "update" -> updateChecker.check().thenAccept(checked -> {
if (checked.isUpToDate()) {
plugin.getLocales().getLocale("up_to_date", plugin.getVersion().toString())
.ifPresent(executor::sendMessage);
return;
}
plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(),
plugin.getVersion().toString()).ifPresent(executor::sendMessage);
});
case "import" -> {
if (!importersLoaded) {
importersLoaded = true;
@@ -132,12 +124,38 @@ public class HuskHomesCommand extends Command implements TabProvider {
}
this.importData(executor, removeFirstArg(args));
}
case "delete" -> {
if (args.length < 2) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
final String[] deletionArgs = removeFirstArg(args);
switch (deletionArgs[0].toLowerCase(Locale.ENGLISH)) {
case "player" -> this.deletePlayerData(executor, removeFirstArg(deletionArgs));
case "homes" -> this.deleteHomes(executor, removeFirstArg(deletionArgs));
case "warps" -> this.deleteWarps(executor, removeFirstArg(deletionArgs));
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/" + getName() + " delete <player|homes|warps> [args]")
.ifPresent(executor::sendMessage);
}
}
case "update" -> updateChecker.check().thenAccept(checked -> {
if (checked.isUpToDate()) {
plugin.getLocales().getLocale("up_to_date", plugin.getVersion().toString())
.ifPresent(executor::sendMessage);
return;
}
plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(),
plugin.getVersion().toString()).ifPresent(executor::sendMessage);
});
default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
}
}
private void importData(@NotNull CommandUser executor, String[] args) {
// Import data from another plugin
private void importData(@NotNull CommandUser executor, @NotNull String[] args) {
switch (parseStringArg(args, 0).orElse("list")) {
case "start" -> parseStringArg(args, 1).ifPresentOrElse(
name -> {
@@ -162,6 +180,109 @@ public class HuskHomesCommand extends Command implements TabProvider {
}
}
// Delete the data of a player
private void deletePlayerData(@NotNull CommandUser executor, @NotNull String[] args) {
final Optional<String> nameOrUuid = parseStringArg(args, 0);
if (nameOrUuid.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/" + getName() + " delete player <player> [confirm]")
.ifPresent(executor::sendMessage);
return;
}
plugin.runAsync(() -> {
Optional<SavedUser> savedUser;
try {
savedUser = plugin.getDatabase().getUserData(UUID.fromString(nameOrUuid.get()));
} catch (IllegalArgumentException e) {
savedUser = plugin.getDatabase().getUserDataByName(nameOrUuid.get());
}
if (savedUser.isEmpty()) {
plugin.getLocales().getLocale("error_player_not_found", nameOrUuid.get())
.ifPresent(executor::sendMessage);
return;
}
final User user = savedUser.get().getUser();
if (!parseStringArg(args, 1)
.map(a -> a.equalsIgnoreCase("confirm")).orElse(false)) {
plugin.getLocales().getLocale("delete_player_confirm",
savedUser.get().getUser().getUsername()).ifPresent(executor::sendMessage);
return;
}
final int homesDeleted = plugin.getManager().homes().deleteAllHomes(user);
plugin.getDatabase().deleteUserData(user.getUuid());
plugin.getLocales().getLocale("delete_player_success",
savedUser.get().getUser().getUsername(), Integer.toString(homesDeleted))
.ifPresent(executor::sendMessage);
});
}
// Delete homes in a certain world and/or server
private void deleteHomes(@NotNull CommandUser executor, @NotNull String[] args) {
final Map<String, String> filters;
try {
filters = getBulkDeleteFilters(args);
} catch (IllegalArgumentException e) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/" + getName() + " delete homes <world> <server> [confirm]")
.ifPresent(executor::sendMessage);
return;
}
if (!parseStringArg(args, 2).map(a -> a.equalsIgnoreCase("confirm")).orElse(false)) {
plugin.getLocales().getLocale("bulk_delete_homes_confirm",
filters.get("world"), filters.get("server")).ifPresent(executor::sendMessage);
return;
}
plugin.runAsync(() -> {
final int homesDeleted = plugin.getManager().homes().deleteAllHomes(
filters.get("world"), filters.get("server")
);
plugin.getLocales().getLocale("bulk_delete_homes_success",
Integer.toString(homesDeleted), filters.get("world"), filters.get("server"))
.ifPresent(executor::sendMessage);
});
}
// Delete warps in a certain world and/or server
private void deleteWarps(@NotNull CommandUser executor, @NotNull String[] args) {
final Map<String, String> filters;
try {
filters = getBulkDeleteFilters(args);
} catch (IllegalArgumentException e) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/" + getName() + " delete warps <world> <server> [confirm]")
.ifPresent(executor::sendMessage);
return;
}
if (!parseStringArg(args, 2).map(a -> a.equalsIgnoreCase("confirm")).orElse(false)) {
plugin.getLocales().getLocale("bulk_delete_warps_confirm",
filters.get("world"), filters.get("server")).ifPresent(executor::sendMessage);
return;
}
plugin.runAsync(() -> {
final int homesDeleted = plugin.getManager().warps().deleteAllWarps(
filters.get("world"), filters.get("server")
);
plugin.getLocales().getLocale("bulk_delete_warps_success",
Integer.toString(homesDeleted), filters.get("world"), filters.get("server"))
.ifPresent(executor::sendMessage);
});
}
@NotNull
private Map<String, String> getBulkDeleteFilters(@NotNull String[] args) throws IllegalArgumentException {
final Map<String, String> filters = new LinkedHashMap<>();
filters.put("world", parseStringArg(args, 0)
.orElseThrow(() -> new IllegalArgumentException("World not specified")));
filters.put("server", parseStringArg(args, 1).orElse(plugin.getServerName()));
return filters;
}
@NotNull
private PaginatedList getCommandList(@NotNull CommandUser user) {
return PaginatedList.of(plugin.getCommands().stream()
@@ -205,6 +326,7 @@ public class HuskHomesCommand extends Command implements TabProvider {
case "help" -> IntStream.rangeClosed(1, getCommandList(user).getTotalPages())
.mapToObj(Integer::toString).toList();
case "import" -> List.of("start", "list");
case "delete" -> List.of("player", "homes", "warps");
default -> null;
};
case 3 -> {
@@ -142,18 +142,31 @@ public class Settings {
@YamlKey("general.strict_tpa_here_requests")
private boolean strictTpaHereRequests = true;
// Name & description settings
@YamlComment("Whether home or warp names should be case insensitive (i.e. allow /home HomeOne and /home homeone)")
@YamlKey("general.case_insensitive_names")
private boolean caseInsensitiveNames = false;
@YamlComment("Whether home or warp names should allow UTF-8 characters (i.e. allow /home 你好)")
@YamlKey("general.allow_unicode_names")
private boolean allowUnicodeNames = false;
@YamlComment("Whether home and warp names should be restricted by a regex."
+ "Set this to false to allow full UTF-8 names (i.e. allow /home 你好).")
@YamlKey("towns.restrict_names")
private boolean restrictNames = true;
@YamlComment("Whether home or warp descriptions should allow UTF-8 characters")
@YamlKey("general.allow_unicode_descriptions")
private boolean allowUnicodeDescriptions = true;
@YamlComment("Regex which home and warp names must match. Names have a max length of 16 characters")
@YamlKey("towns.name_regex")
private String nameRegex = "[a-zA-Z0-9-_]*";
@YamlComment("Whether home/warp descriptions should be restricted. Set this to true to restrict UTF-8 usage.")
@YamlKey("towns.restrict_descriptions")
private boolean restrictDescriptions = false;
@YamlComment("Regex which home and warp descriptions must match. A hard max length of 256 characters is enforced")
@YamlKey("towns.description_regex")
private String descriptionRegex = "\\A\\p{ASCII}*\\z";
// Back command settings
@YamlComment("Whether /back should work to teleport the user to where they died")
@YamlKey("general.back_command_return_by_death")
private boolean backCommandReturnByDeath = true;
@@ -408,12 +421,22 @@ public class Settings {
return caseInsensitiveNames;
}
public boolean doAllowUnicodeNames() {
return allowUnicodeNames;
public boolean doRestrictNames() {
return restrictNames;
}
public boolean doAllowUnicodeDescriptions() {
return allowUnicodeDescriptions;
@NotNull
public String getNameRegex() {
return nameRegex;
}
public boolean doRestrictDescriptions() {
return restrictDescriptions;
}
@NotNull
public String getDescriptionRegex() {
return descriptionRegex;
}
public boolean doBackCommandReturnByDeath() {
@@ -172,6 +172,13 @@ public abstract class Database {
*/
public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid);
/**
* Delete a {@link SavedUser} from the database.
*
* @param uuid The {@link UUID} of the {@link SavedUser} to delete
*/
public abstract void deleteUserData(@NotNull UUID uuid);
/**
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
*
@@ -414,6 +421,15 @@ public abstract class Database {
*/
public abstract int deleteAllHomes(@NotNull User user);
/**
* Deletes all {@link Home}s on a specific world and server (given by name) from the home table on the database.
*
* @param worldName The name of the world to delete homes from
* @param serverName The name of the server to delete homes from
* @return An integer; the number of deleted homes
*/
public abstract int deleteAllHomes(@NotNull String worldName, @NotNull String serverName);
/**
* Deletes a {@link Warp} by the given unique id from the warp table on the database.
*
@@ -428,6 +444,15 @@ public abstract class Database {
*/
public abstract int deleteAllWarps();
/**
* Deletes all {@link Warp}s on a specific world and server (given by name) from the warp table on the database.
*
* @param worldName The name of the world to delete warps from
* @param serverName The name of the server to delete warps from
* @return An integer; the number of deleted warps
*/
public abstract int deleteAllWarps(@NotNull String worldName, @NotNull String serverName);
/**
* Close any remaining connection to the database source.
*/
@@ -291,6 +291,21 @@ public class H2Database extends Database {
return Optional.empty();
}
@Override
public void deleteUserData(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
}
}
@Override
public Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
@@ -1042,6 +1057,33 @@ public class H2Database extends Database {
return 0;
}
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%homes_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void deleteWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
@@ -1086,6 +1128,33 @@ public class H2Database extends Database {
return 0;
}
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%warps_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void terminate() {
if (connectionPool != null) {
@@ -329,6 +329,21 @@ public class MySqlDatabase extends Database {
return Optional.empty();
}
@Override
public void deleteUserData(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
}
}
@Override
public Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
@@ -1080,6 +1095,33 @@ public class MySqlDatabase extends Database {
return 0;
}
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%homes_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void deleteWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
@@ -1124,6 +1166,33 @@ public class MySqlDatabase extends Database {
return 0;
}
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%warps_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void terminate() {
if (dataSource != null) {
@@ -321,6 +321,18 @@ public class SqLiteDatabase extends Database {
return Optional.empty();
}
@Override
public void deleteUserData(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%players_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete a player from the database", e);
}
}
@Override
public Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -1026,6 +1038,30 @@ public class SqLiteDatabase extends Database {
return 0;
}
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%homes_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void deleteWarp(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -1065,6 +1101,30 @@ public class SqLiteDatabase extends Database {
return 0;
}
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN (
SELECT `position_id`
FROM `%saved_positions_table%`
WHERE `%saved_positions_table%`.`id` IN (
SELECT `saved_position_id`
FROM `%warps_table%`
WHERE `world_name`=?
AND `server_name`=?
)
);"""))) {
statement.setString(1, worldName);
statement.setString(2, serverName);
return statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
+ serverName + " from the database", e);
}
return 0;
}
@Override
public void terminate() {
try {
@@ -113,6 +113,13 @@ public class BlueMapHook extends MapHook {
}
}
@Override
public void clearHomes(@NotNull String worldName) {
if (publicHomesMarkerSets != null) {
publicHomesMarkerSets.get(worldName).getMarkers().clear();
}
}
@Override
public void updateWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
@@ -143,6 +150,13 @@ public class BlueMapHook extends MapHook {
}
}
@Override
public void clearWarps(@NotNull String worldName) {
if (warpsMarkerSets != null) {
warpsMarkerSets.get(worldName).getMarkers().clear();
}
}
@Nullable
private String getIcon(@NotNull String iconName) {
return BlueMapAPI.getInstance().map(api -> {
@@ -112,6 +112,13 @@ public class DynmapHook extends MapHook {
.forEach(Marker::deleteMarker)));
}
@Override
public void clearHomes(@NotNull String worldName) {
plugin.runSync(() -> getPublicHomesMarkerSet().ifPresent(markerSet -> markerSet.getMarkers().stream()
.filter(marker -> marker.getWorld().equals(worldName))
.forEach(Marker::deleteMarker)));
}
@Override
public void updateWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
@@ -150,6 +157,13 @@ public class DynmapHook extends MapHook {
.forEach(Marker::deleteMarker)));
}
@Override
public void clearWarps(@NotNull String worldName) {
plugin.runSync(() -> getWarpsMarkerSet().ifPresent(markerSet -> markerSet.getMarkers().stream()
.filter(marker -> marker.getWorld().equals(worldName))
.forEach(Marker::deleteMarker)));
}
private Optional<DynmapCommonAPI> getDynmap() {
return Optional.ofNullable(dynmapApi);
}
@@ -80,6 +80,13 @@ public abstract class MapHook extends Hook {
*/
public abstract void clearHomes(@NotNull User user);
/**
* Clears homes on a world from the map.
*
* @param worldName the world to clear homes from
*/
public abstract void clearHomes(@NotNull String worldName);
/**
* Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't.
*
@@ -99,6 +106,13 @@ public abstract class MapHook extends Hook {
*/
public abstract void clearWarps();
/**
* Clears all warps from a world from the map.
*
* @param worldName the world to clear warps from
*/
public abstract void clearWarps(@NotNull String worldName);
/**
* Returns if the position is valid to be set on this server.
*
@@ -85,6 +85,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
publicHomes.removeIf(home -> home.getOwner().equals(user));
}
@Override
public void clearHomes(@NotNull String worldName) {
publicHomes.removeIf(home -> home.getWorld().getName().equals(worldName));
}
@Override
public void updateWarp(@NotNull Warp warp) {
warps.remove(warp);
@@ -103,6 +108,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
warps.clear();
}
@Override
public void clearWarps(@NotNull String worldName) {
warps.removeIf(warp -> warp.getWorld().getName().equals(worldName));
}
private void registerIcon(@NotNull String key, @NotNull String iconFileName) {
try (InputStream iconStream = plugin.getResource(iconFileName)) {
if (iconStream == null) {
@@ -181,16 +181,16 @@ public class HomesManager {
userHomes.remove(user.getUuid().toString());
}
public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position,
@NotNull
public Home createHome(@NotNull User owner, @NotNull String name, @NotNull Position position,
boolean overwrite, boolean buyAdditionalSlots) throws ValidationException {
final Optional<Home> existingHome = plugin.getDatabase().getHome(owner, name);
if (existingHome.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
// Validate the home name; throw an exception if invalid
plugin.getValidator().validateName(name);
// Determine what the new home count would be & validate against user max homes
int homes = plugin.getDatabase().getHomes(owner).size() + (existingHome.isPresent() ? 0 : 1);
@@ -224,11 +224,12 @@ public class HomesManager {
.orElse(Home.from(position, PositionMeta.create(name, ""), owner));
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
return home;
}
public void createHome(@NotNull OnlineUser owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true);
this.createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true);
}
public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException {
@@ -257,6 +258,19 @@ public class HomesManager {
return deleted;
}
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
final int deleted = plugin.getDatabase().deleteAllHomes(worldName, serverName);
userHomes.values().forEach(homes -> homes.removeIf(
h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName)
));
publicHomes.removeIf(h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName));
if (plugin.getSettings().doCrossServer() && serverName.equals(plugin.getServerName())) {
plugin.getMapHook().ifPresent(hook -> hook.clearHomes(worldName));
}
plugin.getManager().propagateCacheUpdate();
return deleted;
}
public void setHomePosition(@NotNull User owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
@@ -284,10 +298,7 @@ public class HomesManager {
}
public void setHomeName(@NotNull Home home, @NotNull String newName) throws ValidationException {
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
plugin.getValidator().validateName(newName);
home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
@@ -304,10 +315,7 @@ public class HomesManager {
}
public void setHomeDescription(@NotNull Home home, @NotNull String description) {
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID);
}
plugin.getValidator().validateDescription(description);
home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
@@ -112,16 +112,16 @@ public class WarpsManager {
.toList();
}
public void createWarp(@NotNull String name, @NotNull Position position,
@NotNull
public Warp 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);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
// Validate the home name; throw an exception if invalid
plugin.getValidator().validateName(name);
final Warp warp = existingWarp
.map(existing -> {
@@ -132,10 +132,12 @@ public class WarpsManager {
.orElse(Warp.from(position, PositionMeta.create(name, "")));
plugin.getDatabase().saveWarp(warp);
this.cacheWarp(warp, true);
return warp;
}
public void createWarp(@NotNull String name, @NotNull Position position) throws ValidationException {
this.createWarp(name, position, plugin.getSettings().doOverwriteExistingHomesWarps());
@NotNull
public Warp createWarp(@NotNull String name, @NotNull Position position) throws ValidationException {
return this.createWarp(name, position, plugin.getSettings().doOverwriteExistingHomesWarps());
}
public void deleteWarp(@NotNull String name) throws ValidationException {
@@ -160,6 +162,16 @@ public class WarpsManager {
return deleted;
}
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName);
warps.removeIf(warp -> warp.getServer().equals(serverName) && warp.getWorld().getName().equals(worldName));
if (plugin.getSettings().doCrossServer() && plugin.getServerName().equals(serverName)) {
plugin.getMapHook().ifPresent(hook -> hook.clearWarps(worldName));
}
plugin.getManager().propagateCacheUpdate();
return deleted;
}
public void setWarpPosition(@NotNull String name, @NotNull Position position) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
@@ -185,10 +197,7 @@ public class WarpsManager {
}
public void setWarpName(@NotNull Warp warp, @NotNull String newName) throws ValidationException {
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID);
}
plugin.getValidator().validateName(newName);
warp.getMeta().setName(newName);
plugin.getDatabase().saveWarp(warp);
this.cacheWarp(warp, true);
@@ -204,10 +213,7 @@ public class WarpsManager {
}
public void setWarpDescription(@NotNull Warp warp, @NotNull String description) {
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID);
}
plugin.getValidator().validateDescription(description);
warp.getMeta().setDescription(description);
plugin.getDatabase().saveWarp(warp);
this.cacheWarp(warp, true);
@@ -19,6 +19,7 @@
package net.william278.huskhomes.network;
import net.kyori.adventure.key.InvalidKeyException;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Warp;
@@ -27,8 +28,10 @@ import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.logging.Level;
public abstract class Broker {
@@ -149,12 +152,19 @@ public abstract class Broker {
*/
public abstract void close();
// Get the formatted channel ID for the broker
@NotNull
protected String getSubChannelId() {
final String version = plugin.getVersion().getMajor() + "." + plugin.getVersion().getMinor();
return plugin.getKey(plugin.getSettings().getClusterId(), version).asString();
final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor());
try {
return plugin.getKey(plugin.getSettings().getClusterId().toLowerCase(Locale.ENGLISH), version).asString();
} catch (InvalidKeyException e) {
plugin.log(Level.SEVERE, "Cluster ID specified in config contains invalid characters");
}
return plugin.getKey("main", version).asString();
}
// Get the name of this server
@NotNull
protected String getServer() {
return plugin.getServerName();
@@ -42,12 +42,18 @@ public class ValidationException extends IllegalArgumentException {
case NAME_TAKEN -> plugin.getLocales()
.getLocale("error_home_name_taken")
.ifPresent(viewer::sendMessage);
case NAME_INVALID -> plugin.getLocales()
case NAME_INVALID_CHARACTERS -> plugin.getLocales()
.getLocale("error_home_name_characters", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID -> plugin.getLocales()
case NAME_INVALID_LENGTH -> plugin.getLocales()
.getLocale("error_home_name_length", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID_CHARACTERS -> plugin.getLocales()
.getLocale("error_home_description_characters", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID_LENGTH -> plugin.getLocales()
.getLocale("error_home_description_length", args)
.ifPresent(viewer::sendMessage);
case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> plugin.getLocales()
.getLocale("error_set_home_maximum_homes",
Integer.toString(plugin.getManager().homes()
@@ -72,12 +78,18 @@ public class ValidationException extends IllegalArgumentException {
case NAME_TAKEN -> plugin.getLocales()
.getLocale("error_warp_name_taken", args)
.ifPresent(viewer::sendMessage);
case NAME_INVALID -> plugin.getLocales()
case NAME_INVALID_CHARACTERS -> plugin.getLocales()
.getLocale("error_warp_name_characters", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID -> plugin.getLocales()
case NAME_INVALID_LENGTH -> plugin.getLocales()
.getLocale("error_warp_name_length", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID_CHARACTERS -> plugin.getLocales()
.getLocale("error_warp_description_characters", args)
.ifPresent(viewer::sendMessage);
case DESCRIPTION_INVALID_LENGTH -> plugin.getLocales()
.getLocale("error_warp_description_length", args)
.ifPresent(viewer::sendMessage);
default -> {
// Do nothing (silently handle validation errors)
}
@@ -96,12 +108,14 @@ public class ValidationException extends IllegalArgumentException {
public enum Type {
NOT_FOUND,
NAME_TAKEN,
NAME_INVALID,
NAME_INVALID_CHARACTERS,
NAME_INVALID_LENGTH,
REACHED_MAX_HOMES,
NOT_ENOUGH_HOME_SLOTS,
REACHED_MAX_PUBLIC_HOMES,
TRANSACTION_FAILED,
DESCRIPTION_INVALID
DESCRIPTION_INVALID_CHARACTERS,
DESCRIPTION_INVALID_LENGTH,
}
}
@@ -23,7 +23,6 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Home;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public class Validator {
public static final int MAX_NAME_LENGTH = 16;
@@ -37,35 +36,62 @@ public class Validator {
}
/**
* Check if a name is valid.
* Validate home and warp names.
*
* @param name The name to check
* @return True if the name is valid as per the plugin settings, false otherwise
* @param name The name to validate
* @throws ValidationException If the name is invalid
*/
public boolean isValidName(@NotNull String name) {
return (isAsciiOnly(name) || plugin.getSettings().doAllowUnicodeNames())
&& !containsWhitespace(name) && !name.contains(Home.IDENTIFIER_DELIMITER)
&& name.length() <= MAX_NAME_LENGTH && name.length() >= MIN_NAME_LENGTH;
public void validateName(@NotNull String name) throws ValidationException {
if (!isValidNameCharacters(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID_CHARACTERS);
}
if (!isValidNameLength(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID_LENGTH);
}
}
/**
* Validate home and warp descriptions.
*
* @param description The meta to validate
* @return Whether the meta is valid against the plugin settings
* @param description The description to validate
* @throws ValidationException If the description is invalid
*/
public boolean isValidDescription(@NotNull String description) {
return (isAsciiOnly(description) || plugin.getSettings().doAllowUnicodeDescriptions())
&& description.length() <= MAX_DESCRIPTION_LENGTH;
public void validateDescription(@NotNull String description) throws ValidationException {
if (!isValidDescriptionCharacters(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID_CHARACTERS);
}
if (!isValidDescriptionLength(description)) {
throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID_LENGTH);
}
}
// Check if a string contains only ASCII characters
private static boolean isAsciiOnly(@NotNull String string) {
return string.matches("\\A\\p{ASCII}*\\z") && !string.contains("\u0000");
// Check a home/warp name contains only valid characters
private boolean isValidNameCharacters(@NotNull String name) {
return (name.matches(plugin.getSettings().getNameRegex()) || !plugin.getSettings().doRestrictNames())
&& !name.contains("\u0000")
&& !containsWhitespace(name)
&& !name.contains(Home.IDENTIFIER_DELIMITER);
}
// Check a home/warp name is of a valid length
private boolean isValidNameLength(@NotNull String name) {
return name.length() <= MAX_NAME_LENGTH && name.length() >= MIN_NAME_LENGTH;
}
// Check a home/warp description contains only valid characters
private boolean isValidDescriptionCharacters(@NotNull String description) {
return (description.matches(plugin.getSettings().getDescriptionRegex())
|| !plugin.getSettings().doRestrictDescriptions())
&& !description.contains("\u0000");
}
// Check a home/warp description is of a valid length
private boolean isValidDescriptionLength(@NotNull String description) {
return description.length() <= MAX_DESCRIPTION_LENGTH;
}
// Check if a string contains whitespace
private static boolean containsWhitespace(@NotNull String string) {
private boolean containsWhitespace(@NotNull String string) {
return string.matches(".*\\s.*");
}