From 34eb2c1f546457390e85e272e80cbc3ee17c7042 Mon Sep 17 00:00:00 2001 From: William278 Date: Mon, 20 Mar 2023 00:01:09 +0000 Subject: [PATCH] More command refactoring --- .../huskhomes/command/BukkitCommand.java | 36 +++- .../java/net/william278/huskhomes/Cache.java | 35 +--- .../william278/huskhomes/command/Command.java | 11 +- .../huskhomes/command/RtpCommand.java | 169 ++++++++---------- .../command/SavedPositionCommand.java | 6 + .../huskhomes/command/SetHomeCommand.java | 137 +++----------- .../huskhomes/command/SetPositionCommand.java | 36 ++++ .../huskhomes/command/SetSpawnCommand.java | 57 +++--- .../huskhomes/command/SetWarpCommand.java | 42 +---- .../huskhomes/command/SpawnCommand.java | 58 ++++-- .../huskhomes/command/TpOfflineCommand.java | 90 ++++++---- .../huskhomes/manager/HomesManager.java | 4 + .../huskhomes/manager/WarpsManager.java | 4 + .../teleport/TeleportationException.java | 24 ++- .../huskhomes/util/ValidationException.java | 59 +++--- .../database/migrator/mysql_migrator.sql | 71 -------- .../database/migrator/sqlite_migrator.sql | 83 --------- 17 files changed, 382 insertions(+), 540 deletions(-) create mode 100644 common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java delete mode 100644 common/src/main/resources/database/migrator/mysql_migrator.sql delete mode 100644 common/src/main/resources/database/migrator/sqlite_migrator.sql diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java index af56b90a..7f5ce13e 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java @@ -49,14 +49,36 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } // Register permissions - final PluginManager manager = plugin.getServer().getPluginManager(); - manager.addPermission(new Permission(command.getPermission(), "/" + command.getName(), - command.isOperatorCommand() ? PermissionDefault.OP : PermissionDefault.TRUE)); + addPermission(command.getPermission(), command.getUsage(), command.isOperatorCommand()); + final List childNodes = command.getAdditionalPermissions() + .entrySet().stream() + .map((entry) -> addPermission(entry.getKey(), "", entry.getValue())) + .filter(Objects::nonNull) + .toList(); + addPermission(command.getPermission("*"), command.getUsage(), command.isOperatorCommand(), + childNodes.toArray(new Permission[0])); + } - // Register master permission - final Map childNodes = new HashMap<>(); - manager.addPermission(new Permission(command.getPermission() + ".*", command.getUsage(), - PermissionDefault.FALSE, childNodes)); + @Nullable + private Permission addPermission(@NotNull String node, @NotNull String description, boolean operatorCommand, @NotNull Permission... children) { + final Map childNodes = Arrays.stream(children) + .map(Permission::getName) + .collect(HashMap::new, (map, child) -> map.put(child, true), HashMap::putAll); + + final PluginManager manager = plugin.getServer().getPluginManager(); + if (manager.getPermission(node) != null) { + return null; + } + + Permission permission; + if (description.isEmpty()) { + permission = new Permission(node, operatorCommand ? PermissionDefault.OP : PermissionDefault.TRUE, childNodes); + } else { + permission = new Permission(node, description, operatorCommand ? PermissionDefault.OP : PermissionDefault.TRUE, childNodes); + } + manager.addPermission(permission); + + return permission; } /** diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java index 7e2c2ff8..e775c36a 100644 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/Cache.java @@ -1,22 +1,13 @@ package net.william278.huskhomes; -import de.themoep.minedown.adventure.MineDown; -import net.william278.huskhomes.command.Command; -import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.database.Database; -import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.teleport.TimedTeleport; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.User; -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.position.Warp; -import net.william278.huskhomes.teleport.TimedTeleport; -import net.william278.paginedown.ListOptions; -import net.william278.paginedown.PaginatedList; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; /** * A cache used to hold frequently accessed data (i.e. TAB-completed homes and warps) @@ -28,9 +19,6 @@ public class Cache { private final Map> publicHomes = new HashMap<>(); private final List warps = new ArrayList<>(); private final Set players = new HashSet<>(); - private final Map privateHomeLists = new HashMap<>(); - private final Map publicHomeLists = new HashMap<>(); - private final Map warpLists = new HashMap<>(); private final Set currentlyOnWarmup = new HashSet<>(); /** @@ -119,27 +107,6 @@ public class Cache { return players; } - /** - * Cached lists of private homes for pagination, mapped to the username of the home owner - */ - public Map getPrivateHomeLists() { - return privateHomeLists; - } - - /** - * Cached lists of public homes for pagination - */ - public Map getPublicHomeLists() { - return publicHomeLists; - } - - /** - * Cached lists of warps for pagination - */ - public Map getWarpLists() { - return warpLists; - } - /** * Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s */ diff --git a/common/src/main/java/net/william278/huskhomes/command/Command.java b/common/src/main/java/net/william278/huskhomes/command/Command.java index 3247b5c9..97655e9a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Command.java +++ b/common/src/main/java/net/william278/huskhomes/command/Command.java @@ -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 aliases, @NotNull String usage, @NotNull HuskHomes plugin) { + protected Command(@NotNull String name, @NotNull List 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 getAdditionalPermissions() { + return Map.of(); + } + } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index 675b7f58..07cd6664 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -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 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 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 = 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 = 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 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 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."); - } - })); - }); - - } } diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index ff0cad4a..dade4c8a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -114,6 +114,12 @@ public abstract class SavedPositionCommand extends Comm .execute(); } + @Override + @NotNull + public Map getAdditionalPermissions() { + return Map.of(getOtherPermission(), true); + } + @Override @NotNull public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { diff --git a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java index 448d946c..09242de9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -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 ") - .ifPresent(onlineUser::sendMessage); - } - } - case 1 -> setHome(onlineUser, args[0], homes); - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome ") - .ifPresent(onlineUser::sendMessage); - } - }); - } - - /** - * Attempts to set a home by given name for the {@link OnlineUser}. - *

