diff --git a/bukkit/build.gradle b/bukkit/build.gradle index 4ce6967f..b0d6ba11 100644 --- a/bukkit/build.gradle +++ b/bukkit/build.gradle @@ -1,6 +1,7 @@ dependencies { implementation project(path: ':common') + implementation 'org.bstats:bstats-bukkit:3.0.0' implementation 'io.papermc:paperlib:1.0.7' compileOnly 'org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT' @@ -21,4 +22,5 @@ shadowJar { relocate 'com.google', 'net.william278.huskhomes.libraries' relocate 'io.papermc.lib', 'net.william278.huskhomes.libraries.paperlib' + relocate 'org.bstats', 'net.william278.husksync.libraries.bstats' } \ No newline at end of file diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java new file mode 100644 index 00000000..913f627d --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -0,0 +1,354 @@ +package net.william278.huskhomes; + +import dev.dejvokep.boostedyaml.YamlDocument; +import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; +import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; +import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; +import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; +import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; +import net.william278.huskhomes.cache.Cache; +import net.william278.huskhomes.command.*; +import net.william278.huskhomes.config.Locales; +import net.william278.huskhomes.config.Settings; +import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.MySqlDatabase; +import net.william278.huskhomes.database.SqLiteDatabase; +import net.william278.huskhomes.listener.BukkitEventListener; +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.player.OnlineUser; +import net.william278.huskhomes.player.BukkitPlayer; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.Server; +import net.william278.huskhomes.position.SavedPositionManager; +import net.william278.huskhomes.teleport.BukkitTeleportManager; +import net.william278.huskhomes.teleport.TeleportManager; +import net.william278.huskhomes.util.*; +import org.bstats.bukkit.Metrics; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.PluginCommand; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; + +public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { + + /** + * Metrics ID for HuskHomes on Bukkit. + */ + private static final int METRICS_ID = 8430; + private Settings settings; + private Locales locales; + private BukkitLogger logger; + private BukkitResourceReader resourceReader; + private Database database; + private Cache cache; + private TeleportManager teleportManager; + private SavedPositionManager savedPositionManager; + private EventListener eventListener; + + @Nullable + private NetworkMessenger networkMessenger; + + @Nullable + private Server server; + + private static BukkitHuskHomes instance; + + public static BukkitHuskHomes getInstance() { + return instance; + } + + /** + * Returns the {@link Server} the plugin is on + * + * @param onlineUser {@link OnlineUser} to request the server + * @return The {@link Server} object + */ + @Override + public CompletableFuture getServer(@NotNull OnlineUser onlineUser) { + if (server != null) { + return CompletableFuture.supplyAsync(() -> server); + } + if (!getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + server = new Server("server"); + return CompletableFuture.supplyAsync(() -> server); + } + assert networkMessenger != null; + return networkMessenger.getServerName(onlineUser).thenApplyAsync(server -> { + this.server = new Server(server); + return this.server; + }); + } + + @Override + public void onLoad() { + // Set the instance + instance = this; + } + + @Override + public void onEnable() { + // Initialize HuskHomes + final AtomicBoolean initialized = new AtomicBoolean(true); + try { + // Set the logging and resource reading adapter + this.logger = new BukkitLogger(getLogger()); + this.resourceReader = new BukkitResourceReader(this); + + // Load settings and locales + getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); + initialized.set(reload().join()); + if (initialized.get()) { + logger.showDebugLogs(settings.getBooleanValue(Settings.ConfigOption.DEBUG_LOGGING)); + getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); + } else { + throw new HuskHomesInitializationException("Failed to load plugin configuration settings and/or locales"); + } + + // Initialize the database + getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database..."); + final String databaseType = settings.getStringValue(Settings.ConfigOption.DATA_STORAGE_TYPE); + this.database = switch (databaseType == null ? "MYSQL" : databaseType.toUpperCase()) { + case "MYSQL" -> new MySqlDatabase(settings, logger, resourceReader); + case "SQLITE" -> new SqLiteDatabase(settings, logger, resourceReader); + default -> null; + }; + if (database == null) { + throw new HuskHomesInitializationException("An invalid database type was specified. " + + "Please check the database type in the configuration file."); + } + initialized.set(this.database.initialize()); + if (initialized.get()) { + getLoggingAdapter().log(Level.INFO, "Successfully established a connection to the database"); + } else { + throw new HuskHomesInitializationException("Failed to establish a connection to the database. " + + "Please check the supplied database credentials in the config file"); + } + + // Initialize the network messenger if proxy mode is enabled + if (getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); + networkMessenger = switch (settings.getStringValue(Settings.ConfigOption.MESSENGER_TYPE).toUpperCase()) { + case "PLUGIN_MESSAGE", "PLUGINMESSAGE" -> new PluginMessenger(); + case "REDIS", "JEDIS" -> new RedisMessenger(); + default -> null; + }; + if (networkMessenger == null) { + throw new HuskHomesInitializationException("An invalid network messenger type was specified. " + + "Please check the network messenger type in the configuration file."); + } + networkMessenger.initialize(this); + getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); + } + + // Initialize the cache + cache = new Cache(); + cache.initialize(database); + + // Prepare the teleport manager + this.teleportManager = new BukkitTeleportManager(this); + + // Prepare the home and warp position manager + this.savedPositionManager = new SavedPositionManager(database, cache); + + // Register events + getLoggingAdapter().log(Level.INFO, "Registering events..."); + this.eventListener = new BukkitEventListener(this); + getLoggingAdapter().log(Level.INFO, "Successfully registered events listener"); + + // Register permissions + getLoggingAdapter().log(Level.INFO, "Registering permissions & commands..."); + Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission( + new org.bukkit.permissions.Permission(permission.node, + switch (permission.defaultAccess) { + case EVERYONE -> PermissionDefault.TRUE; + case NOBODY -> PermissionDefault.FALSE; + case OPERATORS -> PermissionDefault.OP; + }))); + + // Register commands + for (final BukkitCommandType bukkitCommandType : BukkitCommandType.values()) { + final PluginCommand pluginCommand = getCommand(bukkitCommandType.commandBase.command); + if (pluginCommand != null) { + new BukkitCommand(bukkitCommandType.commandBase, this).register(pluginCommand); + } + } + getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands."); + + // Hook into bStats metrics + try { + new Metrics(this, METRICS_ID); + } catch (final Exception e) { + getLoggingAdapter().log(Level.WARNING, "Skipped bStats metrics initialization due to an exception."); + } + + // Check for updates + if (settings.getBooleanValue(Settings.ConfigOption.CHECK_FOR_UPDATES)) { + getLoggingAdapter().log(Level.INFO, "Checking for updates..."); + CompletableFuture.runAsync(() -> new UpdateChecker(getPluginVersion(), getLoggingAdapter()).logToConsole()); + } + } catch (HuskHomesInitializationException exception) { + getLoggingAdapter().log(Level.SEVERE, exception.getMessage()); + initialized.set(false); + } catch (Exception exception) { + getLoggingAdapter().log(Level.SEVERE, "An unhandled exception occurred initializing HuskHomes!", exception); + initialized.set(false); + } finally { + // Validate initialization + if (initialized.get()) { + getLoggingAdapter().log(Level.INFO, "Successfully enabled HuskHomes v" + getPluginVersion()); + } else { + getLoggingAdapter().log(Level.SEVERE, "Failed to initialize HuskHomes. The plugin will now be disabled"); + getServer().getPluginManager().disablePlugin(this); + } + } + } + + @Override + public void onDisable() { + if (this.eventListener != null) { + this.eventListener.handlePluginDisable(); + } + if (database != null) { + database.terminate(); + } + if (networkMessenger != null) { + networkMessenger.terminate(); + } + } + + @NotNull + @Override + public Logger getLoggingAdapter() { + return logger; + } + + @NotNull + @Override + public List getOnlinePlayers() { + return Bukkit.getOnlinePlayers().stream().map( + player -> (OnlineUser) BukkitPlayer.adapt(player)).toList(); + } + + @NotNull + @Override + public Settings getSettings() { + return settings; + } + + @NotNull + @Override + public Locales getLocales() { + return locales; + } + + @Override + public @NotNull Database getDatabase() { + return database; + } + + @NotNull + @Override + public Cache getCache() { + return cache; + } + + @NotNull + @Override + public TeleportManager getTeleportManager() { + return teleportManager; + } + + @NotNull + @Override + public SavedPositionManager getSavedPositionManager() { + return savedPositionManager; + } + + @Override + public @Nullable NetworkMessenger getNetworkMessenger() { + return networkMessenger; + } + + @Override + public boolean isValidPositionOnServer(Position position) { + final Optional adaptedLocation = BukkitAdapter.adaptLocation(position); + if (adaptedLocation.isEmpty()) { + return false; + } + final Location location = adaptedLocation.get(); + assert location.getWorld() != null; + return location.getWorld().getWorldBorder().isInside(location); + } + + @Override + public @NotNull Version getPluginVersion() { + return Version.pluginVersion(getDescription().getVersion()); + } + + @Override + public @NotNull Version getMinecraftVersion() { + return Version.minecraftVersion(Bukkit.getBukkitVersion()); + } + + @Override + public @NotNull String getPlatformType() { + return getServer().getName(); + } + + @Override + public CompletableFuture reload() { + return CompletableFuture.supplyAsync(() -> { + try { + this.settings = Settings.load(YamlDocument.create(new File(getDataFolder(), "config.yml"), Objects.requireNonNull(resourceReader.getResource("config.yml")), GeneralSettings.builder().setUseDefaults(false).build(), LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.builder().setEncoding(DumperSettings.Encoding.UNICODE).build(), UpdaterSettings.builder().setVersioning(new BasicVersioning("config_version")).build())); + + this.locales = Locales.load(YamlDocument.create(new File(getDataFolder(), "messages-" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml"), Objects.requireNonNull(resourceReader.getResource("locales/" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml")))); + return true; + } catch (IOException | NullPointerException e) { + getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", e); + return false; + } + }); + } + + public static final class BukkitAdapter { + + public static Optional adaptLocation(net.william278.huskhomes.position.Location location) { + World world = Bukkit.getWorld(location.world.name); + if (world == null) { + world = Bukkit.getWorld(location.world.uuid); + } + if (world == null) { + return Optional.empty(); + } + return Optional.of(new Location(world, location.x, location.y, location.z, + location.yaw, location.pitch)); + } + + @Nullable + public static net.william278.huskhomes.position.Location adaptLocation(@NotNull Location location) { + if (location.getWorld() == null) return null; + return new net.william278.huskhomes.position.Location(location.getX(), location.getY(), location.getZ(), + location.getYaw(), location.getPitch(), + new net.william278.huskhomes.position.World(location.getWorld().getName(), location.getWorld().getUID())); + } + + } + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java deleted file mode 100644 index f79e6fc2..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java +++ /dev/null @@ -1,304 +0,0 @@ -package net.william278.huskhomes; - -import dev.dejvokep.boostedyaml.YamlDocument; -import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; -import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; -import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; -import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; -import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; -import net.william278.huskhomes.cache.Cache; -import net.william278.huskhomes.command.*; -import net.william278.huskhomes.config.Locales; -import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.data.Database; -import net.william278.huskhomes.data.MySqlDatabase; -import net.william278.huskhomes.data.SqLiteDatabase; -import net.william278.huskhomes.listener.BukkitEventProcessor; -import net.william278.huskhomes.messenger.NetworkMessenger; -import net.william278.huskhomes.messenger.PluginMessenger; -import net.william278.huskhomes.messenger.RedisMessenger; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.BukkitPlayer; -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Server; -import net.william278.huskhomes.position.SavedPositionManager; -import net.william278.huskhomes.teleport.BukkitTeleportManager; -import net.william278.huskhomes.teleport.TeleportManager; -import net.william278.huskhomes.util.BukkitLogger; -import net.william278.huskhomes.util.BukkitResourceReader; -import net.william278.huskhomes.util.Logger; -import net.william278.huskhomes.util.Permission; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.PluginCommand; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; - -public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { - - private static HuskHomesBukkit instance; - - public static HuskHomesBukkit getInstance() { - return instance; - } - - private Settings settings; - private Locales locales; - private BukkitLogger logger; - private BukkitResourceReader resourceReader; - private Database database; - private Cache cache; - private TeleportManager teleportManager; - private SavedPositionManager savedPositionManager; - @Nullable - private NetworkMessenger networkMessenger; - - @Nullable - private Server server; - - /** - * Returns the {@link Server} the plugin is on - * - * @param player {@link Player} to request the server - * @return The {@link Server} object - */ - @Override - public CompletableFuture getServer(@NotNull Player player) { - if (server != null) { - return CompletableFuture.supplyAsync(() -> server); - } - if (!getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { - server = new Server("server"); - return CompletableFuture.supplyAsync(() -> server); - } - assert networkMessenger != null; - return networkMessenger.getServerName(player).thenApplyAsync(server -> { - this.server = new Server(server); - return this.server; - }); - } - - @Override - public void onLoad() { - // Set the instance - instance = this; - } - - @Override - public void onEnable() { - // Set the logging and resource reading adapter - logger = new BukkitLogger(getLogger()); - resourceReader = new BukkitResourceReader(this); - - // Load plugin settings and messages - loadConfigData(); - - // Initialize the network messenger - if (getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { - getLogger().log(Level.INFO, "Initializing the network messenger..."); - networkMessenger = switch (settings.getStringValue(Settings.ConfigOption.MESSENGER_TYPE).toUpperCase()) { - case "PLUGIN_MESSAGE", "PLUGINMESSAGE" -> new PluginMessenger(); - case "REDIS", "JEDIS" -> new RedisMessenger(); - default -> null; - }; - if (networkMessenger == null) { - getLoggingAdapter().log(Level.SEVERE, "Invalid network messenger type specified; disabling!"); - setEnabled(false); - return; - } - networkMessenger.initialize(this); - getLogger().log(Level.INFO, "Successfully initialized the network messenger."); - } - - // Initialize the database - getLogger().log(Level.INFO, "Initializing database..."); - final String databaseType = settings.getStringValue(Settings.ConfigOption.DATA_STORAGE_TYPE); - database = switch (databaseType.toUpperCase()) { - case "MYSQL" -> new MySqlDatabase(settings, logger, resourceReader); - case "SQLITE" -> new SqLiteDatabase(settings, logger, resourceReader); - default -> null; - }; - if (database == null) { - getLoggingAdapter().log(Level.SEVERE, "Invalid database type specified; disabling!"); - setEnabled(false); - return; - } - database.initialize().thenRun(() -> { - getLogger().log(Level.INFO, "Successfully initialized the " + databaseType + " database."); - - // Initialize the cache - getLogger().log(Level.INFO, "Initializing the system cache..."); - - cache = new Cache(); - cache.initialize(database); - - getLogger().log(Level.INFO, "Successfully initialized the system cache."); - }).thenRun(() -> { - // Prepare the teleport manager - this.teleportManager = new BukkitTeleportManager(this); - - // Prepare the home and warp position manager - this.savedPositionManager = new SavedPositionManager(database, cache); - - // Register permissions - Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission( - new org.bukkit.permissions.Permission(permission.node, - switch (permission.defaultAccess) { - case EVERYONE -> PermissionDefault.TRUE; - case NOBODY -> PermissionDefault.FALSE; - case OPERATORS -> PermissionDefault.OP; - }))); - - // Register commands - todo add all here - getLogger().log(Level.INFO, "Registering commands..."); - final CommandBase[] commands = new CommandBase[]{ - new HomeCommand(this), new SetHomeCommand(this), new HomeListCommand(this), new DelHomeCommand(this), - new WarpCommand(this), new SetWarpCommand(this), new WarpListCommand(this), new DelWarpCommand(this), - new BackCommand(this)}; - for (CommandBase commandBase : commands) { - final PluginCommand pluginCommand = getCommand(commandBase.command); - if (pluginCommand != null) { - new BukkitCommand(commandBase, this).register(pluginCommand); - } - } - getLogger().log(Level.INFO, "Successfully registered " + commands.length + " commands."); - - // Register listener - getServer().getPluginManager().registerEvents(new BukkitEventProcessor(this), this); - }); - } - - @Override - public void onDisable() { - if (database != null) { - database.terminate(); - } - if (networkMessenger != null) { - networkMessenger.terminate(); - } - } - - @Override - public Logger getLoggingAdapter() { - return logger; - } - - @Override - public List getOnlinePlayers() { - return Bukkit.getOnlinePlayers().stream().map( - player -> (Player) BukkitPlayer.adapt(player)).toList(); - } - - @Override - public Settings getSettings() { - return settings; - } - - @Override - public Locales getLocales() { - return locales; - } - - @Override - public Database getDatabase() { - return database; - } - - @Override - public Cache getCache() { - return cache; - } - - @Override - public TeleportManager getTeleportManager() { - return teleportManager; - } - - @Override - public SavedPositionManager getSavedPositionManager() { - return savedPositionManager; - } - - @Override - public @Nullable NetworkMessenger getNetworkMessenger() { - return networkMessenger; - } - - @Override - public boolean isValidPositionOnServer(Position position) { - final Optional adaptedLocation = BukkitAdapter.adaptLocation(position); - if (adaptedLocation.isEmpty()) { - return false; - } - final Location location = adaptedLocation.get(); - assert location.getWorld() != null; - return location.getWorld().getWorldBorder().isInside(location); - } - - // Load from the plugin config - public void loadConfigData() { - try { - getLogger().log(Level.INFO, "Loading configuration data..."); - settings = Settings.load(YamlDocument.create(new File(getDataFolder(), "config.yml"), - Objects.requireNonNull(resourceReader.getResource("config.yml")), - GeneralSettings.builder().setUseDefaults(false).build(), - LoaderSettings.builder().setAutoUpdate(true).build(), - DumperSettings.builder().setEncoding(DumperSettings.Encoding.UNICODE).build(), - UpdaterSettings.builder().setVersioning(new BasicVersioning("config_version")).build())); - locales = Locales.load(YamlDocument.create(new File(getDataFolder(), - "messages-" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml"), - Objects.requireNonNull(resourceReader.getResource( - "languages/" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml")))); - getLogger().log(Level.INFO, "Successfully loaded configuration data."); - } catch (IOException | NullPointerException e) { - getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", e); - } - } - - @Override - public String getPluginVersion() { - return getDescription().getVersion(); - } - - @Override - public String getPlatformType() { - return getServer().getName(); - } - - public static final class BukkitAdapter { - - public static Optional adaptLocation(net.william278.huskhomes.position.Location location) { - World world = Bukkit.getWorld(location.world.name); - if (world == null) { - world = Bukkit.getWorld(location.world.uuid); - } - if (world == null) { - return Optional.empty(); - } - return Optional.of(new Location(world, location.x, location.y, location.z, - location.yaw, location.pitch)); - } - - @Nullable - public static net.william278.huskhomes.position.Location adaptLocation(@NotNull Location location) { - if (location.getWorld() == null) return null; - return new net.william278.huskhomes.position.Location(location.getX(), location.getY(), location.getZ(), - location.getYaw(), location.getPitch(), - new net.william278.huskhomes.position.World(location.getWorld().getName(), location.getWorld().getUID())); - } - - } - -} diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommandType.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommandType.java new file mode 100644 index 00000000..6e71a6e3 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommandType.java @@ -0,0 +1,26 @@ +package net.william278.huskhomes.command; + +import net.william278.huskhomes.BukkitHuskHomes; +import org.jetbrains.annotations.NotNull; + +/** + * Commands available on the Bukkit HuskHomes implementation + */ +public enum BukkitCommandType { + + HOME_COMMAND(new HomeCommand(BukkitHuskHomes.getInstance())), + SET_HOME_COMMAND(new SetHomeCommand(BukkitHuskHomes.getInstance())), + HOME_LIST_COMMAND(new HomeListCommand(BukkitHuskHomes.getInstance())), + DEL_HOME_COMMAND(new DelHomeCommand(BukkitHuskHomes.getInstance())), + WARP_COMMAND(new WarpCommand(BukkitHuskHomes.getInstance())), + SET_WARP_COMMAND(new SetWarpCommand(BukkitHuskHomes.getInstance())), + WARP_LIST_COMMAND(new WarpListCommand(BukkitHuskHomes.getInstance())), + DEL_WARP_COMMAND(new DelWarpCommand(BukkitHuskHomes.getInstance())), + BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance())); + + public final CommandBase commandBase; + + BukkitCommandType(@NotNull CommandBase commandBase) { + this.commandBase = commandBase; + } +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java similarity index 82% rename from bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java rename to bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java index 3c7855d3..1b0f81a5 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java @@ -8,9 +8,9 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; -public class BukkitEventProcessor extends EventProcessor implements Listener { +public class BukkitEventListener extends EventListener implements Listener { - public BukkitEventProcessor(@NotNull HuskHomes implementor) { + public BukkitEventListener(@NotNull HuskHomes implementor) { super(implementor); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java b/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java index 43b2399e..6abe4d22 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/messenger/PluginMessenger.java @@ -4,9 +4,9 @@ import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.HuskHomesBukkit; +import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.player.BukkitPlayer; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Server; import org.bukkit.Bukkit; import org.bukkit.plugin.messaging.PluginMessageListener; @@ -37,18 +37,18 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi super.initialize(implementor); // Register HuskHomes messaging channel - Bukkit.getMessenger().registerIncomingPluginChannel((HuskHomesBukkit) implementor, BUNGEE_PLUGIN_CHANNEL_NAME, this); - Bukkit.getMessenger().registerOutgoingPluginChannel((HuskHomesBukkit) implementor, BUNGEE_PLUGIN_CHANNEL_NAME); + Bukkit.getMessenger().registerIncomingPluginChannel((BukkitHuskHomes) implementor, BUNGEE_PLUGIN_CHANNEL_NAME, this); + Bukkit.getMessenger().registerOutgoingPluginChannel((BukkitHuskHomes) implementor, BUNGEE_PLUGIN_CHANNEL_NAME); } @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture getOnlinePlayerNames(@NotNull Player requester) { + public CompletableFuture getOnlinePlayerNames(@NotNull OnlineUser requester) { onlinePlayerNamesRequest = new CompletableFuture<>(); final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("PlayerList"); pluginMessageWriter.writeUTF("ALL"); - ((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return onlinePlayerNamesRequest; @@ -56,11 +56,11 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture getServerName(@NotNull Player requester) { + public CompletableFuture getServerName(@NotNull OnlineUser requester) { serverNameRequest = new CompletableFuture<>(); final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("GetServer"); - ((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return serverNameRequest; @@ -68,11 +68,11 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture getOnlineServers(@NotNull Player requester) { + public CompletableFuture getOnlineServers(@NotNull OnlineUser requester) { onlineServersRequest = new CompletableFuture<>(); final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("GetServers"); - ((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(), + ((BukkitPlayer) requester).sendPluginMessage(BukkitHuskHomes.getInstance(), BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return onlineServersRequest; @@ -80,14 +80,14 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi @Override @SuppressWarnings("UnstableApiUsage") - public CompletableFuture sendPlayer(@NotNull Player player, @NotNull Server server) { - return getOnlineServers(player).thenApplyAsync(onlineServers -> { + public CompletableFuture sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server) { + return getOnlineServers(onlineUser).thenApplyAsync(onlineServers -> { for (String onlineServerName : onlineServers) { if (onlineServerName.equals(server.name)) { final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput(); pluginMessageWriter.writeUTF("Connect"); pluginMessageWriter.writeUTF(server.name); - ((BukkitPlayer) player).sendPluginMessage(HuskHomesBukkit.getInstance(), + ((BukkitPlayer) onlineUser).sendPluginMessage(BukkitHuskHomes.getInstance(), BUNGEE_PLUGIN_CHANNEL_NAME, pluginMessageWriter.toByteArray()); return true; @@ -98,7 +98,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } @Override - public CompletableFuture sendMessage(@NotNull Player sender, @NotNull Message message) { + public CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { final CompletableFuture repliedMessage = new CompletableFuture<>(); processingMessages.put(message.uuid, repliedMessage); sendPluginMessage((BukkitPlayer) sender, message); @@ -106,7 +106,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi } @Override - protected CompletableFuture sendReply(@NotNull Player replier, @NotNull Message reply) { + protected CompletableFuture sendReply(@NotNull OnlineUser replier, @NotNull Message reply) { return sendPluginMessage((BukkitPlayer) replier, reply); } @@ -126,20 +126,20 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi messageWriter.write(messageByteOutputStream.toByteArray()); } } catch (IOException e) { - HuskHomesBukkit.getInstance().getLoggingAdapter().log(Level.SEVERE, + BukkitHuskHomes.getInstance().getLoggingAdapter().log(Level.SEVERE, "An error occurred dispatching a plugin message", e); } // Send the written message - player.sendPluginMessage(HuskHomesBukkit.getInstance(), + player.sendPluginMessage(BukkitHuskHomes.getInstance(), BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray()); }); } @Override public void terminate() { - Bukkit.getMessenger().unregisterIncomingPluginChannel(HuskHomesBukkit.getInstance()); - Bukkit.getMessenger().unregisterIncomingPluginChannel(HuskHomesBukkit.getInstance()); + Bukkit.getMessenger().unregisterIncomingPluginChannel(BukkitHuskHomes.getInstance()); + Bukkit.getMessenger().unregisterIncomingPluginChannel(BukkitHuskHomes.getInstance()); } @Override @@ -168,7 +168,7 @@ public class PluginMessenger extends NetworkMessenger implements PluginMessageLi handleMessage(BukkitPlayer.adapt(player), message); } catch (IOException e) { - HuskHomesBukkit.getInstance().getLoggingAdapter().log(Level.SEVERE, + BukkitHuskHomes.getInstance().getLoggingAdapter().log(Level.SEVERE, "Failed to read an inbound plugin message", e); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java b/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java index 6c30d4c3..b2d2709d 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/messenger/RedisMessenger.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.messenger; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.player.BukkitPlayer; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.redis.RedisWorker; import org.jetbrains.annotations.NotNull; import redis.clients.jedis.Jedis; @@ -53,7 +53,7 @@ public class RedisMessenger extends PluginMessenger { } @Override - public CompletableFuture sendMessage(@NotNull Player sender, @NotNull Message message) { + public CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message) { final CompletableFuture repliedMessage = new CompletableFuture<>(); processingMessages.put(message.uuid, repliedMessage); redisWorker.sendMessage(message); @@ -61,7 +61,7 @@ public class RedisMessenger extends PluginMessenger { } @Override - protected CompletableFuture sendReply(@NotNull Player replier, @NotNull Message reply) { + protected CompletableFuture sendReply(@NotNull OnlineUser replier, @NotNull Message reply) { return redisWorker.sendMessage(reply); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java index e44bfe72..b523d5f9 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java +++ b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java @@ -2,12 +2,14 @@ package net.william278.huskhomes.player; import de.themoep.minedown.MineDown; import io.papermc.lib.PaperLib; -import net.william278.huskhomes.HuskHomesBukkit; +import net.md_5.bungee.api.ChatMessageType; +import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.TeleportResult; import net.william278.huskhomes.util.EconomyUnsupportedException; import org.bukkit.Bukkit; +import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; @@ -16,84 +18,90 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; -public class BukkitPlayer implements Player { +/** + * Bukkit implementation of an {@link OnlineUser} + */ +public class BukkitPlayer extends OnlineUser { - private final org.bukkit.entity.Player bukkitPlayer; + private final Player player; - private BukkitPlayer(org.bukkit.entity.Player bukkitPlayer) { - this.bukkitPlayer = bukkitPlayer; + private BukkitPlayer(@NotNull Player player) { + super(player.getUniqueId(), player.getName()); + this.player = player; } - public static Optional get(@NotNull User user) { - return get(user.uuid); - } - - public static Optional get(@NotNull UUID uuid) { - final org.bukkit.entity.Player bukkitPlayer = Bukkit.getPlayer(uuid); - if (bukkitPlayer != null) { - return Optional.of(adapt(bukkitPlayer)); - } - return Optional.empty(); - } - - public static Optional get(@NotNull String username) { - final org.bukkit.entity.Player bukkitPlayer = Bukkit.getPlayerExact(username); - if (bukkitPlayer != null) { - return Optional.of(adapt(bukkitPlayer)); - } - return Optional.empty(); - } - - public static BukkitPlayer adapt(@NotNull org.bukkit.entity.Player player) { + /** + * Adapt a {@link Player} to a {@link OnlineUser} + * @param player the online {@link Player} to adapt + * @return the adapted {@link OnlineUser} + */ + public static BukkitPlayer adapt(@NotNull Player player) { return new BukkitPlayer(player); } - public org.bukkit.entity.Player toBukkitPlayer() { - return bukkitPlayer; + /** + * Get an online {@link BukkitPlayer} by their UUID + * @param uuid the UUID of the player to find + * @return an {@link Optional} containing the {@link BukkitPlayer} if found; {@link Optional#empty()} otherwise + */ + public static Optional get(@NotNull UUID uuid) { + final Player player = Bukkit.getPlayer(uuid); + if (player != null) { + return Optional.of(adapt(player)); + } + return Optional.empty(); } - @Override - public String getName() { - return bukkitPlayer.getName(); - } - - @Override - public UUID getUuid() { - return bukkitPlayer.getUniqueId(); + /** + * Get an online {@link BukkitPlayer} by their exact username + * @param username the UUID of the player to find + * @return an {@link Optional} containing the {@link BukkitPlayer} if found; {@link Optional#empty()} otherwise + */ + public static Optional get(@NotNull String username) { + final Player player = Bukkit.getPlayerExact(username); + if (player != null) { + return Optional.of(adapt(player)); + } + return Optional.empty(); } @Override public CompletableFuture getPosition() { final Location location = getLocation(); - return HuskHomesBukkit.getInstance().getServer(this).thenApplyAsync(server -> new Position( + return BukkitHuskHomes.getInstance().getServer(this).thenApplyAsync(server -> new Position( location.x, location.y, location.z, location.yaw, location.pitch, location.world, server)); } @Override public Location getLocation() { - return HuskHomesBukkit.BukkitAdapter.adaptLocation(bukkitPlayer.getLocation()); + return BukkitHuskHomes.BukkitAdapter.adaptLocation(player.getLocation()); } @Override public double getHealth() { - return bukkitPlayer.getHealth(); + return player.getHealth(); } @Override public boolean hasPermission(@NotNull String node) { - return bukkitPlayer.hasPermission(node); + return player.hasPermission(node); + } + + @Override + public void sendActionBar(@NotNull MineDown mineDown) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, mineDown.replace().toComponent()); } @Override public void sendMessage(@NotNull MineDown mineDown) { - bukkitPlayer.spigot().sendMessage(mineDown.toComponent()); + player.spigot().sendMessage(mineDown.replace().toComponent()); } @Override public CompletableFuture teleport(Location location) { return CompletableFuture.supplyAsync(() -> { - final Optional bukkitLocation = HuskHomesBukkit.BukkitAdapter.adaptLocation(location); + final Optional bukkitLocation = BukkitHuskHomes.BukkitAdapter.adaptLocation(location); if (bukkitLocation.isEmpty()) { return TeleportResult.FAILED_INVALID_WORLD; } @@ -101,10 +109,9 @@ public class BukkitPlayer implements Player { if (!bukkitLocation.get().getWorld().getWorldBorder().isInside(bukkitLocation.get())) { return TeleportResult.FAILED_ILLEGAL_COORDINATES; } - System.out.println("teleport 5"); final CompletableFuture resultCompletableFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(HuskHomesBukkit.getInstance(), () -> - PaperLib.teleportAsync(bukkitPlayer, bukkitLocation.get(), PlayerTeleportEvent.TeleportCause.COMMAND) + Bukkit.getScheduler().runTask(BukkitHuskHomes.getInstance(), () -> + PaperLib.teleportAsync(player, bukkitLocation.get(), PlayerTeleportEvent.TeleportCause.COMMAND) .thenAccept(result -> { if (result) { resultCompletableFuture.completeAsync(() -> TeleportResult.COMPLETED_LOCALLY); @@ -128,18 +135,18 @@ public class BukkitPlayer implements Player { @Override public double getEconomyBalance() throws EconomyUnsupportedException { - return 0; + return 0; //todo } @Override public void deductEconomyBalance() throws EconomyUnsupportedException { - + //todo } /** * Send a Bukkit plugin message */ public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, @NotNull byte[] message) { - bukkitPlayer.sendPluginMessage(source, channel, message); + player.sendPluginMessage(source, channel, message); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java b/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java index 957cb937..202fae96 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java +++ b/bukkit/src/main/java/net/william278/huskhomes/teleport/BukkitTeleportManager.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.teleport; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.HuskHomesBukkit; +import net.william278.huskhomes.BukkitHuskHomes; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull; @@ -33,7 +33,7 @@ public class BukkitTeleportManager extends TeleportManager { this.cancel(); } } - }.runTaskTimerAsynchronously((HuskHomesBukkit) plugin, 0L, 20L); + }.runTaskTimerAsynchronously((BukkitHuskHomes) plugin, 0L, 20L); return teleportCompletableFuture.join(); }); diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java index 7e8181ed..0293ef6b 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java @@ -1,37 +1,46 @@ package net.william278.huskhomes.util; +import de.themoep.minedown.MineDown; +import net.md_5.bungee.api.chat.TextComponent; +import org.jetbrains.annotations.NotNull; + import java.util.logging.Level; -public class BukkitLogger implements Logger { +public class BukkitLogger extends Logger { private final java.util.logging.Logger logger; - public BukkitLogger(java.util.logging.Logger logger) { + public BukkitLogger(@NotNull java.util.logging.Logger logger) { this.logger = logger; } @Override - public void log(Level level, String message, Exception e) { + public void log(@NotNull Level level, @NotNull String message, @NotNull Exception e) { logger.log(level, message, e); } @Override - public void log(Level level, String message) { + public void log(@NotNull Level level, @NotNull String message) { logger.log(level, message); } @Override - public void info(String message) { + public void log(@NotNull Level level, @NotNull MineDown mineDown) { + logger.log(level, TextComponent.toLegacyText(mineDown.toComponent())); + } + + @Override + public void info(@NotNull String message) { logger.info(message); } @Override - public void severe(String message) { + public void severe(@NotNull String message) { logger.severe(message); } @Override - public void config(String message) { + public void config(@NotNull String message) { logger.config(message); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java index cdfee69e..ac6d19e7 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java @@ -1,15 +1,15 @@ package net.william278.huskhomes.util; -import net.william278.huskhomes.HuskHomesBukkit; +import net.william278.huskhomes.BukkitHuskHomes; import java.io.File; import java.io.InputStream; public class BukkitResourceReader implements ResourceReader { - private final HuskHomesBukkit plugin; + private final BukkitHuskHomes plugin; - public BukkitResourceReader(HuskHomesBukkit plugin) { + public BukkitResourceReader(BukkitHuskHomes plugin) { this.plugin = plugin; } diff --git a/bukkit/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml index d971aedc..a90911da 100644 --- a/bukkit/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -1,7 +1,7 @@ name: 'HuskHomes' description: 'A powerful, intuitive and flexible teleportation suite' author: 'William278' -main: 'net.william278.huskhomes.HuskHomesBukkit' +main: 'net.william278.huskhomes.BukkitHuskHomes' version: '${version}' api-version: 1.16 libraries: diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 175cc66b..82679349 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -3,14 +3,15 @@ package net.william278.huskhomes; import net.william278.huskhomes.cache.Cache; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.data.Database; +import net.william278.huskhomes.database.Database; import net.william278.huskhomes.messenger.NetworkMessenger; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.util.Logger; +import net.william278.huskhomes.util.Version; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,20 +29,23 @@ public interface HuskHomes { * * @return the {@link Logger} implementation to use */ + @NotNull Logger getLoggingAdapter(); /** - * The {@link Set} of online {@link Player}s on this server + * The {@link Set} of online {@link OnlineUser}s on this server * - * @return a {@link Set} of currently online {@link Player}s + * @return a {@link Set} of currently online {@link OnlineUser}s */ - List getOnlinePlayers(); + @NotNull + List getOnlinePlayers(); /** * The plugin {@link Settings} loaded from file * * @return the plugin {@link Settings} */ + @NotNull Settings getSettings(); /** @@ -49,6 +53,7 @@ public interface HuskHomes { * * @return The plugin {@link Locales} */ + @NotNull Locales getLocales(); /** @@ -56,6 +61,7 @@ public interface HuskHomes { * * @return the {@link Database} implementation for accessing data */ + @NotNull Database getDatabase(); /** @@ -63,6 +69,7 @@ public interface HuskHomes { * * @return the plugin {@link Cache} */ + @NotNull Cache getCache(); /** @@ -70,6 +77,7 @@ public interface HuskHomes { * * @return the {@link TeleportManager} implementation */ + @NotNull TeleportManager getTeleportManager(); /** @@ -77,6 +85,7 @@ public interface HuskHomes { * * @return the {@link SavedPositionManager} implementation */ + @NotNull SavedPositionManager getSavedPositionManager(); /** @@ -92,7 +101,7 @@ public interface HuskHomes { * * @return The server */ - CompletableFuture getServer(@NotNull Player requester); + CompletableFuture getServer(@NotNull OnlineUser requester); /** * Returns true if the position is a valid location on the server @@ -103,22 +112,33 @@ public interface HuskHomes { boolean isValidPositionOnServer(Position position); /** - * (Re)-load config and message data from files + * Returns the plugin version + * + * @return the plugin {@link Version} */ - void loadConfigData(); + @NotNull + Version getPluginVersion(); /** - * Get the HuskHomes plugin version + * Returns the Minecraft version implementation * - * @return the HuskHomes plugin version string + * @return the Minecraft {@link Version} */ - String getPluginVersion(); + @NotNull + Version getMinecraftVersion(); /** * Get the platform type (e.g. Spigot, Paper etc) * * @return the type of server platform string */ + @NotNull String getPlatformType(); + /** + * Reloads the {@link Settings} and {@link Locales} from their respective config files + * + * @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful + */ + CompletableFuture reload(); } diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomesInitializationException.java b/common/src/main/java/net/william278/huskhomes/HuskHomesInitializationException.java new file mode 100644 index 00000000..e4746932 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/HuskHomesInitializationException.java @@ -0,0 +1,12 @@ +package net.william278.huskhomes; + +import org.jetbrains.annotations.NotNull; + +/** + * Indicates an exception occurred while initialising the HuskHomes plugin + */ +public class HuskHomesInitializationException extends RuntimeException { + public HuskHomesInitializationException(@NotNull String message) { + super(message); + } +} diff --git a/common/src/main/java/net/william278/huskhomes/cache/Cache.java b/common/src/main/java/net/william278/huskhomes/cache/Cache.java index 77610d1c..20938392 100644 --- a/common/src/main/java/net/william278/huskhomes/cache/Cache.java +++ b/common/src/main/java/net/william278/huskhomes/cache/Cache.java @@ -2,9 +2,9 @@ package net.william278.huskhomes.cache; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.data.Database; +import net.william278.huskhomes.database.Database; import net.william278.huskhomes.list.ChatList; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -75,7 +75,7 @@ public class Cache { * * @param plugin the implementing plugin */ - public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull Player requester) { + public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) { if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { assert plugin.getNetworkMessenger() != null; CompletableFuture.runAsync(() -> plugin.getNetworkMessenger(). @@ -85,7 +85,7 @@ public class Cache { })); } else { players.clear(); - players.addAll(plugin.getOnlinePlayers().stream().map(Player::getName).toList()); + players.addAll(plugin.getOnlinePlayers().stream().map(onlineUser -> onlineUser.username).toList()); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java index 1e3582c0..684515b7 100644 --- a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -13,11 +13,11 @@ public class BackCommand extends CommandBase { } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { - plugin.getDatabase().getLastPosition(new User(player)).thenAccept(lastPosition -> - lastPosition.ifPresentOrElse(position -> plugin.getTeleportManager().teleport(player, position) - .thenAccept(result -> plugin.getTeleportManager().finishTeleport(player, result)), - () -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(player::sendMessage))); + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition -> + lastPosition.ifPresentOrElse(position -> plugin.getTeleportManager().teleport(onlineUser, position) + .thenAccept(result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)), + () -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage))); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/CommandBase.java b/common/src/main/java/net/william278/huskhomes/command/CommandBase.java index 6d7fd206..b4d4f377 100644 --- a/common/src/main/java/net/william278/huskhomes/command/CommandBase.java +++ b/common/src/main/java/net/william278/huskhomes/command/CommandBase.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -41,10 +41,10 @@ public abstract class CommandBase { /** * Fires when the command is executed * - * @param player {@link Player} executing the command + * @param onlineUser {@link OnlineUser} executing the command * @param args Command arguments */ - public abstract void onExecute(@NotNull Player player, @NotNull String[] args); + public abstract void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args); /** * Returns the localised description string of this command diff --git a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java index b9e138d5..3ee2f120 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.RegexUtil; @@ -17,15 +17,15 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { - final User user = new User(player); + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + switch (args.length) { - case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> { + case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> { if (homes.size() == 1) { - homes.stream().findFirst().ifPresent(home -> plugin.getSavedPositionManager().deleteHome(user, home.meta.name)); + homes.stream().findFirst().ifPresent(home -> plugin.getSavedPositionManager().deleteHome(onlineUser, home.meta.name)); } else { plugin.getLocales().getLocale("error_invalid_syntax", "/delhome ") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } }); case 1 -> { @@ -35,23 +35,23 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso final String ownersHomeName = homeName.split("\\.")[1]; plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData .ifPresentOrElse(userData -> { - if (!userData.uuid.equals(player.getUuid())) { - if (!player.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) { + if (!userData.uuid.equals(onlineUser.uuid)) { + if (!onlineUser.hasPermission(Permission.COMMAND_DELETE_HOME_OTHER.node)) { plugin.getLocales().getLocale("error_no_permission") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); return; } } plugin.getSavedPositionManager().deleteHome(userData, ownersHomeName); }, () -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName) - .ifPresent(player::sendMessage))); + .ifPresent(onlineUser::sendMessage))); } else { - plugin.getSavedPositionManager().deleteHome(user, homeName); + plugin.getSavedPositionManager().deleteHome(onlineUser, homeName); } } default -> plugin.getLocales().getLocale("error_invalid_syntax", "/delhome ") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } @@ -61,8 +61,8 @@ public class DelHomeCommand extends CommandBase implements TabCompletable, Conso } @Override - public List onTabComplete(@NotNull Player player, @NotNull String[] args) { - return plugin.getCache().homes.get(player.getUuid()).stream() + public List onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + return plugin.getCache().homes.get(onlineUser.uuid).stream() .filter(s -> s.startsWith(args.length >= 1 ? args[0] : "")) .sorted().collect(Collectors.toList()); } diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index 4520520b..8b7f0bb9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -1,10 +1,8 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.User; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; -import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -17,12 +15,12 @@ public class DelWarpCommand extends CommandBase implements TabCompletable, Conso } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { if (args.length == 1) { plugin.getSavedPositionManager().deleteWarp(args[0]); } else { plugin.getLocales().getLocale("error_invalid_syntax", "/delwarp ") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } @@ -32,7 +30,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable, Conso } @Override - public List onTabComplete(@NotNull Player player, @NotNull String[] args) { + public List onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) { return plugin.getCache().warps.stream() .filter(s -> s.startsWith(args.length >= 1 ? args[0] : "")) .sorted().collect(Collectors.toList()); diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index 49897efd..4da6f839 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -2,8 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.list.PrivateHomeList; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.User; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; @@ -18,18 +17,18 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { - final User user = new User(player); + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + switch (args.length) { - case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> { + case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> { switch (homes.size()) { - case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage); - case 1 -> plugin.getTeleportManager().teleport(player, homes.get(0)).thenAccept(result -> - plugin.getTeleportManager().finishTeleport(player, result)); + case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage); + case 1 -> plugin.getTeleportManager().teleport(onlineUser, homes.get(0)).thenAccept(result -> + plugin.getTeleportManager().finishTeleport(onlineUser, result)); default -> { - final PrivateHomeList homeList = new PrivateHomeList(homes, user, plugin); - plugin.getCache().positionLists.put(user.uuid, homeList); - homeList.getDisplay(1).forEach(player::sendMessage); + final PrivateHomeList homeList = new PrivateHomeList(homes, onlineUser, plugin); + plugin.getCache().positionLists.put(onlineUser.uuid, homeList); + homeList.getDisplay(1).forEach(onlineUser::sendMessage); } } }); @@ -39,15 +38,15 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE final String ownerName = homeName.split("\\.")[0]; final String ownersHomeName = homeName.split("\\.")[1]; plugin.getDatabase().getUserByName(ownerName).thenAccept(optionalUserData -> optionalUserData - .ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(player, userData, ownersHomeName), + .ifPresentOrElse(userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData, ownersHomeName), () -> plugin.getLocales().getLocale("error_home_invalid_other", ownerName, homeName) - .ifPresent(player::sendMessage))); + .ifPresent(onlineUser::sendMessage))); } else { - plugin.getTeleportManager().teleportToHome(player, user, homeName); + plugin.getTeleportManager().teleportToHome(onlineUser, onlineUser, homeName); } } default -> plugin.getLocales().getLocale("error_invalid_syntax", "/home [name]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } @@ -57,8 +56,8 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE } @Override - public List onTabComplete(@NotNull Player player, @NotNull String[] args) { - return plugin.getCache().homes.get(player.getUuid()).stream() + public List onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + return plugin.getCache().homes.get(onlineUser.uuid).stream() .filter(s -> s.startsWith(args.length >= 1 ? args[0] : "")) .sorted().collect(Collectors.toList()); } diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java index 1cbf5e69..a670f7ed 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.list.PrivateHomeList; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -13,62 +13,62 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable { } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { switch (args.length) { - case 0 -> showHomeList(player, player.getName(), 1); + case 0 -> showHomeList(onlineUser, onlineUser.username, 1); case 1 -> { try { int pageNumber = Integer.parseInt(args[0]); - showHomeList(player, player.getName(), pageNumber); + showHomeList(onlineUser, onlineUser.username, pageNumber); } catch (NumberFormatException e) { - showHomeList(player, args[0], 1); + showHomeList(onlineUser, args[0], 1); } } case 2 -> { try { int pageNumber = Integer.parseInt(args[1]); - showHomeList(player, args[0], pageNumber); + showHomeList(onlineUser, args[0], pageNumber); } catch (NumberFormatException e) { plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [player] [page]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } default -> plugin.getLocales().getLocale("error_invalid_syntax", "/homelist [page]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } /** - * Show a (cached) list of a {@link Player}'s homes + * Show a (cached) list of a {@link OnlineUser}'s homes * - * @param player the user to display the homes to + * @param onlineUser the user to display the homes to * @param homeOwner the user whose homes should be displayed * @param pageNumber page number to display */ - private void showHomeList(@NotNull Player player, @NotNull String homeOwner, int pageNumber) { - if (plugin.getCache().positionLists.containsKey(player.getUuid())) { - if (plugin.getCache().positionLists.get(player.getUuid()) instanceof PrivateHomeList privateHomeList) { - privateHomeList.getDisplay(pageNumber).forEach(player::sendMessage); + private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) { + if (plugin.getCache().positionLists.containsKey(onlineUser.uuid)) { + if (plugin.getCache().positionLists.get(onlineUser.uuid) instanceof PrivateHomeList privateHomeList) { + privateHomeList.getDisplay(pageNumber).forEach(onlineUser::sendMessage); return; } } plugin.getDatabase().getUserByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(user -> { - if (!user.uuid.equals(player.getUuid())) { - if (!player.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); + if (!user.uuid.equals(onlineUser.uuid)) { + if (!onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { + plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); return; } } plugin.getDatabase().getHomes(user).thenAccept(homes -> { if (homes.isEmpty()) { - plugin.getLocales().getLocale("error_no_homes_set").ifPresent(player::sendMessage); + plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage); return; } final PrivateHomeList homeList = new PrivateHomeList(homes, user, plugin); plugin.getCache().positionLists.put(user.uuid, homeList); - homeList.getDisplay(pageNumber).forEach(player::sendMessage); + homeList.getDisplay(pageNumber).forEach(onlineUser::sendMessage); }); - }, () -> plugin.getLocales().getLocale("error_invalid_user").ifPresent(player::sendMessage))); + }, () -> plugin.getLocales().getLocale("error_invalid_user").ifPresent(onlineUser::sendMessage))); } 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 379a7420..d7fbaab1 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -2,7 +2,7 @@ package net.william278.huskhomes.command; import de.themoep.minedown.MineDown; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.util.Permission; @@ -15,28 +15,28 @@ public class SetHomeCommand extends CommandBase { } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { - final User user = new User(player); + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { + switch (args.length) { - case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> { + case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> { if (homes.isEmpty()) { - setHome(player, user, "home"); + setHome(onlineUser, onlineUser, "home"); } else { plugin.getLocales().getLocale("error_invalid_syntax", "/sethome ") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } }); - case 1 -> setHome(player, user, args[0]); + case 1 -> setHome(onlineUser, onlineUser, args[0]); default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome ") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } - private void setHome(@NotNull Player player, @NotNull User user, @NotNull String homeName) { - player.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setHome(new PositionMeta(homeName, + private void setHome(@NotNull OnlineUser onlineUser, @NotNull User user, @NotNull String homeName) { + onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setHome(new PositionMeta(homeName, plugin.getLocales().getRawLocale("home_default_description", user.username).orElse("")), user, position).thenAccept(setResult -> - player.sendMessage(switch (setResult.resultType()) { + onlineUser.sendMessage(switch (setResult.resultType()) { case SUCCESS -> { assert setResult.setPosition() != null; yield plugin.getLocales().getLocale("set_home_success", setResult.setPosition().meta.name) 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 f0dd038b..91d60ca7 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java @@ -2,8 +2,7 @@ package net.william278.huskhomes.command; import de.themoep.minedown.MineDown; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.User; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -15,24 +14,20 @@ public class SetWarpCommand extends CommandBase { } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { - final User user = new User(player); - switch (args.length) { - case 0 -> plugin.getDatabase().getHomes(user).thenAccept(homes -> { - plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp ") - .ifPresent(player::sendMessage); - }); - case 1 -> setWarp(player, args[0]); - default -> plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp ") - .ifPresent(player::sendMessage); + 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); } } - private void setWarp(@NotNull Player player, @NotNull String warpName) { - player.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setWarp(new PositionMeta(warpName, + private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) { + onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setWarp(new PositionMeta(warpName, plugin.getLocales().getRawLocale("warp_default_description").orElse("")), position).thenAccept(setResult -> - player.sendMessage(switch (setResult.resultType()) { + onlineUser.sendMessage(switch (setResult.resultType()) { case SUCCESS -> { assert setResult.setPosition() != null; yield plugin.getLocales().getLocale("set_warp_success", setResult.setPosition().meta.name) diff --git a/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java b/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java index 22988a6c..870f941d 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java +++ b/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java @@ -1,6 +1,6 @@ package net.william278.huskhomes.command; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -13,10 +13,10 @@ public interface TabCompletable { /** * What should be returned when the player attempts to TAB-complete the command * - * @param player {@link Player} doing the TAB completion + * @param onlineUser {@link OnlineUser} doing the TAB completion * @param args Current command arguments * @return List of String arguments to offer TAB suggestions */ - List onTabComplete(@NotNull Player player, @NotNull String[] args); + List onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args); } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index 87689150..ee13c6b4 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -15,18 +15,18 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { if (args.length == 1) { final String warpName = args[0]; - plugin.getTeleportManager().teleportToWarp(player, warpName); + plugin.getTeleportManager().teleportToWarp(onlineUser, warpName); } else { plugin.getLocales().getLocale("error_invalid_syntax", "/warp [name]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } @Override - public List onTabComplete(@NotNull Player player, @NotNull String[] args) { + public List onTabComplete(@NotNull OnlineUser onlineUser, @NotNull String[] args) { return plugin.getCache().warps.stream() .filter(s -> s.startsWith(args.length >= 1 ? args[0] : "")) .sorted().collect(Collectors.toList()); diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index 2e7950e6..17c60d04 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -2,8 +2,7 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.list.WarpList; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.User; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.util.Permission; import org.jetbrains.annotations.NotNull; @@ -14,45 +13,45 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable { } @Override - public void onExecute(@NotNull Player player, @NotNull String[] args) { + public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { switch (args.length) { - case 0 -> showWarpList(player, 1); + case 0 -> showWarpList(onlineUser, 1); case 1 -> { try { int pageNumber = Integer.parseInt(args[0]); - showWarpList(player, pageNumber); + showWarpList(onlineUser, pageNumber); } catch (NumberFormatException e) { plugin.getLocales().getLocale("error_invalid_syntax", "/warplist [page]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } default -> plugin.getLocales().getLocale("error_invalid_syntax", "/warplist [page]") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } /** * Show a (cached) list of server warps * - * @param player the user to display warps to + * @param onlineUser the user to display warps to * @param pageNumber page number to display */ - private void showWarpList(@NotNull Player player, int pageNumber) { - if (plugin.getCache().positionLists.containsKey(player.getUuid())) { - if (plugin.getCache().positionLists.get(player.getUuid()) instanceof WarpList warpList) { - warpList.getDisplay(pageNumber).forEach(player::sendMessage); + private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) { + if (plugin.getCache().positionLists.containsKey(onlineUser.uuid)) { + if (plugin.getCache().positionLists.get(onlineUser.uuid) instanceof WarpList warpList) { + warpList.getDisplay(pageNumber).forEach(onlineUser::sendMessage); return; } } - final User user = new User(player); + plugin.getDatabase().getWarps().thenAccept(warps -> { if (warps.isEmpty()) { - plugin.getLocales().getLocale("error_no_warps_set").ifPresent(player::sendMessage); + plugin.getLocales().getLocale("error_no_warps_set").ifPresent(onlineUser::sendMessage); return; } final WarpList warpList = new WarpList(warps, plugin); - plugin.getCache().positionLists.put(user.uuid, warpList); - warpList.getDisplay(pageNumber).forEach(player::sendMessage); + plugin.getCache().positionLists.put(onlineUser.uuid, warpList); + warpList.getDisplay(pageNumber).forEach(onlineUser::sendMessage); }); } 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 400f8968..2184d0d1 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -114,7 +114,7 @@ public class Settings { public enum ConfigOption { LANGUAGE("language", OptionType.STRING, "en-gb"), CHECK_FOR_UPDATES("check_for_updates", OptionType.BOOLEAN, true), - + DEBUG_LOGGING("debug_logging", OptionType.BOOLEAN, false), DATA_STORAGE_TYPE("data_storage_options.storage_type", OptionType.STRING, "SQLite"), DATABASE_HOST("data_storage_options.mysql_credentials.host", OptionType.STRING, "localhost"), DATABASE_PORT("data_storage_options.mysql_credentials.port", OptionType.INTEGER, 3306), diff --git a/common/src/main/java/net/william278/huskhomes/data/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java similarity index 98% rename from common/src/main/java/net/william278/huskhomes/data/Database.java rename to common/src/main/java/net/william278/huskhomes/database/Database.java index 81282a0e..d16e3611 100644 --- a/common/src/main/java/net/william278/huskhomes/data/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -1,7 +1,6 @@ -package net.william278.huskhomes.data; +package net.william278.huskhomes.database; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.player.Player; import net.william278.huskhomes.player.User; import net.william278.huskhomes.player.UserData; import net.william278.huskhomes.position.*; @@ -172,7 +171,7 @@ public abstract class Database { * * @return A future returning void when complete */ - public abstract CompletableFuture initialize(); + public abstract boolean initialize(); /** * (Internal use only) - Sets a position to the position table in the database @@ -215,12 +214,12 @@ public abstract class Database { protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException; /** - * Ensure a {@link Player} has a {@link UserData} entry in the database and that their username is up-to-date + * Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date * - * @param player The {@link Player} to ensure + * @param user The {@link User} to ensure * @return A future returning void when complete */ - public abstract CompletableFuture ensureUser(@NotNull Player player); + public abstract CompletableFuture ensureUser(@NotNull User user); /** * Get a user by their username (case-insensitive) diff --git a/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java similarity index 97% rename from common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java rename to common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index e9211b8b..6fdf7f90 100644 --- a/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -1,8 +1,8 @@ -package net.william278.huskhomes.data; +package net.william278.huskhomes.database; import com.zaxxer.hikari.HikariDataSource; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.player.UserData; import net.william278.huskhomes.position.*; @@ -90,8 +90,8 @@ public class MySqlDatabase extends Database { } @Override - public CompletableFuture initialize() { - return CompletableFuture.runAsync(() -> { + public boolean initialize() { + try { // Create jdbc driver connection url final String jdbcUrl = "jdbc:mysql://" + mySqlHost + ":" + mySqlPort + "/" + mySqlDatabaseName + mySqlConnectionParameters; dataSource = new HikariDataSource(); @@ -118,10 +118,14 @@ public class MySqlDatabase extends Database { statement.execute(tableCreationStatement); } } + return true; } catch (SQLException | IOException e) { getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e); } - }); + } catch (Exception e) { + getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); + } + return false; } @Override @@ -202,10 +206,10 @@ public class MySqlDatabase extends Database { updatePosition(positionId, position, connection); try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%saved_positions_table%` - SET `name`=?, - `description`=? - WHERE `id`=?;"""))) { + UPDATE `%saved_positions_table%` + SET `name`=?, + `description`=? + WHERE `id`=?;"""))) { updateStatement.setString(1, position.meta.name); updateStatement.setString(2, position.meta.description); updateStatement.setInt(3, savedPositionId); @@ -216,10 +220,10 @@ public class MySqlDatabase extends Database { } @Override - public CompletableFuture ensureUser(@NotNull Player player) { - return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser -> + public CompletableFuture ensureUser(@NotNull User onlineUser) { + return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(existingUser -> { - if (!existingUser.username.equals(player.getName())) { + if (!existingUser.username.equals(onlineUser.username)) { // Update a player's name if it has changed in the database try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" @@ -227,11 +231,11 @@ public class MySqlDatabase extends Database { SET `username`=? WHERE `uuid`=?"""))) { - statement.setString(1, player.getName()); + statement.setString(1, onlineUser.username); statement.setString(2, existingUser.uuid.toString()); statement.executeUpdate(); } - getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username + " -> " + player.getName() + ")"); + getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")"); } catch (SQLException e) { getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -244,8 +248,8 @@ public class MySqlDatabase extends Database { INSERT INTO `%players_table%` (`uuid`,`username`) VALUES (?,?);"""))) { - statement.setString(1, player.getUuid().toString()); - statement.setString(2, player.getName()); + statement.setString(1, onlineUser.uuid.toString()); + statement.setString(2, onlineUser.username); statement.executeUpdate(); } } catch (SQLException e) { diff --git a/common/src/main/java/net/william278/huskhomes/data/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java similarity index 98% rename from common/src/main/java/net/william278/huskhomes/data/SqLiteDatabase.java rename to common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 01dc26df..92654258 100644 --- a/common/src/main/java/net/william278/huskhomes/data/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -1,7 +1,7 @@ -package net.william278.huskhomes.data; +package net.william278.huskhomes.database; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.player.UserData; import net.william278.huskhomes.position.*; @@ -87,9 +87,9 @@ public class SqLiteDatabase extends Database { } @Override - public CompletableFuture initialize() { - return CompletableFuture.runAsync(() -> { - // Setup the connection + public boolean initialize() { + try { + // Set up the connection setConnection(); // Prepare database schema; make tables if they don't exist @@ -101,10 +101,14 @@ public class SqLiteDatabase extends Database { statement.execute(tableCreationStatement); } } + return true; } catch (SQLException | IOException e) { getLogger().log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e); } - }); + } catch (Exception e) { + getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); + } + return false; } @Override @@ -199,10 +203,10 @@ public class SqLiteDatabase extends Database { } @Override - public CompletableFuture ensureUser(@NotNull Player player) { - return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser -> + public CompletableFuture ensureUser(@NotNull User onlineUser) { + return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(existingUser -> { - if (!existingUser.username.equals(player.getName())) { + if (!existingUser.username.equals(onlineUser.username)) { // Update a player's name if it has changed in the database try { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" @@ -210,11 +214,11 @@ public class SqLiteDatabase extends Database { SET `username`=? WHERE `uuid`=?"""))) { - statement.setString(1, player.getName()); + statement.setString(1, onlineUser.username); statement.setString(2, existingUser.uuid.toString()); statement.executeUpdate(); } - getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username + " -> " + player.getName() + ")"); + getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")"); } catch (SQLException e) { getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -227,8 +231,8 @@ public class SqLiteDatabase extends Database { INSERT INTO `%players_table%` (`uuid`,`username`) VALUES (?,?);"""))) { - statement.setString(1, player.getUuid().toString()); - statement.setString(2, player.getName()); + statement.setString(1, onlineUser.uuid.toString()); + statement.setString(2, onlineUser.username); statement.executeUpdate(); } } catch (SQLException e) { diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java similarity index 51% rename from common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java rename to common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 8f8091aa..4dd47f9a 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -2,8 +2,7 @@ package net.william278.huskhomes.listener; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.player.User; +import net.william278.huskhomes.player.OnlineUser; import org.jetbrains.annotations.NotNull; import java.util.stream.Collectors; @@ -11,94 +10,101 @@ import java.util.stream.Collectors; /** * A handler for when events take place */ -public class EventProcessor { +public class EventListener { @NotNull protected final HuskHomes plugin; - public EventProcessor(@NotNull HuskHomes implementor) { + public EventListener(@NotNull HuskHomes implementor) { this.plugin = implementor; } /** - * Handle when a {@link Player} joins the server + * Handle when a {@link OnlineUser} joins the server * - * @param player the joining {@link Player} + * @param onlineUser the joining {@link OnlineUser} */ - public void onPlayerJoin(@NotNull Player player) { + public void onPlayerJoin(@NotNull OnlineUser onlineUser) { // Ensure the player is present on the database first - plugin.getDatabase().ensureUser(player).thenRun(() -> { + plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> { // If the server is in proxy mode, check if the player is teleporting cross-server and handle if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { - plugin.getDatabase().getCurrentTeleport(new User(player)) + plugin.getDatabase().getCurrentTeleport(onlineUser) .thenAccept(teleport -> teleport.ifPresent(currentTeleport -> // Teleport the player locally - player.teleport(currentTeleport.target).thenAccept(teleportResult -> { + onlineUser.teleport(currentTeleport.target).thenAccept(teleportResult -> { if (!teleportResult.successful) { plugin.getLocales().getLocale("error_invalid_on_arrival") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } else { plugin.getLocales().getLocale("teleporting_complete") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } }))); // Update the player list assert plugin.getNetworkMessenger() != null; - plugin.getCache().updatePlayerList(plugin, player); + plugin.getCache().updatePlayerList(plugin, onlineUser); } // Cache this user's homes - plugin.getDatabase().getHomes(new User(player)).thenAccept(homes -> - plugin.getCache().homes.put(player.getUuid(), + plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> + plugin.getCache().homes.put(onlineUser.uuid, homes.stream().map(home -> home.meta.name).collect(Collectors.toList()))); // Ensure the server has been set if (plugin.getOnlinePlayers().size() == 1) { - plugin.getServer(player); + plugin.getServer(onlineUser); } }); } /** - * Handle when a {@link Player} leaves the server + * Handle when a {@link OnlineUser} leaves the server * - * @param player the leaving {@link Player} + * @param onlineUser the leaving {@link OnlineUser} */ - public void onPlayerLeave(@NotNull Player player) { + public void onPlayerLeave(@NotNull OnlineUser onlineUser) { // Remove this user's home cache - plugin.getCache().homes.remove(player.getUuid()); + plugin.getCache().homes.remove(onlineUser.uuid); // Update the player list if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { assert plugin.getNetworkMessenger() != null; plugin.getOnlinePlayers().stream().filter( - onlinePlayer -> !onlinePlayer.getUuid().equals(player.getUuid())) + onlinePlayer -> !onlinePlayer.uuid.equals(onlineUser.uuid)) .findAny().ifPresent(updater -> plugin.getCache().updatePlayerList(plugin, updater)); } // Set offline position - player.getPosition().thenAcceptAsync(position -> plugin.getDatabase().setOfflinePosition( - new User(player.getUuid(), player.getName()), position)); + onlineUser.getPosition().thenAcceptAsync(position -> plugin.getDatabase() + .setOfflinePosition(onlineUser, position)); } /** - * Handle when a {@link Player} dies + * Handle when a {@link OnlineUser} dies * - * @param player the {@link Player} who died + * @param onlineUser the {@link OnlineUser} who died */ - public void onPlayerDeath(@NotNull Player player) { - + public void onPlayerDeath(@NotNull OnlineUser onlineUser) { + //todo } /** - * Handle when a {@link Player} respawns after dying + * Handle when a {@link OnlineUser} respawns after dying * - * @param player the respawning {@link Player} + * @param onlineUser the respawning {@link OnlineUser} */ - public void onPlayerRespawn(@NotNull Player player) { + public void onPlayerRespawn(@NotNull OnlineUser onlineUser) { + //todo + } + /** + * Handle when the plugin is disabling (server is shutting down) + */ + public void handlePluginDisable() { + //todo } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java index 2dc105cb..9261249d 100644 --- a/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java +++ b/common/src/main/java/net/william278/huskhomes/messenger/NetworkMessenger.java @@ -2,8 +2,7 @@ package net.william278.huskhomes.messenger; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Server; import org.jetbrains.annotations.NotNull; @@ -25,17 +24,17 @@ public abstract class NetworkMessenger { protected HashMap> processingMessages; /** - * Future for processing {@link #getServerName(Player)} requests + * Future for processing {@link #getServerName(OnlineUser)} requests */ protected CompletableFuture serverNameRequest; /** - * Future for processing {@link #getOnlinePlayerNames(Player)} requests + * Future for processing {@link #getOnlinePlayerNames(OnlineUser)} requests */ protected CompletableFuture onlinePlayerNamesRequest; /** - * Future for processing {@link #getOnlineServers(Player)} requests + * Future for processing {@link #getOnlineServers(OnlineUser)} requests */ protected CompletableFuture onlineServersRequest; @@ -57,35 +56,35 @@ public abstract class NetworkMessenger { /** * Fetch a list of online player usernames from the proxy * - * @param requester {@link Player} to send the request + * @param requester {@link OnlineUser} to send the request * @return Future returning a {@link List} of usernames of players on the proxy network */ - public abstract CompletableFuture getOnlinePlayerNames(@NotNull Player requester); + public abstract CompletableFuture getOnlinePlayerNames(@NotNull OnlineUser requester); /** * Fetch the name of this server on the proxy network * - * @param requester {@link Player} to send the request + * @param requester {@link OnlineUser} to send the request * @return Future returning the name of this server on the network */ - public abstract CompletableFuture getServerName(@NotNull Player requester); + public abstract CompletableFuture getServerName(@NotNull OnlineUser requester); /** * Fetch a list of online server names proxy * - * @param requester {@link Player} to send the request + * @param requester {@link OnlineUser} to send the request * @return Future returning a {@link List} of online servers connected to the proxy network */ - public abstract CompletableFuture getOnlineServers(@NotNull Player requester); + public abstract CompletableFuture getOnlineServers(@NotNull OnlineUser requester); /** - * Send a {@link Player} to a target {@link Server} on the proxy network + * Send a {@link OnlineUser} to a target {@link Server} on the proxy network * - * @param server The {@link Server} to send the {@link Player} to + * @param server The {@link Server} to send the {@link OnlineUser} to * @return A future, returning {@code true} if the player was sent.

* If the player could not be sent (i.e. the server was offline), this will return {@code false} */ - public abstract CompletableFuture sendPlayer(@NotNull Player player, @NotNull Server server); + public abstract CompletableFuture sendPlayer(@NotNull OnlineUser onlineUser, @NotNull Server server); /** * Send a network {@link Message} to a target player on the proxy @@ -93,7 +92,7 @@ public abstract class NetworkMessenger { * @param message The {@link Message} to send * @return A future containing a reply to the {@link Message} that was sent */ - public abstract CompletableFuture sendMessage(@NotNull Player sender, @NotNull Message message); + public abstract CompletableFuture sendMessage(@NotNull OnlineUser sender, @NotNull Message message); /** * Send a reply to a received {@link Message} @@ -101,15 +100,15 @@ public abstract class NetworkMessenger { * @param reply The reply {@link Message} to send * @return A future completing when the message has been sent */ - protected abstract CompletableFuture sendReply(@NotNull Player replier, @NotNull Message reply); + protected abstract CompletableFuture sendReply(@NotNull OnlineUser replier, @NotNull Message reply); /** * Handle and action received network {@link Message}s * - * @param receiver The online {@link Player} receiving the message + * @param receiver The online {@link OnlineUser} receiving the message * @param message The received {@link Message} */ - protected final void handleMessage(@NotNull Player receiver, @NotNull Message message) { + protected final void handleMessage(@NotNull OnlineUser receiver, @NotNull Message message) { switch (message.kind) { // Handle a message and send reply case MESSAGE -> prepareReply(receiver, message).thenAccept(reply -> sendReply(receiver, message)); @@ -123,7 +122,7 @@ public abstract class NetworkMessenger { } } - private CompletableFuture prepareReply(@NotNull final Player receiver, @NotNull final Message message) { + private CompletableFuture prepareReply(@NotNull final OnlineUser receiver, @NotNull final Message message) { return CompletableFuture.supplyAsync(() -> { // Handle different message types and apply changes for reply message switch (message.type) { @@ -137,7 +136,7 @@ public abstract class NetworkMessenger { // Prepare reply message message.targetPlayer = message.sender; - message.sender = receiver.getName(); + message.sender = receiver.username; message.kind = Message.MessageKind.REPLY; return message; }); diff --git a/common/src/main/java/net/william278/huskhomes/player/Player.java b/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java similarity index 63% rename from common/src/main/java/net/william278/huskhomes/player/Player.java rename to common/src/main/java/net/william278/huskhomes/player/OnlineUser.java index 26348c0b..2e723b0e 100644 --- a/common/src/main/java/net/william278/huskhomes/player/Player.java +++ b/common/src/main/java/net/william278/huskhomes/player/OnlineUser.java @@ -3,7 +3,6 @@ package net.william278.huskhomes.player; import de.themoep.minedown.MineDown; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Server; import net.william278.huskhomes.teleport.TeleportResult; import net.william278.huskhomes.util.EconomyUnsupportedException; import org.jetbrains.annotations.NotNull; @@ -12,44 +11,35 @@ import java.util.UUID; import java.util.concurrent.CompletableFuture; /** - * A cross-platform representation of a player + * A cross-platform representation of a logged-in {@link User} */ -public interface Player { +public abstract class OnlineUser extends User { - /** - * Return the player's name - * - * @return the player's name - */ - String getName(); + public OnlineUser(@NotNull UUID uuid, @NotNull String username) { + super(uuid, username); + } - /** - * Return the player's {@link UUID} - * - * @return the player {@link UUID} - */ - UUID getUuid(); /** * Returns the current {@link Position} of this player * * @return the player's current {@link Position} */ - CompletableFuture getPosition(); + public abstract CompletableFuture getPosition(); /** * Returns the current local {@link Location} of this player * * @return the player's current {@link Location} on the server */ - Location getLocation(); + public abstract Location getLocation(); /** * Returns the health of this player * * @return the player's health points */ - double getHealth(); + public abstract double getHealth(); /** * Returns if the player has the permission node @@ -57,35 +47,43 @@ public interface Player { * @param node The permission node string * @return {@code true} if the player has the node; {@code false} otherwise */ - boolean hasPermission(@NotNull String node); + public abstract boolean hasPermission(@NotNull String node); /** - * Dispatch a MineDown-formatted message to this player + * Dispatch a MineDown-formatted action bar message to this player * * @param mineDown the parsed {@link MineDown} to send */ - void sendMessage(@NotNull MineDown mineDown); + public abstract void sendActionBar(@NotNull MineDown mineDown); + + + /** + * Dispatch a MineDown-formatted chat message to this player + * + * @param mineDown the parsed {@link MineDown} to send + */ + public abstract void sendMessage(@NotNull MineDown mineDown); /** * Teleport a player to the specified {@link Location} * * @param location the {@link Location} to teleport the player to */ - CompletableFuture teleport(Location location); + public abstract CompletableFuture teleport(Location location); /** * Returns the maximum number of homes this player can set * * @return a {@link CompletableFuture} providing the max number of homes this player can set */ - CompletableFuture getMaxHomes(); + public abstract CompletableFuture getMaxHomes(); /** * Returns the number of homes this player can set for free * * @return a {@link CompletableFuture} providing the max number of homes this player can set */ - CompletableFuture getFreeHomes(); + public abstract CompletableFuture getFreeHomes(); /** * Get this player's economy balance @@ -93,14 +91,14 @@ public interface Player { * @return the player's economy balance * @throws EconomyUnsupportedException if the economy integration is not enabled */ - double getEconomyBalance() throws EconomyUnsupportedException; + public abstract double getEconomyBalance() throws EconomyUnsupportedException; /** * Deduct money from this player's economy balance * * @throws EconomyUnsupportedException if the economy integration is not enabled */ - void deductEconomyBalance() throws EconomyUnsupportedException; + public abstract void deductEconomyBalance() throws EconomyUnsupportedException; } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/player/User.java b/common/src/main/java/net/william278/huskhomes/player/User.java index aaf08ebc..e8112cd5 100644 --- a/common/src/main/java/net/william278/huskhomes/player/User.java +++ b/common/src/main/java/net/william278/huskhomes/player/User.java @@ -5,13 +5,14 @@ import org.jetbrains.annotations.NotNull; import java.util.UUID; /** - * Represents persistently stored {@link User} data about a {@link Player}; uuid and username - * A {@link Player} may be retrieved from a user by the platform implementing classes + * Represents a user who has data saved in the database */ public class User { + @NotNull public final UUID uuid; + @NotNull public final String username; /** @@ -25,13 +26,4 @@ public class User { this.username = username; } - /** - * Get a user from an online {@link Player} - * - * @param player the online {@link Player} - */ - public User(Player player) { - this.uuid = player.getUuid(); - this.username = player.getName(); - } } diff --git a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java index 789ea004..e3fdd5fa 100644 --- a/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java +++ b/common/src/main/java/net/william278/huskhomes/position/SavedPositionManager.java @@ -1,7 +1,7 @@ package net.william278.huskhomes.position; import net.william278.huskhomes.cache.Cache; -import net.william278.huskhomes.data.Database; +import net.william278.huskhomes.database.Database; import net.william278.huskhomes.player.User; import net.william278.huskhomes.util.RegexUtil; import org.jetbrains.annotations.NotNull; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java index 099b4000..e9724965 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -4,7 +4,7 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.messenger.EmptyPayload; import net.william278.huskhomes.messenger.Message; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.User; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; @@ -32,74 +32,74 @@ public abstract class TeleportManager { } /** - * Teleport a {@link Player} to another {@link User}'s {@link Home} + * Teleport a {@link OnlineUser} to another {@link User}'s {@link Home} * - * @param player the {@link Player} to teleport + * @param onlineUser the {@link OnlineUser} to teleport * @param homeOwner the {@link User} who owns the home * @param homeName the name of the home */ - public void teleportToHome(@NotNull Player player, @NotNull User homeOwner, @NotNull String homeName) { + public void teleportToHome(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull String homeName) { plugin.getDatabase().getHome(homeOwner, homeName).thenAccept(optionalHome -> optionalHome.ifPresentOrElse(home -> { - if (!homeOwner.uuid.equals(player.getUuid())) { - if (!home.isPublic && !player.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { + if (!homeOwner.uuid.equals(onlineUser.uuid)) { + if (!home.isPublic && !onlineUser.hasPermission(Permission.COMMAND_HOME_OTHER.node)) { plugin.getLocales().getLocale("error_public_home_invalid", homeOwner.username, homeName) - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); return; } } - teleport(player, home).thenAccept(result -> finishTeleport(player, result)); + teleport(onlineUser, home).thenAccept(result -> finishTeleport(onlineUser, result)); }, () -> { - if (homeOwner.uuid.equals(player.getUuid())) { - plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(player::sendMessage); + if (homeOwner.uuid.equals(onlineUser.uuid)) { + plugin.getLocales().getLocale("error_home_invalid", homeName).ifPresent(onlineUser::sendMessage); } else { - plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(player::sendMessage); + plugin.getLocales().getLocale("error_home_invalid_other", homeName).ifPresent(onlineUser::sendMessage); } })); } /** - * Teleport a {@link Player} to a server {@link Warp} + * Teleport a {@link OnlineUser} to a server {@link Warp} * - * @param player the {@link Player} to teleport + * @param onlineUser the {@link OnlineUser} to teleport * @param warpName the name of the warp */ - public void teleportToWarp(@NotNull Player player, @NotNull String warpName) { + public void teleportToWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) { plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp -> optionalWarp.ifPresentOrElse(warp -> //todo permission restricted warps - teleport(player, warp).thenAccept(result -> finishTeleport(player, result)), () -> + teleport(onlineUser, warp).thenAccept(result -> finishTeleport(onlineUser, result)), () -> plugin.getLocales().getLocale("error_warp_invalid", warpName) - .ifPresent(player::sendMessage))); + .ifPresent(onlineUser::sendMessage))); } /** - * Teleport a {@link Player} to another player by given input name + * Teleport a {@link OnlineUser} to another player by given input name * - * @param player the {@link Player} to teleport + * @param onlineUser the {@link OnlineUser} to teleport * @param targetPlayer the name of the target player */ - public void teleportToPlayer(@NotNull Player player, @NotNull String targetPlayer) { + public void teleportToPlayer(@NotNull OnlineUser onlineUser, @NotNull String targetPlayer) { MatcherUtil.matchPlayerName(targetPlayer, plugin).ifPresentOrElse(playerName -> - getPlayerPosition(player, playerName).thenAccept(optionalPosition -> + getPlayerPosition(onlineUser, playerName).thenAccept(optionalPosition -> optionalPosition.ifPresentOrElse(targetPosition -> - teleport(player, targetPosition).thenAccept(result -> - finishTeleport(player, result)), + teleport(onlineUser, targetPosition).thenAccept(result -> + finishTeleport(onlineUser, result)), () -> plugin.getLocales().getLocale("error_invalid_player"). - ifPresent(player::sendMessage))), - () -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(player::sendMessage)); + ifPresent(onlineUser::sendMessage))), + () -> plugin.getLocales().getLocale("error_invalid_player").ifPresent(onlineUser::sendMessage)); } /** * Gets the position of a player by their username, including players on other servers * - * @param requester the {@link Player} requesting their position + * @param requester the {@link OnlineUser} requesting their position * @param playerName the username of the player being requested * @return future optionally supplying the player's position, if the player could be found */ - private CompletableFuture> getPlayerPosition(@NotNull Player requester, @NotNull String playerName) { + private CompletableFuture> getPlayerPosition(@NotNull OnlineUser requester, @NotNull String playerName) { return CompletableFuture.supplyAsync(() -> { - final Optional localPlayer = plugin.getOnlinePlayers().stream().filter(player -> - player.getName().equalsIgnoreCase(playerName)).findFirst(); + final Optional localPlayer = plugin.getOnlinePlayers().stream().filter(player -> + player.username.equalsIgnoreCase(playerName)).findFirst(); if (localPlayer.isPresent()) { return localPlayer.get().getPosition().thenApply(Optional::of).join(); } @@ -107,7 +107,7 @@ public abstract class TeleportManager { assert plugin.getNetworkMessenger() != null; return plugin.getNetworkMessenger().sendMessage(requester, new Message(Message.MessageType.POSITION_REQUEST, - requester.getName(), + requester.username, playerName, new EmptyPayload(), Message.MessageKind.MESSAGE, @@ -119,16 +119,16 @@ public abstract class TeleportManager { } /** - * Teleport a {@link Player} to a specified {@link Position}. Respects timed teleport. + * Teleport a {@link OnlineUser} to a specified {@link Position}. Respects timed teleport. * - * @param player the {@link Player} to teleport + * @param onlineUser the {@link OnlineUser} to teleport * @param position the target {@link Position} to teleport to */ - public CompletableFuture teleport(@NotNull Player player, @NotNull Position position) { + public CompletableFuture teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) { return CompletableFuture.supplyAsync(() -> { final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME); - if (!player.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) { - return processTimedTeleport(new TimedTeleport(player, position, teleportWarmupTime)) + if (!onlineUser.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) { + return processTimedTeleport(new TimedTeleport(onlineUser, position, teleportWarmupTime)) .thenApply(teleport -> { if (!teleport.cancelled) { return teleport.getPlayer().teleport(teleport.getTargetPosition()).join(); @@ -137,58 +137,57 @@ public abstract class TeleportManager { } }).join(); } else { - return teleportNow(player, position).join(); + return teleportNow(onlineUser, position).join(); } }); } /** - * Handles a completed {@link Player}'s {@link TeleportResult} with the appropriate message + * Handles a completed {@link OnlineUser}'s {@link TeleportResult} with the appropriate message * - * @param player the {@link Player} who just completed a teleport + * @param onlineUser the {@link OnlineUser} who just completed a teleport * @param teleportResult the {@link TeleportResult} to handle */ - public void finishTeleport(@NotNull Player player, @NotNull TeleportResult teleportResult) { + public void finishTeleport(@NotNull OnlineUser onlineUser, @NotNull TeleportResult teleportResult) { switch (teleportResult) { case COMPLETED_LOCALLY -> plugin.getLocales().getLocale("teleporting_complete") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); case FAILED_INVALID_WORLD -> plugin.getLocales().getLocale("error_invalid_on_arrival") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); case FAILED_UNSAFE -> { //todo } case FAILED_ILLEGAL_COORDINATES -> plugin.getLocales().getLocale("error_illegal_target_coordinates") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); case FAILED_INVALID_SERVER -> plugin.getLocales().getLocale("error_invalid_server") - .ifPresent(player::sendMessage); + .ifPresent(onlineUser::sendMessage); } } /** - * Executes a teleport now, teleporting a {@link Player} to a specified {@link Position} + * Executes a teleport now, teleporting a {@link OnlineUser} to a specified {@link Position} * - * @param player the {@link Player} to teleport + * @param onlineUser the {@link OnlineUser} to teleport * @param position the target {@link Position} to teleport to */ - private CompletableFuture teleportNow(@NotNull Player player, @NotNull Position position) { - final User user = new User(player); - final Teleport teleport = new Teleport(user, position); - return CompletableFuture.supplyAsync(() -> player.getPosition().thenApply(preTeleportPosition -> plugin.getDatabase() - .setLastPosition(user, preTeleportPosition) // Update the player's last position - .thenApply(ignored -> plugin.getServer(player).thenApply(server -> { + private CompletableFuture teleportNow(@NotNull OnlineUser onlineUser, @NotNull Position position) { + final Teleport teleport = new Teleport(onlineUser, position); + return CompletableFuture.supplyAsync(() -> onlineUser.getPosition().thenApply(preTeleportPosition -> plugin.getDatabase() + .setLastPosition(onlineUser, preTeleportPosition) // Update the player's last position + .thenApply(ignored -> plugin.getServer(onlineUser).thenApply(server -> { // Teleport player locally, or across server depending on need if (position.server.equals(server)) { - return player.teleport(teleport.target).join(); + return onlineUser.teleport(teleport.target).join(); } else { - return teleportCrossServer(player, teleport).join(); + return teleportCrossServer(onlineUser, teleport).join(); } }).join()).join()).join()); } - private CompletableFuture teleportCrossServer(Player player, Teleport teleport) { + private CompletableFuture teleportCrossServer(OnlineUser onlineUser, Teleport teleport) { assert plugin.getNetworkMessenger() != null; return CompletableFuture.supplyAsync(() -> plugin.getDatabase().setCurrentTeleport(teleport.player, teleport) - .thenApply(ignored -> plugin.getNetworkMessenger().sendPlayer(player, teleport.target.server) + .thenApply(ignored -> plugin.getNetworkMessenger().sendPlayer(onlineUser, teleport.target.server) .thenApply(completed -> completed ? TeleportResult.COMPLETED_CROSS_SERVER : TeleportResult.FAILED_INVALID_SERVER) .join()).join()); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index d592992b..16950183 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -1,6 +1,6 @@ package net.william278.huskhomes.teleport; -import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import org.jetbrains.annotations.NotNull; @@ -10,7 +10,7 @@ import org.jetbrains.annotations.NotNull; */ public class TimedTeleport { - private final Player player; + private final OnlineUser onlineUser; private final Position targetPosition; private final Location startLocation; @@ -21,11 +21,11 @@ public class TimedTeleport { public boolean cancelled = false; - protected TimedTeleport(@NotNull Player player, @NotNull Position targetPosition, int duration) { - this.player = player; + protected TimedTeleport(@NotNull OnlineUser onlineUser, @NotNull Position targetPosition, int duration) { + this.onlineUser = onlineUser; this.targetPosition = targetPosition; - this.startLocation = player.getLocation(); - this.startHealth = player.getHealth(); + this.startLocation = onlineUser.getLocation(); + this.startHealth = onlineUser.getHealth(); this.duration = duration; this.timeLeft = duration; } @@ -41,10 +41,10 @@ public class TimedTeleport { /** * Get the teleporting player * - * @return the {@link Player} who is teleporting + * @return the {@link OnlineUser} who is teleporting */ - public Player getPlayer() { - return player; + public OnlineUser getPlayer() { + return onlineUser; } /** @@ -54,9 +54,9 @@ public class TimedTeleport { */ public boolean hasMoved() { final double maxMovementDistance = 0.1d; - double movementDistance = Math.abs(startLocation.x - player.getLocation().x) + - Math.abs(startLocation.y - player.getLocation().y) + - Math.abs(startLocation.z - player.getLocation().z); + double movementDistance = Math.abs(startLocation.x - onlineUser.getLocation().x) + + Math.abs(startLocation.y - onlineUser.getLocation().y) + + Math.abs(startLocation.z - onlineUser.getLocation().z); return movementDistance > maxMovementDistance; } @@ -66,7 +66,7 @@ public class TimedTeleport { * @return {@code true} if the player has taken damage */ public boolean hasTakenDamage() { - return player.getHealth() < startHealth; + return onlineUser.getHealth() < startHealth; } /** diff --git a/common/src/main/java/net/william278/huskhomes/util/Logger.java b/common/src/main/java/net/william278/huskhomes/util/Logger.java index 17272067..b0479917 100644 --- a/common/src/main/java/net/william278/huskhomes/util/Logger.java +++ b/common/src/main/java/net/william278/huskhomes/util/Logger.java @@ -1,20 +1,37 @@ package net.william278.huskhomes.util; +import de.themoep.minedown.MineDown; +import org.jetbrains.annotations.NotNull; + import java.util.logging.Level; /** * An abstract, cross-platform representation of a logger */ -public interface Logger { +public abstract class Logger { - void log(Level level, String message, Exception e); + private boolean debug; - void log(Level level, String message); + public abstract void log(@NotNull Level level, @NotNull String message, @NotNull Exception e); - void info(String message); + public abstract void log(@NotNull Level level, @NotNull String message); - void severe(String message); + public abstract void log(@NotNull Level level, @NotNull MineDown mineDown); - void config(String message); + public abstract void info(@NotNull String message); + + public abstract void severe(@NotNull String message); + + public final void debug(@NotNull String message) { + if (debug) { + log(Level.INFO, "[DEBUG] " + message); + } + } + + public abstract void config(@NotNull String message); + + public final void showDebugLogs(boolean debug) { + this.debug = debug; + } } diff --git a/common/src/main/java/net/william278/huskhomes/util/UpdateChecker.java b/common/src/main/java/net/william278/huskhomes/util/UpdateChecker.java new file mode 100644 index 00000000..383b976c --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/UpdateChecker.java @@ -0,0 +1,57 @@ +package net.william278.huskhomes.util; + +import org.jetbrains.annotations.NotNull; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; + +public class UpdateChecker { + + private final static int SPIGOT_PROJECT_ID = 83767; + private final Logger logger; + private final Version currentVersion; + + public UpdateChecker(@NotNull Version currentVersion, @NotNull Logger logger) { + this.currentVersion = currentVersion; + this.logger = logger; + } + + public CompletableFuture fetchLatestVersion() { + return CompletableFuture.supplyAsync(() -> { + try { + final URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + SPIGOT_PROJECT_ID); + URLConnection urlConnection = url.openConnection(); + return Version.pluginVersion(new BufferedReader(new InputStreamReader(urlConnection.getInputStream())).readLine()); + } catch (Exception e) { + logger.log(Level.WARNING, "Failed to fetch the latest plugin version", e); + } + return new Version(); + }); + } + + public boolean isUpdateAvailable(@NotNull Version latestVersion) { + return latestVersion.compareTo(currentVersion) > 0; + } + + public Version getCurrentVersion() { + return currentVersion; + } + + public CompletableFuture isUpToDate() { + return fetchLatestVersion().thenApply(this::isUpdateAvailable); + } + + public void logToConsole() { + fetchLatestVersion().thenAccept(latestVersion -> { + if (isUpdateAvailable(latestVersion)) { + logger.log(Level.WARNING, "A new version of HuskHomes is available: v" + latestVersion); + } else { + logger.log(Level.INFO, "HuskHomes is up-to-date! (Running: v" + getCurrentVersion().toString() + ")"); + } + }); + } +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/util/Version.java b/common/src/main/java/net/william278/huskhomes/util/Version.java new file mode 100644 index 00000000..f9a16f91 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/Version.java @@ -0,0 +1,71 @@ +package net.william278.huskhomes.util; + +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.StringJoiner; +import java.util.regex.Pattern; + +public class Version implements Comparable { + private final static String VERSION_SEPARATOR = "."; + private final static String MINECRAFT_META_SEPARATOR = "-"; + private final static String PLUGIN_META_SEPARATOR = "+"; + + private int[] versions = new int[]{}; + @NotNull + private String metadata = ""; + @NotNull + private String metaSeparator = ""; + + protected Version() { + } + + private Version(@NotNull String version, @NotNull String metaSeparator) { + this.parse(version, metaSeparator); + this.metaSeparator = metaSeparator; + } + + @NotNull + public static Version pluginVersion(@NotNull String versionString) { + return new Version(versionString, PLUGIN_META_SEPARATOR); + } + + @NotNull + public static Version minecraftVersion(@NotNull String versionString) { + return new Version(versionString, MINECRAFT_META_SEPARATOR); + } + + private void parse(@NotNull String version, @NotNull String metaSeparator) { + int metaIndex = version.indexOf(metaSeparator); + if (metaIndex > 0) { + this.metadata = version.substring(metaIndex + 1); + version = version.substring(0, metaIndex); + } + String[] versions = version.split(Pattern.quote(VERSION_SEPARATOR)); + this.versions = Arrays.stream(versions).mapToInt(Integer::parseInt).toArray(); + } + + @Override + public int compareTo(@NotNull Version other) { + int length = Math.max(this.versions.length, other.versions.length); + for (int i = 0; i < length; i++) { + int a = i < this.versions.length ? this.versions[i] : 0; + int b = i < other.versions.length ? other.versions[i] : 0; + + if (a < b) return -1; + if (a > b) return 1; + } + + return 0; + } + + @Override + public String toString() { + final StringJoiner joiner = new StringJoiner(VERSION_SEPARATOR); + for (int version : this.versions) { + joiner.add(String.valueOf(version)); + } + return joiner + ((!this.metadata.isEmpty()) ? (this.metaSeparator + this.metadata) : ""); + } + +} diff --git a/common/src/main/resources/config.yml b/common/src/main/resources/config.yml index af6cc5b5..af7ada00 100644 --- a/common/src/main/resources/config.yml +++ b/common/src/main/resources/config.yml @@ -6,6 +6,7 @@ language: 'en-gb' check_for_updates: true +debug_logging: false data_storage_options: storage_type: 'SQLite' mysql_credentials: diff --git a/common/src/main/resources/languages/en-gb.yml b/common/src/main/resources/locales/en-gb.yml similarity index 100% rename from common/src/main/resources/languages/en-gb.yml rename to common/src/main/resources/locales/en-gb.yml