diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 119584cf..2bf2d44c 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -21,6 +21,8 @@ import net.william278.huskhomes.listener.EventListener; import net.william278.huskhomes.messenger.NetworkMessenger; import net.william278.huskhomes.messenger.PluginMessenger; import net.william278.huskhomes.messenger.RedisMessenger; +import net.william278.huskhomes.migrator.LegacyMigrator; +import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.player.BukkitPlayer; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Location; @@ -72,6 +74,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { private Set pluginHooks; private List registeredCommands; + private List migrators; + @Nullable private NetworkMessenger networkMessenger; @@ -100,11 +104,17 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { this.logger = new BukkitLogger(getLogger()); this.resourceReader = new BukkitResourceReader(this); + // Detect if an upgrade is needed + final BukkitUpgradeUtil upgradeData = BukkitUpgradeUtil.detect(this); + // Load settings and locales getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); initialized.set(reload().join()); if (initialized.get()) { logger.showDebugLogs(settings.debugLogging); + if (upgradeData != null) { + upgradeData.upgradeSettings(settings); + } getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); } else { throw new HuskHomesInitializationException("Failed to load plugin configuration settings and/or locales"); @@ -229,6 +239,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { }); getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands."); + // Prepare migrators + this.migrators = new ArrayList<>(); + this.migrators.add(new LegacyMigrator(this)); + //todo EssentialsX + // Hook into bStats metrics try { new Metrics(this, METRICS_ID); @@ -244,6 +259,18 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getPluginVersion() + ")"))); } + + // Perform automatic upgrade if detected + if (upgradeData != null) { + getLoggingAdapter().log(Level.INFO, "Performing automatic upgrade..."); + new LegacyMigrator(this, upgradeData).start().thenAccept(result -> { + if (result) { + getLoggingAdapter().log(Level.INFO, "Successfully performed automatic upgrade."); + } else { + getLoggingAdapter().log(Level.WARNING, "Failed to perform automatic upgrade."); + } + }); + } } catch (HuskHomesInitializationException exception) { getLoggingAdapter().log(Level.SEVERE, exception.getMessage()); initialized.set(false); @@ -348,6 +375,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { return eventDispatcher; } + @Override + public List getMigrators() { + return migrators; + } + @Override public Optional getServerSpawn() { return Optional.ofNullable(serverSpawn); diff --git a/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java b/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java new file mode 100644 index 00000000..2fd6f157 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/migrator/LegacyMigrator.java @@ -0,0 +1,175 @@ +package net.william278.huskhomes.migrator; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.util.BukkitUpgradeUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; + +public class LegacyMigrator extends Migrator { + + public Settings.DatabaseType sourceDatabaseType; + public String sourceMySqlHost; + public int sourceMySqlPort; + public String sourceMySqlDatabase; + public String sourceMySqlUsername; + public String sourceMySqlPassword; + public String sourcePlayerDataTable = "huskhomes_player_data"; + public String sourceLocationsDataTable = "huskhomes_location_data"; + public String sourceHomesDataTable = "huskhomes_home_data"; + public String sourceWarpsDataTable = "huskhomes_warp_data"; + + public LegacyMigrator(@NotNull HuskHomes implementor) { + super(implementor); + this.sourceDatabaseType = implementor.getSettings().databaseType; + this.sourceMySqlHost = implementor.getSettings().mySqlHost; + this.sourceMySqlPort = implementor.getSettings().mySqlPort; + this.sourceMySqlDatabase = implementor.getSettings().mySqlDatabase; + this.sourceMySqlUsername = implementor.getSettings().mySqlUsername; + this.sourceMySqlPassword = implementor.getSettings().mySqlPassword; + } + + public LegacyMigrator(@NotNull HuskHomes implementor, @NotNull BukkitUpgradeUtil bukkitUpgradeUtil) { + super(implementor); + this.sourceDatabaseType = bukkitUpgradeUtil.databaseType; + + this.sourceMySqlHost = bukkitUpgradeUtil.mySqlHost; + this.sourceMySqlPort = bukkitUpgradeUtil.mySqlPort; + this.sourceMySqlDatabase = bukkitUpgradeUtil.mySqlDatabase; + this.sourceMySqlUsername = bukkitUpgradeUtil.mySqlUsername; + this.sourceMySqlPassword = bukkitUpgradeUtil.mySqlPassword; + + this.sourcePlayerDataTable = bukkitUpgradeUtil.sourcePlayerDataTable; + this.sourceLocationsDataTable = bukkitUpgradeUtil.sourceLocationsDataTable; + this.sourceHomesDataTable = bukkitUpgradeUtil.sourceHomesDataTable; + this.sourceWarpsDataTable = bukkitUpgradeUtil.sourceWarpsDataTable; + } + + @Override + public CompletableFuture start() { + return CompletableFuture.supplyAsync(() -> { + if (sourceDatabaseType == Settings.DatabaseType.SQLITE) { + migrateSqLiteDatabase(); + return true; + } + + if (sourceDatabaseType == plugin.getSettings().databaseType + && sourceMySqlHost.equals(plugin.getSettings().mySqlHost) + && sourceMySqlPort == plugin.getSettings().mySqlPort) { + migrateMySqlDatabase(); + return true; + } + + plugin.getLoggingAdapter().log(Level.SEVERE, "Migration failed! Different source and target databases/types." + + "Please dump your data from your source database manually and then" + + " import it to your new database, then attempt migration again."); + return false; + }); + } + + private void migrateSqLiteDatabase() { + plugin.getLoggingAdapter().log(Level.INFO, "Migrating SQLite database..."); + //todo write script + } + + private void migrateMySqlDatabase() { + plugin.getLoggingAdapter().log(Level.INFO, "Migrating same MySQL database..."); + //todo write script + } + + @Override + public void handleConfigurationCommand(@NotNull String[] args) { + if (args.length == 2) { + if (switch (args[0].toLowerCase()) { + case "database" -> { + this.sourceMySqlDatabase = args[1]; + yield true; + } + case "player_data_table" -> { + this.sourcePlayerDataTable = args[1]; + yield true; + } + case "locations_data_table" -> { + this.sourceLocationsDataTable = args[1]; + yield true; + } + case "homes_data_table" -> { + this.sourceHomesDataTable = args[1]; + yield true; + } + case "warps_data_table" -> { + this.sourceWarpsDataTable = args[1]; + yield true; + } + default -> false; + }) { + plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu()); + plugin.getLoggingAdapter().log(Level.INFO, "Successfully set " + args[0] + " to " + + obfuscateDataString(args[1])); + } else { + plugin.getLoggingAdapter().log(Level.INFO, "Invalid operation, could not set " + args[0] + " to " + + obfuscateDataString(args[1]) + " (is it a valid option?)"); + } + } else { + plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu()); + } + } + + @Override + public @NotNull String getIdentifier() { + return "legacy"; + } + + @Override + public @NotNull String getName() { + return "HuskHomes Legacy (v2.x)"; + } + + @NotNull + @Override + public String getHelpMenu() { + return """ + === HuskHomes v2.x --> v3.x Migration Wizard ========= + This will migrate all user data from HuskHomes v2.x + to HuskHomes v3.x. The source and target databases + must be the same, please note. + + [!] Existing data in the database will be wiped. [!] + + STEP 1] Please ensure no players are on any servers + running HuskHomes. If you're running MySQL, you only + need to do this once - it's best to only have one + server running. + + STEP 2] Ensure the following settings are correct: + + Source table names: + - player_data: %source_players_table% + - locations_data: %source_locations_table% + - homes_data: %source_homes_table% + - warps_data: %source_warps_table% + + Source MySQL database name (ignore if using SQLite): + - database: %source_mysql_database% + + If any of these are not correct, please correct them + using the command: + "huskhomes migrate legacy set " + (e.g.: "huskhomes migrate legacy set database foo") + + STEP 3] HuskHomes will migrate data into the database + tables configured in the config.yml file of this + server. Please make sure you're happy with this + before proceeding. + + STEP 4] To start the migration, please run: + "huskhomes migrate legacy start" + """.replaceAll("%source_players_table%", sourcePlayerDataTable) + .replaceAll("%source_locations_table%", sourceLocationsDataTable) + .replaceAll("%source_homes_table%", sourceHomesDataTable) + .replaceAll("%source_warps_table%", sourceWarpsDataTable) + .replaceAll("%source_mysql_database%", sourceMySqlDatabase); + } +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java new file mode 100644 index 00000000..6fc034ad --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitUpgradeUtil.java @@ -0,0 +1,82 @@ +package net.william278.huskhomes.util; + +import net.william278.annotaml.Annotaml; +import net.william278.huskhomes.BukkitHuskHomes; +import net.william278.huskhomes.config.Settings; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.logging.Level; + +/** + * Utility class for upgrading important stuff from HuskHomes v2.x config files to v3.x. + */ +public class BukkitUpgradeUtil { + + private final BukkitHuskHomes plugin; + public Settings.DatabaseType databaseType; + public String mySqlHost; + public int mySqlPort; + public String mySqlDatabase; + public String mySqlUsername; + public String mySqlPassword; + public String mySqlParams; + + public String sourcePlayerDataTable; + public String sourceLocationsDataTable; + public String sourceHomesDataTable; + public String sourceWarpsDataTable; + + private BukkitUpgradeUtil(@NotNull BukkitHuskHomes plugin) { + this.plugin = plugin; + } + + /** + * Reads old settings from the config and writes them to the new config. + */ + private void readOldSettings() { + this.databaseType = Settings.DatabaseType.valueOf(plugin.getConfig() + .getString("data_storage_options.storage_type", "SQLITE").toUpperCase()); + + this.mySqlHost = plugin.getConfig().getString("data_storage_options.mysql_credentials.host", "localhost"); + this.mySqlPort = plugin.getConfig().getInt("data_storage_options.mysql_credentials.port", 3306); + this.mySqlDatabase = plugin.getConfig().getString("data_storage_options.mysql_credentials.database", "HuskHomes"); + this.mySqlUsername = plugin.getConfig().getString("data_storage_options.mysql_credentials.username", "root"); + this.mySqlPassword = plugin.getConfig().getString("data_storage_options.mysql_credentials.password", "pa55w0rd"); + this.mySqlParams = plugin.getConfig().getString("data_storage_options.mysql_credentials.params", "?autoReconnect=true&useSSL=false"); + + this.sourcePlayerDataTable = plugin.getConfig().getString("data_storage_options.table_names.player_data", "huskhomes_player_data"); + this.sourceLocationsDataTable = plugin.getConfig().getString("data_storage_options.table_names.locations_data", "huskhomes_location_data"); + this.sourceHomesDataTable = plugin.getConfig().getString("data_storage_options.table_names.homes_data", "huskhomes_home_data"); + this.sourceWarpsDataTable = plugin.getConfig().getString("data_storage_options.table_names.warps_data", "huskhomes_warp_data"); + } + + /** + * Upgrade the config from an older version to the current version. + * + * @param settings The settings to upgrade + */ + public void upgradeSettings(@NotNull Settings settings) { + plugin.getLoggingAdapter().log(Level.WARNING, "Upgrading critical HuskHomes v2.x settings to v3.x."); + settings.databaseType = databaseType; + settings.mySqlHost = mySqlHost; + settings.mySqlPort = mySqlPort; + settings.mySqlDatabase = mySqlDatabase; + settings.mySqlUsername = mySqlUsername; + settings.mySqlPassword = mySqlPassword; + settings.mySqlConnectionParameters = mySqlParams; + Annotaml.save(settings, new File(plugin.getDataFolder(), "config.yml")); + } + + @Nullable + public static BukkitUpgradeUtil detect(@NotNull BukkitHuskHomes plugin) { + if (!plugin.getConfig().contains("config_file_version")) { + return null; + } + final BukkitUpgradeUtil upgrade = new BukkitUpgradeUtil(plugin); + upgrade.readOldSettings(); + return upgrade; + } + +} diff --git a/bukkit/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml index 1fe7bfd4..660499f9 100644 --- a/bukkit/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -78,4 +78,4 @@ commands: back: usage: /back huskhomes: - usage: /huskhomes [about|help|reload|update] \ No newline at end of file + usage: /huskhomes [about|help|reload|update|migrate] \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index af051e22..531941d6 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -12,6 +12,7 @@ import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.MapHook; import net.william278.huskhomes.hook.PluginHook; import net.william278.huskhomes.messenger.NetworkMessenger; +import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.SavedPositionManager; @@ -155,6 +156,13 @@ public interface HuskHomes { @NotNull EventDispatcher getEventDispatcher(); + /** + * The list of available {@link Migrator}s + * + * @return the list of available {@link Migrator} + */ + List getMigrators(); + /** * The {@link Spawn} location of this server * diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index 52d26075..9e387013 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -3,6 +3,7 @@ package net.william278.huskhomes.command; import de.themoep.minedown.MineDown; import net.william278.desertwell.AboutMenu; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -11,6 +12,7 @@ import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; @@ -104,6 +106,8 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, new MineDown("[HuskHomes](#00fb9a bold) [| HuskHomes is up-to-date." + " (Currently running: v" + plugin.getPluginVersion() + "](#00fb9a)")))); } + case "migrate" -> plugin.getLocales().getLocale("error_console_command_only") + .ifPresent(onlineUser::sendMessage); } } @@ -140,9 +144,49 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, () -> plugin.getLoggingAdapter().log(Level.INFO, "HuskHomes is up to date" + " (Currently running v" + plugin.getPluginVersion() + ")"))); + case "migrate" -> { + if (args.length < 2) { + plugin.getLoggingAdapter().log(Level.INFO, + "Please choose a migrator, then run \"huskhomes migrate \""); + logMigratorsList(); + return; + } + final Optional selectedMigrator = plugin.getMigrators().stream().filter(availableMigrator -> + availableMigrator.getIdentifier().equalsIgnoreCase(args[1])).findFirst(); + selectedMigrator.ifPresentOrElse(migrator -> { + if (args.length < 3) { + plugin.getLoggingAdapter().log(Level.INFO, migrator.getHelpMenu()); + return; + } + switch (args[2]) { + case "start" -> migrator.start().thenAccept(succeeded -> { + if (succeeded) { + plugin.getLoggingAdapter().log(Level.INFO, "Migration completed successfully!"); + } else { + plugin.getLoggingAdapter().log(Level.WARNING, "Migration failed!"); + } + }); + case "set" -> migrator.handleConfigurationCommand(Arrays.copyOfRange(args, 3, args.length)); + default -> plugin.getLoggingAdapter().log(Level.INFO, + "Invalid syntax. Console usage: \"huskhomes migrate " + args[1] + " "); + } + }, () -> { + plugin.getLoggingAdapter().log(Level.INFO, + "Please specify a valid migrator.\n" + + "If a migrator is not available, please verify that you meet the prerequisites to use it."); + logMigratorsList(); + }); + } } } + private void logMigratorsList() { + plugin.getLoggingAdapter().log(Level.INFO, + "List of available migrators:\nMigrator ID / Migrator Name:\n" + + plugin.getMigrators().stream() + .map(migrator -> migrator.getIdentifier() + " - " + migrator.getName()) + .collect(Collectors.joining("\n"))); + } private void sendAboutMenu(@NotNull OnlineUser onlineUser) { if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_ABOUT.node)) { diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index 2afca9bd..dc8c6fd5 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -261,12 +261,12 @@ public class Settings { * Represents the names of tables in the database */ public enum TableName { - PLAYER_DATA("huskhomes_player_data"), + PLAYER_DATA("huskhomes_users"), POSITION_DATA("huskhomes_position_data"), - SAVED_POSITION_DATA("huskhomes_saved_position_data"), - HOME_DATA("huskhomes_home_data"), - WARP_DATA("huskhomes_warp_data"), - TELEPORT_DATA("huskhomes_teleport_data"); + SAVED_POSITION_DATA("huskhomes_saved_positions"), + HOME_DATA("huskhomes_homes"), + WARP_DATA("huskhomes_warps"), + TELEPORT_DATA("huskhomes_teleports"); private final String defaultName; diff --git a/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java b/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java new file mode 100644 index 00000000..ca67901b --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/migrator/Migrator.java @@ -0,0 +1,68 @@ +package net.william278.huskhomes.migrator; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; + +/** + * A migrator that imports legacy and other plugin's data into HuskHomes' format. + */ +public abstract class Migrator { + + protected final HuskHomes plugin; + + protected Migrator(@NotNull HuskHomes implementor) { + this.plugin = implementor; + } + + /** + * Start the migrator + * + * @return A future that will be completed when the migrator is done + */ + public abstract CompletableFuture start(); + + /** + * Handle a command that sets migrator configuration parameters + * + * @param args The command arguments + */ + public abstract void handleConfigurationCommand(@NotNull String[] args); + + /** + * Obfuscates a data string to prevent important data from being logged to console + * + * @param dataString The data string to obfuscate + * @return The data string obfuscated with stars (*) + */ + @NotNull + protected final String obfuscateDataString(@NotNull String dataString) { + return (dataString.length() > 1 ? dataString.charAt(0) + "*".repeat(dataString.length() - 1) : ""); + } + + /** + * Get the unique identifier of the migrator + * + * @return The unique identifier of the migrator + */ + @NotNull + public abstract String getIdentifier(); + + /** + * Get the display name of the migrator + * + * @return The name of the migrator + */ + @NotNull + public abstract String getName(); + + /** + * Get the help splash menu of the migrator + * + * @return The help splash menu of the migrator + */ + @NotNull + public abstract String getHelpMenu(); + +} diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index 9180706a..fa8c6748 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -150,7 +150,7 @@ error_player_not_found: '[Error:](#ff3300) [Could not find the player %1%.](#ff7 error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' error_rtp_cooldown: '[Error:](#ff3300) [You must wait %1% minutes before randomly teleporting again.](#ff7e5e)' error_command_disabled: '[Error:](#ff3300) [That command is disabled!](#ff7e5e)' -error_console_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' # todo migrator +error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_tp_invalid_world: '[Error:](#ff3300) [Please specify a valid server world.](#ff7e5e)' error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe random location to teleport you.](#ff7e5e)' error_permission_restricted_warp: '[Error:](#ff3300) [You do not have permission to warp to %1%!](#ff7e5e)'