- * A number of validation checks will take place before the home is set. If these checks fail, the home won't be set. - *

    - *
  • The user's currentHomes must not exceed the permissive maximum home limit
  • - *
  • If economy features are on and the user does not have enough home slots, they must have sufficient funds to buy another
  • - *
  • The home name must not already exist
  • - *
  • The home name must meet the length and character criteria
  • - *
- * - * @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 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 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 homes = plugin.getDatabase().getHomes(user); + final Optional 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; } } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java new file mode 100644 index 00000000..70cad3c8 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java @@ -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(), "", 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 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); +} diff --git a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java index 9c570b32..be3e4972 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java @@ -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); } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java index 674500ae..2e2c1167 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java @@ -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 ") - .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)); - } - } diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index 7da1d227..0e78e423 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -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 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 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); + } + } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java index a7a9ea26..c2315a70 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java @@ -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(), "", plugin); } @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - if (args.length != 1) { - plugin.getLocales().getLocale("error_invalid_syntax", "/tpoffline ") - .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 optionalUser = parseStringArg(args, 0); + if (optionalUser.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); + return; + } + + final Optional 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 = 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(); } + } diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index 44f11b3d..4c5a74e8 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -48,6 +48,10 @@ public class HomesManager { throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS); } + if (!plugin.validateEconomyCheck(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT)) { + throw new ValidationException(ValidationException.Type.NOT_ENOUGH_MONEY); + } + plugin.performEconomyTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT); savedOwner.setHomeSlots(savedOwner.getHomeSlots() + 1); plugin.getDatabase().updateUserData(savedOwner); diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 09c1c86a..5a906e0f 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -41,6 +41,10 @@ public class WarpsManager { plugin.getDatabase().saveWarp(warp); } + public void createWarp(@NotNull String name, @NotNull Position position) throws ValidationException { + this.createWarp(name, position, plugin.getSettings().doOverwriteExistingHomesWarps()); + } + public void deleteWarp(@NotNull String name) throws ValidationException { final Optional warp = plugin.getDatabase().getWarp(name); if (warp.isEmpty()) { diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java index 57b69700..2518fad1 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportationException.java @@ -1,5 +1,7 @@ package net.william278.huskhomes.teleport; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.user.CommandUser; import org.jetbrains.annotations.NotNull; public class TeleportationException extends IllegalArgumentException { @@ -11,6 +13,26 @@ public class TeleportationException extends IllegalArgumentException { public enum Type { TELEPORTER_NOT_FOUND, TARGET_NOT_FOUND, - ALREADY_WARMING_UP, ECONOMY_ACTION_FAILED, WARMUP_ALREADY_MOVING, CANNOT_TELEPORT_TO_SELF + ALREADY_WARMING_UP, + ECONOMY_ACTION_FAILED, + WARMUP_ALREADY_MOVING, + CANNOT_TELEPORT_TO_SELF + } + + public void displayMessage(@NotNull CommandUser user, @NotNull HuskHomes plugin, @NotNull String[] args) { + switch (Type.valueOf(getMessage().split(": ")[1])) { + case TELEPORTER_NOT_FOUND, TARGET_NOT_FOUND -> plugin.getLocales() + .getLocale("error_player_not_found", args) + .ifPresent(user::sendMessage); + case ALREADY_WARMING_UP -> plugin.getLocales() + .getLocale("error_already_teleporting") + .ifPresent(user::sendMessage); + case WARMUP_ALREADY_MOVING -> plugin.getLocales() + .getLocale("error_teleport_warmup_stand_still") + .ifPresent(user::sendMessage); + case CANNOT_TELEPORT_TO_SELF -> plugin.getLocales() + .getLocale("error_teleport_request_self") + .ifPresent(user::sendMessage); + } } } diff --git a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java index 648277af..9f0c7abf 100644 --- a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java @@ -14,35 +14,54 @@ public class ValidationException extends IllegalArgumentException { } public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin, @NotNull String... args) { - plugin.getLocales() - .getLocale(switch (error) { - 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); + switch (error) { + case NOT_FOUND -> plugin.getLocales() + .getLocale(other ? "error_home_invalid_other" : "error_home_invalid", args) + .ifPresent(viewer::sendMessage); + case NAME_TAKEN -> plugin.getLocales() + .getLocale("error_home_name_taken", args) + .ifPresent(viewer::sendMessage); + case NAME_INVALID -> plugin.getLocales() + .getLocale("error_home_name_characters", args) + .ifPresent(viewer::sendMessage); + case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> plugin.getLocales() + .getLocale("error_set_home_maximum_homes", args) + .ifPresent(viewer::sendMessage); + case REACHED_MAX_PUBLIC_HOMES -> plugin.getLocales() + .getLocale("error_edit_home_maximum_public_homes", args) + .ifPresent(viewer::sendMessage); + case DESCRIPTION_INVALID -> plugin.getLocales() + .getLocale("error_home_description_characters", args) + .ifPresent(viewer::sendMessage); + } } 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); + switch (error) { + case NOT_FOUND -> plugin.getLocales() + .getLocale("error_warp_invalid", args) + .ifPresent(viewer::sendMessage); + case NAME_TAKEN -> plugin.getLocales() + .getLocale("error_warp_name_taken", args) + .ifPresent(viewer::sendMessage); + case NAME_INVALID -> plugin.getLocales() + .getLocale("error_warp_name_characters", args) + .ifPresent(viewer::sendMessage); + case DESCRIPTION_INVALID -> plugin.getLocales() + .getLocale("error_warp_description_characters", args) + .ifPresent(viewer::sendMessage); + } } public enum Type { NOT_FOUND, NAME_TAKEN, NAME_INVALID, - REACHED_MAX_HOMES, NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_PUBLIC_HOMES, DESCRIPTION_INVALID + REACHED_MAX_HOMES, + NOT_ENOUGH_HOME_SLOTS, + REACHED_MAX_PUBLIC_HOMES, + NOT_ENOUGH_MONEY, + DESCRIPTION_INVALID } } diff --git a/common/src/main/resources/database/migrator/mysql_migrator.sql b/common/src/main/resources/database/migrator/mysql_migrator.sql deleted file mode 100644 index c0c7f245..00000000 --- a/common/src/main/resources/database/migrator/mysql_migrator.sql +++ /dev/null @@ -1,71 +0,0 @@ -# MySQL migration script. - -# Clear target database. -DELETE -FROM `%target_positions_table%`; -DELETE -FROM `%target_users_table%`; - -# Migrate positions to the new schema -INSERT INTO `%target_positions_table%` (`id`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`) -SELECT `location_id` AS `id`, - `x`, - `y`, - `z`, - `yaw`, - `pitch`, - `world` AS `world_name`, - '00000000-0000-0000-0000-000000000000' AS `world_uuid`, - `server` AS `server_name` -FROM `%source_database%`.`%source_positions_table%`; - -# Migrate users to the new schema -INSERT INTO `%target_users_table%` (`uuid`, `username`, `last_position`, `offline_position`, `home_slots`, - `ignoring_requests`) -SELECT `user_uuid` AS `uuid`, - `username`, - `last_location_id` AS `last_position`, - `offline_location_id` AS `offline_position`, - `home_slots`, - `is_ignoring_requests` AS `ignoring_requests` -FROM `%source_database%`.`%source_users_table%`; - -# Migrate homes to the new schema -INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`) -SELECT `location_id` AS `position_id`, - `name`, - `description`, - `creation_time` AS `timestamp` -FROM `%source_database%`.`%source_homes_table%`; - -INSERT INTO `%target_homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) -SELECT UUID() AS `uuid`, - `id` AS `saved_position_id`, - `user_uuid` AS `owner_uuid`, - `public` -FROM `%source_database%`.`%source_homes_table%` AS `%source_homes_table%` - INNER JOIN `%target_saved_positions%` - ON `%source_homes_table%`.`location_id` = `%target_saved_positions%`.`position_id` - INNER JOIN `%source_database%`.`%source_users_table%` AS `%source_users_table%` - ON `%source_homes_table%`.`player_id` = `%source_users_table%`.`player_id`; - -# Migrate warps to the new schema -INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`) -SELECT `location_id` AS `position_id`, - `name`, - `description`, - `creation_time` AS `timestamp` -FROM `%source_database%`.`%source_warps_table%`; - -INSERT INTO `%target_warps_table%` (`uuid`, `saved_position_id`) -SELECT UUID() AS `uuid`, - `id` AS `saved_position_id` -FROM `%source_database%`.`%source_warps_table%` AS `%source_warps_table%` - INNER JOIN `%target_saved_positions%` - ON `%source_warps_table%`.`location_id` = `%target_saved_positions%`.`position_id`; - -# Rename old tables -ALTER TABLE `%source_database%`.`%source_positions_table%` RENAME TO `old_%source_positions_table%`; -ALTER TABLE `%source_database%`.`%source_users_table%` RENAME TO `old_%source_users_table%`; -ALTER TABLE `%source_database%`.`%source_homes_table%` RENAME TO `old_%source_homes_table%`; -ALTER TABLE `%source_database%`.`%source_warps_table%` RENAME TO `old_%source_warps_table%`; \ No newline at end of file diff --git a/common/src/main/resources/database/migrator/sqlite_migrator.sql b/common/src/main/resources/database/migrator/sqlite_migrator.sql deleted file mode 100644 index 549d65b8..00000000 --- a/common/src/main/resources/database/migrator/sqlite_migrator.sql +++ /dev/null @@ -1,83 +0,0 @@ -/* SQLite migration script. */ - --- Clear target database. -DELETE -FROM `%target_positions_table%`; -DELETE -FROM `%target_users_table%`; - --- Migrate positions to the new schema -INSERT INTO `%target_positions_table%` (`id`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`) -SELECT `location_id` AS `id`, - `x`, - `y`, - `z`, - `yaw`, - `pitch`, - `world` AS `world_name`, - '00000000-0000-0000-0000-000000000000' AS `world_uuid`, - `server` AS `server_name` -FROM `%source_positions_table%`; - --- Migrate users to the new schema -INSERT INTO `%target_users_table%` (`uuid`, `username`, `last_position`, `offline_position`, `home_slots`, - `ignoring_requests`) -SELECT `user_uuid` AS `uuid`, - `username`, - `last_location_id` AS `last_position`, - `offline_location_id` AS `offline_position`, - `home_slots`, - `is_ignoring_requests` AS `ignoring_requests` -FROM `%source_users_table%`; - --- Migrate homes to the new schema -INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`) -SELECT `location_id` AS `position_id`, - `name`, - `description`, - `creation_time` AS `timestamp` -FROM `%source_homes_table%`; - -INSERT INTO `%target_homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) -SELECT lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' || - substr(hex(randomblob(2)), 2) || '-' || - substr('AB89', 1 + (abs(random()) % 4), 1) || - substr(hex(randomblob(2)), 2) || '-' || - hex(randomblob(6))) AS `uuid`, - `id` AS `saved_position_id`, - `user_uuid` AS `owner_uuid`, - `public` -FROM `%source_homes_table%` - INNER JOIN `%target_saved_positions%` - ON `%source_homes_table%`.`location_id` = `%target_saved_positions%`.`position_id` - INNER JOIN `%source_users_table%` - ON `%source_homes_table%`.`player_id` = `%source_users_table%`.`player_id`; - --- Migrate warps to the new schema -INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`) -SELECT `location_id` AS `position_id`, - `name`, - `description`, - `creation_time` AS `timestamp` -FROM `%source_warps_table%`; - -INSERT INTO `%target_warps_table%` (`uuid`, `saved_position_id`) -SELECT lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' || - substr(hex(randomblob(2)), 2) || '-' || - substr('AB89', 1 + (abs(random()) % 4), 1) || - substr(hex(randomblob(2)), 2) || '-' || - hex(randomblob(6))) AS `uuid`, - `id` AS `saved_position_id` -FROM `%source_warps_table%` - INNER JOIN `%target_saved_positions%` - ON `%source_warps_table%`.`location_id` = `%target_saved_positions%`.`position_id`; - --- Rename old tables -ALTER TABLE `%source_positions_table%` - RENAME TO `old_%source_positions_table%`; -ALTER TABLE `%source_users_table%` - RENAME TO `old_%source_users_table%`; -ALTER TABLE `%source_homes_table%` - RENAME TO `old_%source_homes_table%`; -ALTER TABLE `%source_warps_table%` - RENAME TO `old_%source_warps_table%`; \ No newline at end of file