diff --git a/bukkit/build.gradle b/bukkit/build.gradle index da76b010..d2898e89 100644 --- a/bukkit/build.gradle +++ b/bukkit/build.gradle @@ -15,4 +15,6 @@ shadowJar { relocate 'de.themoep', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries' + relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' + relocate 'org.slf4j', 'net.william278.huskhomes.libraries.slf4j' } \ No newline at end of file diff --git a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java index 1ef5fc73..1dbb8836 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java +++ b/bukkit/src/main/java/net/william278/huskhomes/HuskHomesBukkit.java @@ -13,6 +13,7 @@ import net.william278.huskhomes.player.Player; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Server; import net.william278.huskhomes.util.BukkitLogger; +import net.william278.huskhomes.util.BukkitResourceReader; import net.william278.huskhomes.util.Logger; import org.bukkit.plugin.java.JavaPlugin; @@ -27,9 +28,8 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { private Settings settings; private Messages messages; private BukkitLogger logger; - + private BukkitResourceReader resourceReader; private Server server; - private Database database; @Override @@ -39,8 +39,9 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { @Override public void onEnable() { - // Set the logging adapter + // Set the logging and resource reading adapter logger = new BukkitLogger(getLogger()); + resourceReader = new BukkitResourceReader(this); // Load plugin settings and messages loadConfigData(); @@ -96,14 +97,14 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes { private void loadConfigData() { try { settings = Settings.load(YamlDocument.create(new File(getDataFolder(), "config.yml"), - Objects.requireNonNull(getResource("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())); messages = Messages.load(YamlDocument.create(new File(getDataFolder(), "messages-" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml"), - Objects.requireNonNull(getResource( + Objects.requireNonNull(resourceReader.getResource( "languages/" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml")))); } catch (IOException | NullPointerException e) { getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", e); diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java new file mode 100644 index 00000000..eb940276 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventProcessor.java @@ -0,0 +1,21 @@ +package net.william278.huskhomes.listener; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.player.BukkitPlayer; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.jetbrains.annotations.NotNull; + +public class BukkitEventProcessor extends EventProcessor implements Listener { + + public BukkitEventProcessor(@NotNull HuskHomes implementor) { + super(implementor); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + super.onPlayerJoin(BukkitPlayer.adapt(event.getPlayer())); + } + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java new file mode 100644 index 00000000..f6334ade --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/player/BukkitPlayer.java @@ -0,0 +1,78 @@ +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.teleport.TeleportResult; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +public class BukkitPlayer implements Player { + + private final org.bukkit.entity.Player bukkitPlayer; + + private BukkitPlayer(org.bukkit.entity.Player bukkitPlayer) { + this.bukkitPlayer = bukkitPlayer; + } + + 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 BukkitPlayer adapt(@NotNull org.bukkit.entity.Player player) { + return new BukkitPlayer(player); + } + + @Override + public String getName() { + return bukkitPlayer.getName(); + } + + @Override + public UUID getUuid() { + return bukkitPlayer.getUniqueId(); + } + + @Override + public Position getPosition() { + return null; + } + + @Override + public boolean hasPermission(@NotNull String node) { + return bukkitPlayer.hasPermission(node); + } + + @Override + public void sendMessage(@NotNull MineDown mineDown) { + bukkitPlayer.spigot().sendMessage(mineDown.toComponent()); + } + + @Override + public CompletableFuture teleport(Location location) { + return null; //todo + } + + @Override + public CompletableFuture getMaxHomes() { + return null; //todo + } + + @Override + public CompletableFuture getFreeHomes() { + return null; //todo + } + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java new file mode 100644 index 00000000..3a0a1a4e --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitResourceReader.java @@ -0,0 +1,20 @@ +package net.william278.huskhomes.util; + +import net.william278.huskhomes.HuskHomesBukkit; + +import java.io.InputStream; + +public class BukkitResourceReader implements ResourceReader { + + private final HuskHomesBukkit plugin; + + public BukkitResourceReader(HuskHomesBukkit plugin) { + this.plugin = plugin; + } + + @Override + public InputStream getResource(String fileName) { + return plugin.getResource(fileName); + } + +} diff --git a/common/build.gradle b/common/build.gradle index c9f935eb..e89a3792 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -2,6 +2,7 @@ dependencies { compileOnly 'commons-io:commons-io:2.11.0' compileOnly 'dev.dejvokep:boosted-yaml:1.2' compileOnly 'de.themoep:minedown:1.7.1-SNAPSHOT' + implementation 'com.zaxxer:HikariCP:5.0.1' } shadowJar { @@ -10,4 +11,6 @@ shadowJar { relocate 'de.themoep', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries' + relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' + relocate 'org.slf4j', 'net.william278.huskhomes.libraries.slf4j' } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/config/Messages.java b/common/src/main/java/net/william278/huskhomes/config/Messages.java index 370a90ba..8d707a8b 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Messages.java +++ b/common/src/main/java/net/william278/huskhomes/config/Messages.java @@ -38,7 +38,8 @@ public class Messages { /** * Returns an unformatted message loaded from the messages file, with replacements applied * - * @param messageId String identifier of the message, corresponding to a key in the file + * @param messageId String identifier of the message, corresponding to a key in the file + * @param replacements Ordered array of replacement strings to fill in placeholders with * @return An {@link Optional} containing the replacement-applied message corresponding to the id, if it exists */ public Optional getRawMessage(String messageId, String... replacements) { @@ -58,7 +59,8 @@ public class Messages { /** * Returns a MineDown-formatted message from the messages file, with replacements applied * - * @param messageId String identifier of the message, corresponding to a key in the file + * @param messageId String identifier of the message, corresponding to a key in the file + * @param replacements Ordered array of replacement strings to fill in placeholders with * @return An {@link Optional} containing the replacement-applied, formatted message corresponding to the id, if it exists */ public Optional getMessage(String messageId, String... replacements) { @@ -69,7 +71,7 @@ public class Messages { * Apply placeholder replacements to a raw message * * @param rawMessage The raw, unparsed message - * @param replacements Ordered list of placeholder replacement Strings + * @param replacements Ordered array of replacement strings to fill in placeholders with * @return the raw message, with inserted placeholders */ private String applyReplacements(String rawMessage, String... replacements) { diff --git a/common/src/main/java/net/william278/huskhomes/data/Database.java b/common/src/main/java/net/william278/huskhomes/data/Database.java index 6c5edb77..22c586f3 100644 --- a/common/src/main/java/net/william278/huskhomes/data/Database.java +++ b/common/src/main/java/net/william278/huskhomes/data/Database.java @@ -2,25 +2,35 @@ package net.william278.huskhomes.data; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.position.*; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Position; +import net.william278.huskhomes.position.PositionMeta; +import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.util.Logger; +import net.william278.huskhomes.util.ResourceReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** - * An abstract representation of the plugin database, storing home, warp & player data. + * An abstract representation of the plugin database, storing home, warp and player data. *

* Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator. */ public abstract class Database { /** - * Stores data about {@link Player}s + * Stores data about {@link User}s *

    *
  1. uuid - Primary key, unique; the user's minecraft account unique ID
  2. *
  3. username - The user's username. Checked to be updated on login
  4. @@ -84,7 +94,7 @@ public abstract class Database { protected final String warpsTableName; /** - * Stores data about current cross-server teleports being executed by {@link Player}s + * Stores data about current cross-server teleports being executed by {@link User}s *
      *
    1. player_uuid - Primary key, unique, references player table; represents the unique id of a teleporting player
    2. *
    3. destination_id - References positions table; the destination of the teleporting player
    4. @@ -92,12 +102,58 @@ public abstract class Database { */ protected final String teleportsTableName; + /** + * Logger instance used for database error logging + */ + private final Logger logger; + + /** + * Returns the {@link Logger} used to log database errors + * + * @return the {@link Logger} instance + */ + protected Logger getLogger() { + return logger; + } + + private final ResourceReader resourceReader; + + /** + * Loads SQL table creation schema statements from a resource file as a string array + * + * @param schemaFileName database script resource file to load from + * @return Array of string-formatted table creation schema statements + * @throws IOException if the resource could not be read + */ + protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException { + return formatStatementTables( + new String(resourceReader.getResource(schemaFileName) + .readAllBytes(), StandardCharsets.UTF_8)) + .split(";"); + } + + /** + * Format all table name placeholder strings in a SQL statement + * + * @param sql the SQL statement with unformatted table name placeholders + * @return the formatted statement, with table placeholders replaced with the correct names + */ + protected final String formatStatementTables(@NotNull String sql) { + return sql + .replaceAll("%positions_table%", positionsTableName) + .replaceAll("%players_table%", playerTableName) + .replaceAll("%teleports_table%", teleportsTableName) + .replaceAll("%position_metadata_table%", positionMetadataTableName) + .replaceAll("%homes_table%", homesTableName) + .replaceAll("%warps_table%", warpsTableName); + } + /** * Create a database instance with specified table data {@link Settings} * * @param settings {@link Settings} to fetch database configuration data from */ - protected Database(@NotNull Settings settings) { + protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) { this.playerTableName = settings. getStringValue(Settings.ConfigOption.DATABASE_PLAYER_TABLE_NAME); this.positionsTableName = settings. @@ -110,6 +166,8 @@ public abstract class Database { getStringValue(Settings.ConfigOption.DATABASE_WARPS_TABLE_NAME); this.teleportsTableName = settings. getStringValue(Settings.ConfigOption.DATABASE_TELEPORTS_TABLE_NAME); + this.logger = logger; + this.resourceReader = resourceReader; } /** @@ -123,20 +181,20 @@ public abstract class Database { * (Internal use only) - Sets a position to the position table in the database * * @param position The {@link Position} to set - * @return A future returning the inserted row ID when the operation has completed. + * @return The newly inserted row ID */ - protected abstract CompletableFuture setPosition(@NotNull Position position); + protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException; /** * (Internal use only) - Sets position meta to the position metadata table in the database * * @param meta The {@link PositionMeta} to set - * @return A future returning the inserted row ID when the operation has completed. + * @return The newly inserted row ID */ - protected abstract CompletableFuture setPositionMeta(@NotNull PositionMeta meta); + protected abstract int setPositionMeta(@NotNull PositionMeta meta, @NotNull Connection connection) throws SQLException; /** - * Ensure a {@link Player} has an entry in the database and that their username is up-to-date + * Ensure a {@link Player} has a {@link User} entry in the database and that their username is up-to-date * * @param player The {@link Player} to ensure * @return A future returning void when complete @@ -146,18 +204,27 @@ public abstract class Database { /** * Get a player by their username (case-insensitive) * - * @param name Username of the {@link Player} to get (case-insensitive) - * @return A future returning an optional with the {@link Player} present if they exist + * @param name Username of the {@link User} to get (case-insensitive) + * @return A future returning an optional with the {@link User} present if they exist */ - public abstract CompletableFuture> getPlayerByName(@NotNull String name); + public abstract CompletableFuture> getUserByName(@NotNull String name); /** - * Get a list of {@link Home}s set by a {@link Player} + * Get a player by their Minecraft account {@link UUID} * - * @param player {@link Player} to get the homes of + * @param uuid Minecraft account {@link UUID} of the {@link User} to get + * @return A future returning an optional with the {@link User} present if they exist + */ + public abstract CompletableFuture> getUser(@NotNull UUID uuid); + + + /** + * Get a list of {@link Home}s set by a {@link User} + * + * @param player {@link User} to get the homes of * @return A future returning void when complete */ - public abstract CompletableFuture> getHomes(@NotNull Player player); + public abstract CompletableFuture> getHomes(@NotNull User player); /** * Get a list of all {@link Warp}s that have been set @@ -174,13 +241,13 @@ public abstract class Database { public abstract CompletableFuture> getPublicHomes(); /** - * Get a {@link Home} set by a {@link Player} + * Get a {@link Home} set by a {@link User} * - * @param player The {@link Player} who set the home + * @param player The {@link User} who set the home * @param homeName The case-insensitive name of the home to get * @return A future returning an optional with the {@link Home} present if it exists */ - public abstract CompletableFuture> getHome(@NotNull Player player, @NotNull String homeName); + public abstract CompletableFuture> getHome(@NotNull User player, @NotNull String homeName); /** * Get a {@link Home} by its unique id @@ -207,74 +274,74 @@ public abstract class Database { public abstract CompletableFuture> getWarp(@NotNull UUID uuid); /** - * Get the current {@link Teleport} being executed by the specified {@link Player} + * Get the current {@link Teleport} being executed by the specified {@link User} * - * @param player The {@link Player} to check + * @param player The {@link User} to check * @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server */ - public abstract CompletableFuture> getCurrentTeleport(@NotNull Player player); + public abstract CompletableFuture> getCurrentTeleport(@NotNull User player); /** - * Sets or clears the current {@link Teleport} being executed by a {@link Player} + * Sets or clears the current {@link Teleport} being executed by a {@link User} * - * @param player The {@link Player} to set the current teleport of. + * @param player The {@link User} to set the current teleport of. * Pass as {@code null} to clear the player's current teleport.

      * @param teleport The {@link Teleport} to set as their current cross-server teleport * @return A future returning void when complete */ - public abstract CompletableFuture setCurrentTeleport(@NotNull Player player, @Nullable Teleport teleport); + public abstract CompletableFuture setCurrentTeleport(@NotNull User player, @Nullable Teleport teleport); /** - * Get the last teleport {@link Position} of a specified {@link Player} + * Get the last teleport {@link Position} of a specified {@link User} * - * @param player The {@link Player} to check + * @param player The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getLastPosition(@NotNull Player player); + public abstract CompletableFuture> getLastPosition(@NotNull User player); /** - * Sets the last teleport {@link Position} of a {@link Player} + * Sets the last teleport {@link Position} of a {@link User} * - * @param player The {@link Player} to set the last position of + * @param player The {@link User} to set the last position of * @param position The {@link Position} to set as their last position * @return A future returning void when complete */ - public abstract CompletableFuture setLastPosition(@NotNull Player player, @NotNull Position position); + public abstract CompletableFuture setLastPosition(@NotNull User player, @NotNull Position position); /** - * Get the offline {@link Position} of a specified {@link Player} + * Get the offline {@link Position} of a specified {@link User} * - * @param player The {@link Player} to check + * @param player The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getOfflinePosition(@NotNull Player player); + public abstract CompletableFuture> getOfflinePosition(@NotNull User player); /** - * Sets the offline {@link Position} of a {@link Player} + * Sets the offline {@link Position} of a {@link User} * - * @param player The {@link Player} to set the offline position of + * @param player The {@link User} to set the offline position of * @param position The {@link Position} to set as their offline position * @return A future returning void when complete */ - public abstract CompletableFuture setOfflinePosition(@NotNull Player player, @NotNull Position position); + public abstract CompletableFuture setOfflinePosition(@NotNull User player, @NotNull Position position); /** - * Get the respawn {@link Position} of a specified {@link Player} + * Get the respawn {@link Position} of a specified {@link User} * - * @param player The {@link Player} to check + * @param player The {@link User} to check * @return A future returning an optional with the {@link Position} present if it has been set */ - public abstract CompletableFuture> getRespawnPosition(@NotNull Player player); + public abstract CompletableFuture> getRespawnPosition(@NotNull User player); /** - * Sets or clears the respawn {@link Position} of a {@link Player} + * Sets or clears the respawn {@link Position} of a {@link User} * - * @param player The {@link Player} to set the respawn position of + * @param player The {@link User} to set the respawn position of * @param position The {@link Position} to set as their respawn position * Pass as {@code null} to clear the player's current respawn position.

      * @return A future returning void when complete */ - public abstract CompletableFuture setRespawnPosition(@NotNull Player player, @Nullable Position position); + public abstract CompletableFuture setRespawnPosition(@NotNull User player, @Nullable Position position); /** * Sets or updates a {@link Home} into the home data table on the database. @@ -308,4 +375,55 @@ public abstract class Database { */ public abstract CompletableFuture deleteWarp(@NotNull Warp uuid); + /** + * Get the rtp cooldown time of a specified {@link User} + * + * @param player The {@link User} to check + * @return A future returning the epoch time of their current cooldown + */ + public abstract CompletableFuture getRtpCooldown(@NotNull User player); + + /** + * Sets the rtp cooldown time of a {@link User} + * + * @param player The {@link User} to update + * @param position The epoch time of when the user can use rtp again. + * @return A future returning void when complete + */ + public abstract CompletableFuture setRtpCooldown(@NotNull User player, long position); + + /** + * Get the number of home slots a {@link User} has consumed (bought) + * + * @param player The {@link User} to check + * @return A future returning the number of home slots + */ + public abstract CompletableFuture getHomeSlots(@NotNull User player); + + /** + * Sets the number of home slots a {@link User} has consumed (bought) + * + * @param player The {@link User} to update + * @param homeSlots The number of home slots to set the user as having consumed. + * @return A future returning void when complete + */ + public abstract CompletableFuture setHomeSlots(@NotNull User player, int homeSlots); + + /** + * Get if a {@link User} is ignoring tp requests + * + * @param player The {@link User} to check + * @return A future returning if the player is ignoring tp requests + */ + public abstract CompletableFuture getIsIgnoringTeleports(@NotNull User player); + + /** + * Sets if a {@link User} is ignoring tp requests + * + * @param player The {@link User} to update + * @param ignoringTeleports If the player is ignoring tp requests + * @return A future returning void when complete + */ + public abstract CompletableFuture setIgnoringTeleports(@NotNull User player, boolean ignoringTeleports); + } diff --git a/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java index d78759f9..7eccc536 100644 --- a/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/data/MySqlDatabase.java @@ -1,124 +1,556 @@ package net.william278.huskhomes.data; +import com.zaxxer.hikari.HikariDataSource; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.player.Player; -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.PositionMeta; -import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.player.User; +import net.william278.huskhomes.position.*; import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.util.Logger; +import net.william278.huskhomes.util.ResourceReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.IOException; +import java.sql.*; +import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; //todo write (hikari for this; direct driver for SQLite probably) + +/** + * A MySQL implementation of the plugin {@link Database} + */ +@SuppressWarnings("DuplicatedCode") public class MySqlDatabase extends Database { - public MySqlDatabase(@NotNull Settings settings) { - super(settings); + /** + * MySQL server hostname + */ + private final String mySqlHost; + /** + * MySQL server port + */ + private final int mySqlPort; + /** + * Database to use on the MySQL server + */ + private final String mySqlDatabaseName; + /** + * MySQL username for accessing the database + */ + private final String mySqlUsername; + /** + * MySQL password for accessing the database + */ + private final String mySqlPassword; + /** + * Additional connection parameters, formatted as a jdbc connection string + */ + private final String mySqlConnectionParameters; + + private final int hikariMaximumPoolSize; + private final int hikariMinimumIdle; + private final int hikariMaximumLifetime; + private final int hikariKeepAliveTime; + private final int hikariConnectionTimeOut; + + private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; + + private HikariDataSource dataSource; + + public MySqlDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) { + super(settings, logger, resourceReader); + this.mySqlHost = settings.getStringValue(Settings.ConfigOption.DATABASE_HOST); + this.mySqlPort = settings.getIntegerValue(Settings.ConfigOption.DATABASE_PORT); + this.mySqlDatabaseName = settings.getStringValue(Settings.ConfigOption.DATABASE_NAME); + this.mySqlUsername = settings.getStringValue(Settings.ConfigOption.DATABASE_USERNAME); + this.mySqlPassword = settings.getStringValue(Settings.ConfigOption.DATABASE_PASSWORD); + this.mySqlConnectionParameters = settings.getStringValue(Settings.ConfigOption.DATABASE_CONNECTION_PARAMS); + + this.hikariMaximumPoolSize = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MAX_SIZE); + this.hikariMinimumIdle = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MIN_IDLE); + this.hikariMaximumLifetime = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MAX_LIFETIME); + this.hikariKeepAliveTime = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_KEEPALIVE); + this.hikariConnectionTimeOut = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_TIMEOUT); + } + + /** + * Fetch the auto-closeable connection from the hikariDataSource + * + * @return The {@link Connection} to the MySQL database + * @throws SQLException if the connection fails for some reason + */ + private Connection getConnection() throws SQLException { + return dataSource.getConnection(); } @Override public CompletableFuture initialize() { - return null; + return CompletableFuture.runAsync(() -> { + // Create jdbc driver connection url + final String jdbcUrl = "jdbc:mysql://" + mySqlHost + ":" + mySqlPort + "/" + mySqlDatabaseName + mySqlConnectionParameters; + dataSource = new HikariDataSource(); + dataSource.setJdbcUrl(jdbcUrl); + + // Authenticate + dataSource.setUsername(mySqlUsername); + dataSource.setPassword(mySqlPassword); + + // Set various additional parameters + dataSource.setMaximumPoolSize(hikariMaximumPoolSize); + dataSource.setMinimumIdle(hikariMinimumIdle); + dataSource.setMaxLifetime(hikariMaximumLifetime); + dataSource.setKeepaliveTime(hikariKeepAliveTime); + dataSource.setConnectionTimeout(hikariConnectionTimeOut); + dataSource.setPoolName(DATA_POOL_NAME); + + // Prepare database schema; make tables if they don't exist + try (Connection connection = dataSource.getConnection()) { + // Load database schema CREATE statements from schema file + final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql"); + try (Statement statement = connection.createStatement()) { + for (String tableCreationStatement : databaseSchema) { + statement.execute(tableCreationStatement); + } + } + } catch (SQLException | IOException e) { + getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e); + } + }); } @Override - protected CompletableFuture setPosition(@NotNull Position position) { - return null; + protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) + VALUES (?,?,?,?,?,?,?,?);"""), + Statement.RETURN_GENERATED_KEYS)) { + + statement.setDouble(1, position.x); + statement.setDouble(2, position.y); + statement.setDouble(3, position.z); + statement.setFloat(4, position.yaw); + statement.setFloat(5, position.pitch); + statement.setString(6, position.world.name); + statement.setString(7, position.world.uuid.toString()); + statement.setString(8, position.server.name); + statement.executeUpdate(); + + return statement.getGeneratedKeys().getInt(1); + } } @Override - protected CompletableFuture setPositionMeta(@NotNull PositionMeta meta) { - return null; + protected int setPositionMeta(@NotNull PositionMeta meta, @NotNull Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%position_metadata_table%` (`name`, `description`, `timestamp`) + VALUES (?,?,?);"""), + Statement.RETURN_GENERATED_KEYS)) { + + statement.setString(1, meta.name); + statement.setString(2, meta.description); + statement.setTimestamp(3, new Timestamp(Instant.ofEpochSecond(meta.timestamp).toEpochMilli())); + statement.executeUpdate(); + + return statement.getGeneratedKeys().getInt(1); + } } @Override public CompletableFuture ensurePlayer(@NotNull Player player) { - return null; + return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser -> + optionalUser.ifPresentOrElse(existingUser -> { + if (!existingUser.username().equals(player.getName())) { + // Update a player's name if it has changed in the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `username`=? + WHERE `uuid`=?"""))) { + + statement.setString(1, player.getName()); + statement.setString(2, existingUser.uuid().toString()); + statement.executeUpdate(); + } + getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username() + " -> " + player.getName() + ")"); + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); + } + } + }, + () -> { + // Insert new player data into the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%players_table%` (`uuid`,`username`) + VALUES (?,?);"""))) { + + statement.setString(1, player.getUuid().toString()); + statement.setString(2, player.getName()); + statement.executeUpdate(); + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); + } + }))); } @Override - public CompletableFuture> getPlayerByName(@NotNull String name) { - return null; + public CompletableFuture> getUserByName(@NotNull String name) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username` + FROM `%players_table%` + WHERE `username`=?"""))) { + statement.setString(1, name); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + } + return Optional.empty(); + }); } @Override - public CompletableFuture> getHomes(@NotNull Player player) { - return null; + public CompletableFuture> getUser(@NotNull UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username` + FROM `%players_table%` + WHERE `uuid`=?"""))) { + + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + } + return Optional.empty(); + }); + } + + @Override + public CompletableFuture> getHomes(@NotNull User user) { + return CompletableFuture.supplyAsync(() -> { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `owner_uuid`=? + ORDER BY `name`;"""))) { + + statement.setString(1, user.uuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username()); + } + return userHomes; + }); } @Override public CompletableFuture> getWarps() { - return null; + return CompletableFuture.supplyAsync(() -> { + final List warps = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id` + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + warps.add(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); + } + return warps; + }); } @Override public CompletableFuture> getPublicHomes() { - return null; + return CompletableFuture.supplyAsync(() -> { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `public`=true + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); + } + return userHomes; + }); } @Override - public CompletableFuture> getHome(@NotNull Player player, @NotNull String homeName) { - return null; + public CompletableFuture> getHome(@NotNull User user, @NotNull String homeName) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `owner_uuid`=? + AND `name`=?;"""))) { + statement.setString(1, user.uuid().toString()); + statement.setString(2, homeName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home", e); + } + return Optional.empty(); + }); } @Override public CompletableFuture> getHome(@NotNull UUID uuid) { - return null; + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `%homes_table%`.`uuid`=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Home(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("home_uuid")), + new User(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a player's home by UUID", e); + } + return Optional.empty(); + }); } @Override public CompletableFuture> getWarp(@NotNull String warpName) { - return null; + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `name`=?;"""))) { + statement.setString(1, warpName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + }); } @Override public CompletableFuture> getWarp(@NotNull UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id` + WHERE `%warps_table%`.uuid=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new Warp(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + new World(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + new Server(resultSet.getString("server_name")), + new PositionMeta(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + }); + } + + @Override + public CompletableFuture> getCurrentTeleport(@NotNull User player) { return null; } @Override - public CompletableFuture> getCurrentTeleport(@NotNull Player player) { + public CompletableFuture setCurrentTeleport(@NotNull User player, @Nullable Teleport teleport) { return null; } @Override - public CompletableFuture setCurrentTeleport(@NotNull Player player, @Nullable Teleport teleport) { + public CompletableFuture> getLastPosition(@NotNull User player) { return null; } @Override - public CompletableFuture> getLastPosition(@NotNull Player player) { + public CompletableFuture setLastPosition(@NotNull User player, @NotNull Position position) { return null; } @Override - public CompletableFuture setLastPosition(@NotNull Player player, @NotNull Position position) { + public CompletableFuture> getOfflinePosition(@NotNull User player) { return null; } @Override - public CompletableFuture> getOfflinePosition(@NotNull Player player) { + public CompletableFuture setOfflinePosition(@NotNull User player, @NotNull Position position) { return null; } @Override - public CompletableFuture setOfflinePosition(@NotNull Player player, @NotNull Position position) { + public CompletableFuture> getRespawnPosition(@NotNull User player) { return null; } @Override - public CompletableFuture> getRespawnPosition(@NotNull Player player) { - return null; - } - - @Override - public CompletableFuture setRespawnPosition(@NotNull Player player, @Nullable Position position) { + public CompletableFuture setRespawnPosition(@NotNull User player, @Nullable Position position) { return null; } @@ -141,4 +573,35 @@ public class MySqlDatabase extends Database { public CompletableFuture deleteWarp(@NotNull Warp uuid) { return null; } -} + + @Override + public CompletableFuture getRtpCooldown(@NotNull User player) { + return null; + } + + @Override + public CompletableFuture setRtpCooldown(@NotNull User player, long position) { + return null; + } + + @Override + public CompletableFuture getHomeSlots(@NotNull User player) { + return null; + } + + @Override + public CompletableFuture setHomeSlots(@NotNull User player, int homeSlots) { + return null; + } + + @Override + public CompletableFuture getIsIgnoringTeleports(@NotNull User player) { + return null; + } + + @Override + public CompletableFuture setIgnoringTeleports(@NotNull User player, boolean ignoringTeleports) { + return null; + } + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java b/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java new file mode 100644 index 00000000..477520fd --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/listener/EventProcessor.java @@ -0,0 +1,45 @@ +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 org.jetbrains.annotations.NotNull; + +/** + * A handler for when events take place + */ +public class EventProcessor { + + @NotNull + private final HuskHomes implementor; + + public EventProcessor(@NotNull HuskHomes implementor) { + this.implementor = implementor; + } + + /** + * Handle when a {@link Player} joins the server + * + * @param player the joining {@link Player} + */ + public void onPlayerJoin(@NotNull Player player) { + // Ensure the player is present on the database first + implementor.getDatabase().ensurePlayer(player).thenRun(() -> { + // If the server is in proxy mode, check if the player is teleporting cross-server + if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { + implementor.getDatabase().getCurrentTeleport(new User(player.getUuid(), player.getName())) + .thenAccept(teleport -> teleport.ifPresent(currentTeleport -> + player.teleport(currentTeleport.target).thenAccept(teleportResult -> { + if (!teleportResult.successful) { + //todo error handling if the teleport was not successful on arrival + return; + } else { + //todo display teleport complete ^-^ + } + }))); + } + }); + } + +} \ 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 new file mode 100644 index 00000000..c3557d62 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/player/User.java @@ -0,0 +1,16 @@ +package net.william278.huskhomes.player; + +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 + * + * @param uuid + * @param username {@see {@link Player}} - an online player representation + */ +public record User(@NotNull UUID uuid, @NotNull String username) { + +} diff --git a/common/src/main/java/net/william278/huskhomes/position/Home.java b/common/src/main/java/net/william278/huskhomes/position/Home.java index 99a3eda1..9a0bae11 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Home.java +++ b/common/src/main/java/net/william278/huskhomes/position/Home.java @@ -1,20 +1,21 @@ package net.william278.huskhomes.position; import net.william278.huskhomes.player.Player; +import net.william278.huskhomes.player.User; import org.jetbrains.annotations.NotNull; import java.util.UUID; /** - * Represents a home set by a {@link Player} + * Represents a home set by a {@link User} */ public class Home extends SavedPosition { /** - * The {@link Player} who owns this home + * The {@link User} who owns this home */ @NotNull - public final Player owner; + public final User owner; /** * {@code true} if this home is public @@ -24,13 +25,13 @@ public class Home extends SavedPosition { public Home(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull Server server, @NotNull PositionMeta positionMeta, @NotNull UUID uuid, - @NotNull Player owner, boolean isPublic) { + @NotNull User owner, boolean isPublic) { super(x, y, z, yaw, pitch, world, server, positionMeta, uuid); this.owner = owner; this.isPublic = isPublic; } - public Home(Position position, PositionMeta meta, @NotNull Player owner) { + public Home(Position position, PositionMeta meta, @NotNull User owner) { super(position, meta); this.owner = owner; this.isPublic = false; diff --git a/common/src/main/java/net/william278/huskhomes/position/Location.java b/common/src/main/java/net/william278/huskhomes/position/Location.java index 469bcbb8..69babef3 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Location.java +++ b/common/src/main/java/net/william278/huskhomes/position/Location.java @@ -2,6 +2,9 @@ package net.william278.huskhomes.position; import org.jetbrains.annotations.NotNull; +/** + * Represents a local position on this server + */ public class Location { /** diff --git a/common/src/main/java/net/william278/huskhomes/position/Position.java b/common/src/main/java/net/william278/huskhomes/position/Position.java index 2a73e532..67263d88 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -2,8 +2,6 @@ package net.william278.huskhomes.position; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - /** * Represents a position - a location somewhere on the proxy network or server */ diff --git a/common/src/main/java/net/william278/huskhomes/position/Server.java b/common/src/main/java/net/william278/huskhomes/position/Server.java index a14b3827..649298bd 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Server.java +++ b/common/src/main/java/net/william278/huskhomes/position/Server.java @@ -8,20 +8,20 @@ import org.jetbrains.annotations.NotNull; public class Server { /** - * Proxy-defined identifier of this server + * Proxy-defined name of this server */ @NotNull - public String id; + public String name; - public Server(@NotNull String id) { - this.id = id; + public Server(@NotNull String name) { + this.name = name; } @Override public boolean equals(Object other) { if (other instanceof Server server) { - // If the id of this server matches another, the servers are the same. - return server.id.equalsIgnoreCase(this.id); + // If the name of this server matches another, the servers are the same. + return server.name.equalsIgnoreCase(this.name); } return super.equals(other); } 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 a1575aeb..a8e7f3ca 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportManager.java @@ -23,8 +23,9 @@ public class TeleportManager { } /** - * Teleport the player to a specified {@link Position} + * Teleport a {@link Player} to a specified {@link Position} * + * @param player the {@link Player} to teleport * @param position the target {@link Position} to teleport to */ public CompletableFuture teleport(Player player, Position position) { @@ -38,7 +39,7 @@ public class TeleportManager { private CompletableFuture teleportCrossServer(Teleport teleport) { return CompletableFuture.supplyAsync(() -> { - + //todo return TeleportResult.COMPLETED_CROSS_SERVER; }); } diff --git a/common/src/main/java/net/william278/huskhomes/util/ResourceReader.java b/common/src/main/java/net/william278/huskhomes/util/ResourceReader.java new file mode 100644 index 00000000..2ca9160b --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/ResourceReader.java @@ -0,0 +1,18 @@ +package net.william278.huskhomes.util; + +import java.io.InputStream; + +/** + * Abstract representation of a reader that reads internal resource files by name + */ +public interface ResourceReader { + + /** + * Gets the resource with given filename and reads it as an {@link InputStream} + * + * @param fileName Name of the resource file to read + * @return The resource, read as an {@link InputStream} + */ + InputStream getResource(String fileName); + +} diff --git a/common/src/main/resources/database/mysql_schema.sql b/common/src/main/resources/database/mysql_schema.sql new file mode 100644 index 00000000..5e08bafc --- /dev/null +++ b/common/src/main/resources/database/mysql_schema.sql @@ -0,0 +1,82 @@ +# Create the positions table if it does not exist +CREATE TABLE IF NOT EXISTS `%positions_table%` +( + `id` integer NOT NULL AUTO_INCREMENT, + `x` double NOT NULL, + `y` double NOT NULL, + `z` double NOT NULL, + `yaw` float NOT NULL, + `pitch` float NOT NULL, + `world_name` varchar(255) NOT NULL, + `world_uuid` char(36) NOT NULL, + `server_name` varchar(255) NOT NULL, + + PRIMARY KEY (`id`) +); + +# Create the player data table if it does not exist +CREATE TABLE IF NOT EXISTS `%players_table%` +( + `uuid` char(36) NOT NULL UNIQUE, + `username` varchar(16) NOT NULL, + `last_position` integer DEFAULT NULL, + `offline_position` integer DEFAULT NULL, + `respawn_position` integer DEFAULT NULL, + `home_slots` integer NOT NULL DEFAULT 0, + `ignoring_requests` boolean NOT NULL DEFAULT FALSE, + `rtp_cooldown` datetime NOT NULL DEFAULT 0, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION +); + +# Create the current cross-server teleports table if it does not exist +CREATE TABLE IF NOT EXISTS `%teleports_table%` +( + `player_uuid` char(36) NOT NULL UNIQUE, + `destination_id` integer NOT NULL, + + PRIMARY KEY (`player_uuid`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); + +# Create the position metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%position_metadata_table%` +( + `id` integer NOT NULL AUTO_INCREMENT, + `name` varchar(64) NOT NULL, + `description` varchar(255) NOT NULL, + `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + + PRIMARY KEY (`id`) +); + +# Create the homes table if it does not exist +CREATE TABLE IF NOT EXISTS `%homes_table%` +( + `uuid` char(36) NOT NULL UNIQUE, + `owner_uuid` char(36) NOT NULL, + `position_id` integer NOT NULL, + `metadata_id` integer NOT NULL, + `public` boolean NOT NULL DEFAULT FALSE, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + FOREIGN KEY (`metadata_id`) REFERENCES `%position_metadata_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); + +# Create the warps table if it does not exist +CREATE TABLE IF NOT EXISTS `%warps_table%` +( + `uuid` char(36) NOT NULL UNIQUE, + `position_id` integer NOT NULL, + `metadata_id` integer NOT NULL, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + FOREIGN KEY (`metadata_id`) REFERENCES `%position_metadata_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); \ No newline at end of file