SQLite, network messaging, caching, redis, more bukkit implementing

This commit is contained in:
William committed 2022-05-25 18:45:10 +01:00
1 parent 28a54b0b4a
commit 052eb57438
24 files changed
+1855 -38

No files matched your search

+5
View File
@@ -4,6 +4,8 @@ dependencies {
implementation 'commons-io:commons-io:2.11.0'
implementation 'de.themoep:minedown:1.7.1-SNAPSHOT'
implementation 'dev.dejvokep:boosted-yaml:1.2'
implementation 'io.papermc:paperlib:1.0.7'
implementation 'redis.clients:jedis:4.2.3'
compileOnly 'org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT'
compileOnly 'org.jetbrains:annotations:23.0.0'
@@ -17,4 +19,7 @@ shadowJar {
relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'org.slf4j', 'net.william278.huskhomes.libraries.slf4j'
relocate 'org.xerial', 'net.william278.huskhomes.libraries'
relocate 'io.papermc.lib', 'net.william278.huskhomes.libraries.paperlib'
relocate 'com.google.code', 'net.william278.huskhomes.libraries'
}
@@ -6,35 +6,81 @@ 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.config.Messages;
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.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.util.BukkitLogger;
import net.william278.huskhomes.util.BukkitResourceReader;
import net.william278.huskhomes.util.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
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 Messages messages;
private BukkitLogger logger;
private BukkitResourceReader resourceReader;
private Server server;
private Database database;
private Cache cache;
@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
*/
public CompletableFuture<Server> getServer(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).thenApply(server -> {
this.server = new Server(server);
return this.server;
});
}
@Override
public void onLoad() {
instance = this;
}
@Override
@@ -46,16 +92,47 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes {
// Load plugin settings and messages
loadConfigData();
//todo set the Server object through sending a plugin message
// server = new Server();
// Initialize the network messenger
if (getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
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);
}
//todo set the Database object by loading the correct database type
// database = new MySqlDatabase(); etc
// Initialize the database
database = switch (settings.getStringValue(Settings.ConfigOption.DATA_STORAGE_TYPE).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(() -> {
// Initialize the cache
cache = new Cache();
cache.initialize(database);
});
}
@Override
public void onDisable() {
if (database != null) {
database.terminate();
}
if (networkMessenger != null) {
networkMessenger.terminate();
}
}
@Override
@@ -64,8 +141,9 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes {
}
@Override
public Set<Player> getOnlinePlayers() {
return null;
public List<Player> getOnlinePlayers() {
return Bukkit.getOnlinePlayers().stream().map(
player -> (Player) BukkitPlayer.adapt(player)).toList();
}
@Override
@@ -78,23 +156,29 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes {
return messages;
}
@Override
public Server getServerData() {
return server;
}
@Override
public Database getDatabase() {
return database;
}
@Override
public Cache getCache() {
return cache;
}
@Override
public boolean isValidPositionOnServer(Position position) {
return false;
final Optional<Location> 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
private void loadConfigData() {
public void loadConfigData() {
try {
settings = Settings.load(YamlDocument.create(new File(getDataFolder(), "config.yml"),
Objects.requireNonNull(resourceReader.getResource("config.yml")),
@@ -110,4 +194,27 @@ public class HuskHomesBukkit extends JavaPlugin implements HuskHomes {
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 class BukkitAdapter {
public static Optional<Location> adaptLocation(net.william278.huskhomes.position.Location location) {
final World world = Bukkit.getWorld(location.world.name);
if (world == null) {
return Optional.empty();
}
return Optional.of(new Location(world, location.x, location.y, location.z,
location.yaw, location.pitch));
}
}
}
@@ -5,6 +5,7 @@ import net.william278.huskhomes.player.BukkitPlayer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
public class BukkitEventProcessor extends EventProcessor implements Listener {
@@ -18,4 +19,9 @@ public class BukkitEventProcessor extends EventProcessor implements Listener {
super.onPlayerJoin(BukkitPlayer.adapt(event.getPlayer()));
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
super.onPlayerLeave(BukkitPlayer.adapt(event.getPlayer()));
}
}
@@ -0,0 +1,197 @@
package net.william278.huskhomes.messenger;
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.player.BukkitPlayer;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.Server;
import org.bukkit.Bukkit;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
/**
* <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> messenger implementation
*/
public class PluginMessenger extends NetworkMessenger implements PluginMessageListener {
/**
* The name of BungeeCord's provided plugin channel.
*
* @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps
* {@code BungeeCord} automatically to the new one (<a href="https://wiki.vg/Plugin_channels#bungeecord:main">source</a>).
* Spigot's <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">official documentation</a>
* still instructs usage of {@code BungeeCord} as the name to use, however. It's all a bit inconsistent, so just in case
* it's best to leave it how it is for to maintain backwards compatibility.
*/
private static final String BUNGEE_PLUGIN_CHANNEL_NAME = "BungeeCord";
@Override
public void initialize(@NotNull HuskHomes implementor) {
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);
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String[]> getOnlinePlayerNames(@NotNull Player requester) {
onlinePlayerNamesRequest = new CompletableFuture<>();
final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput();
pluginMessageWriter.writeUTF("PlayerList");
pluginMessageWriter.writeUTF("ALL");
((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(),
BUNGEE_PLUGIN_CHANNEL_NAME,
pluginMessageWriter.toByteArray());
return onlinePlayerNamesRequest;
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String> getServerName(@NotNull Player requester) {
serverNameRequest = new CompletableFuture<>();
final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput();
pluginMessageWriter.writeUTF("GetServer");
((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(),
BUNGEE_PLUGIN_CHANNEL_NAME,
pluginMessageWriter.toByteArray());
return serverNameRequest;
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<String[]> getOnlineServers(@NotNull Player requester) {
onlineServersRequest = new CompletableFuture<>();
final ByteArrayDataOutput pluginMessageWriter = ByteStreams.newDataOutput();
pluginMessageWriter.writeUTF("GetServers");
((BukkitPlayer) requester).sendPluginMessage(HuskHomesBukkit.getInstance(),
BUNGEE_PLUGIN_CHANNEL_NAME,
pluginMessageWriter.toByteArray());
return onlineServersRequest;
}
@Override
@SuppressWarnings("UnstableApiUsage")
public CompletableFuture<Boolean> sendPlayer(@NotNull Player player, @NotNull Server server) {
return getOnlineServers(player).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(),
BUNGEE_PLUGIN_CHANNEL_NAME,
pluginMessageWriter.toByteArray());
return true;
}
}
return false;
});
}
@Override
public CompletableFuture<Message> sendMessage(@NotNull Player sender, @NotNull Message message) {
final CompletableFuture<Message> repliedMessage = new CompletableFuture<>();
processingMessages.put(message.uuid, repliedMessage);
sendPluginMessage((BukkitPlayer) sender, message);
return repliedMessage;
}
@Override
protected CompletableFuture<Void> sendReply(@NotNull Player replier, @NotNull Message reply) {
return sendPluginMessage((BukkitPlayer) replier, reply);
}
@SuppressWarnings("UnstableApiUsage")
private CompletableFuture<Void> sendPluginMessage(@NotNull BukkitPlayer player, @NotNull Message message) {
return CompletableFuture.runAsync(() -> {
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("ForwardToPlayer");
messageWriter.writeUTF(message.targetPlayer);
messageWriter.writeUTF(NETWORK_MESSAGE_CHANNEL);
// Write the plugin message
try (ByteArrayOutputStream messageByteOutputStream = new ByteArrayOutputStream()) {
try (DataOutputStream messageDataOutputStream = new DataOutputStream(messageByteOutputStream)) {
messageDataOutputStream.writeUTF(message.toJson());
messageWriter.writeShort(messageByteOutputStream.toByteArray().length);
messageWriter.write(messageByteOutputStream.toByteArray());
}
} catch (IOException e) {
HuskHomesBukkit.getInstance().getLoggingAdapter().log(Level.SEVERE,
"An error occurred dispatching a plugin message", e);
}
// Send the written message
player.sendPluginMessage(HuskHomesBukkit.getInstance(),
BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray());
});
}
@Override
public void terminate() {
Bukkit.getMessenger().unregisterIncomingPluginChannel(HuskHomesBukkit.getInstance());
Bukkit.getMessenger().unregisterIncomingPluginChannel(HuskHomesBukkit.getInstance());
}
@Override
@SuppressWarnings("UnstableApiUsage")
public void onPluginMessageReceived(@NotNull String channel, @NotNull org.bukkit.entity.Player player,
byte @NotNull [] messageBytes) {
if (!channel.equals(BUNGEE_PLUGIN_CHANNEL_NAME)) {
return;
}
final ByteArrayDataInput pluginMessage = ByteStreams.newDataInput(messageBytes);
final String subChannel = pluginMessage.readUTF();
switch (subChannel) {
case NETWORK_MESSAGE_CHANNEL -> {
final short messageInputLength = pluginMessage.readShort();
final byte[] messageInputBytes = new byte[messageInputLength];
pluginMessage.readFully(messageInputBytes);
// Read the message in byte-by-byte and parse it
try (DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageInputBytes))) {
final Message message = Message.fromJson(messageReader.readUTF());
// Ignore plugin messages to other clusters
if (message.clusterId != clusterId) {
return;
}
handleMessage(BukkitPlayer.adapt(player), message);
} catch (IOException e) {
HuskHomesBukkit.getInstance().getLoggingAdapter().log(Level.SEVERE,
"Failed to read an inbound plugin message", e);
}
}
case "GetServer" -> {
final String serverName = pluginMessage.readUTF();
if (serverNameRequest != null) {
serverNameRequest.completeAsync(() -> serverName);
}
}
case "PlayerList" -> {
final String serverName = pluginMessage.readUTF();
final String[] playerNames = pluginMessage.readUTF().split(", ");
if (onlinePlayerNamesRequest != null) {
onlinePlayerNamesRequest.completeAsync(() -> playerNames);
}
}
case "GetServers" -> {
final String[] serverNames = pluginMessage.readUTF().split(", ");
if (onlineServersRequest != null) {
onlineServersRequest.completeAsync(() -> serverNames);
}
}
}
}
}
@@ -0,0 +1,73 @@
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.redis.RedisWorker;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Redis (Jedis) messenger implementation
*/
public class RedisMessenger extends PluginMessenger {
/**
* The {@link RedisWorker} that will manage the connection to the Redis database via Jedis
*/
private RedisWorker redisWorker;
@Override
public void initialize(@NotNull HuskHomes implementor) {
super.initialize(implementor);
redisWorker = new RedisWorker(implementor.getSettings());
redisWorker.initialize();
new Thread(() -> {
try (Jedis jedis = redisWorker.jedisPool.getResource()) {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String encodedMessage) {
if (!channel.equals(NETWORK_MESSAGE_CHANNEL)) {
return;
}
final Message message = Message.fromJson(encodedMessage);
if (message.clusterId != clusterId) {
return;
}
final Optional<BukkitPlayer> receiver = BukkitPlayer.get(message.targetPlayer);
if (receiver.isEmpty()) {
return;
}
handleMessage(receiver.get(), message);
}
});
}
}, "Redis Subscriber").start();
}
@Override
public CompletableFuture<Message> sendMessage(@NotNull Player sender, @NotNull Message message) {
final CompletableFuture<Message> repliedMessage = new CompletableFuture<>();
processingMessages.put(message.uuid, repliedMessage);
redisWorker.sendMessage(message);
return repliedMessage;
}
@Override
protected CompletableFuture<Void> sendReply(@NotNull Player replier, @NotNull Message reply) {
return redisWorker.sendMessage(reply);
}
@Override
public void terminate() {
redisWorker.terminate();
super.terminate();
}
}
@@ -1,10 +1,14 @@
package net.william278.huskhomes.player;
import de.themoep.minedown.MineDown;
import io.papermc.lib.PaperLib;
import net.william278.huskhomes.HuskHomesBukkit;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
@@ -31,10 +35,22 @@ public class BukkitPlayer implements Player {
return Optional.empty();
}
public static Optional<BukkitPlayer> 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) {
return new BukkitPlayer(player);
}
public org.bukkit.entity.Player getBukkitPlayer() {
return bukkitPlayer;
}
@Override
public String getName() {
return bukkitPlayer.getName();
@@ -46,8 +62,13 @@ public class BukkitPlayer implements Player {
}
@Override
public Position getPosition() {
return null;
public CompletableFuture<Position> getPosition() {
final org.bukkit.Location location = bukkitPlayer.getLocation();
return HuskHomesBukkit.getInstance().getServer(this).thenApplyAsync(server ->
new Position(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(),
new net.william278.huskhomes.position.World(bukkitPlayer.getWorld().getName(),
bukkitPlayer.getWorld().getUID()), server));
}
@Override
@@ -62,7 +83,17 @@ public class BukkitPlayer implements Player {
@Override
public CompletableFuture<TeleportResult> teleport(Location location) {
return null; //todo
final Optional<org.bukkit.Location> bukkitLocation = HuskHomesBukkit.BukkitAdapter.adaptLocation(location);
if (bukkitLocation.isEmpty()) {
return CompletableFuture.supplyAsync(() -> TeleportResult.FAILED_INVALID_WORLD);
}
assert bukkitLocation.get().getWorld() != null;
if (!bukkitLocation.get().getWorld().getWorldBorder().isInside(bukkitLocation.get())) {
return CompletableFuture.supplyAsync(() -> TeleportResult.FAILED_ILLEGAL_COORDINATES);
}
return PaperLib.teleportAsync(bukkitPlayer, bukkitLocation.get(),
PlayerTeleportEvent.TeleportCause.COMMAND)
.thenApplyAsync(result -> TeleportResult.COMPLETED_LOCALLY);
}
@Override
@@ -75,4 +106,10 @@ public class BukkitPlayer implements Player {
return null; //todo
}
/**
* Send a Bukkit plugin message
*/
public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, byte @NotNull [] message) {
bukkitPlayer.sendPluginMessage(source, channel, message);
}
}
@@ -34,4 +34,5 @@ public class BukkitLogger implements Logger {
public void config(String message) {
logger.config(message);
}
}
@@ -2,6 +2,7 @@ package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomesBukkit;
import java.io.File;
import java.io.InputStream;
public class BukkitResourceReader implements ResourceReader {
@@ -17,4 +18,9 @@ public class BukkitResourceReader implements ResourceReader {
return plugin.getResource(fileName);
}
@Override
public File getDataFolder() {
return plugin.getDataFolder();
}
}
+8
View File
@@ -2,7 +2,11 @@ dependencies {
compileOnly 'commons-io:commons-io:2.11.0'
compileOnly 'dev.dejvokep:boosted-yaml:1.2'
compileOnly 'de.themoep:minedown:1.7.1-SNAPSHOT'
compileOnly 'redis.clients:jedis:4.2.3'
implementation 'com.zaxxer:HikariCP:5.0.1'
implementation 'org.xerial:sqlite-jdbc:3.36.0.3'
implementation 'com.google.code.gson:gson:2.9.0'
}
shadowJar {
@@ -13,4 +17,8 @@ shadowJar {
relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'org.slf4j', 'net.william278.huskhomes.libraries.slf4j'
relocate 'org.xerial', 'net.william278.huskhomes.libraries'
relocate 'io.papermc.lib', 'net.william278.huskhomes.libraries.paperlib'
relocate 'com.google.code', 'net.william278.huskhomes.libraries'
relocate 'redis.clients', 'net.william278.huskhomes.libraries.jedis'
}
@@ -1,13 +1,14 @@
package net.william278.huskhomes;
import net.william278.huskhomes.cache.Cache;
import net.william278.huskhomes.config.Messages;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.data.Database;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.util.Logger;
import java.util.List;
import java.util.Set;
/**
@@ -27,7 +28,7 @@ public interface HuskHomes {
*
* @return a {@link Set} of currently online {@link Player}s
*/
Set<Player> getOnlinePlayers();
List<Player> getOnlinePlayers();
/**
* The plugin {@link Settings} loaded from file
@@ -43,13 +44,6 @@ public interface HuskHomes {
*/
Messages getMessages();
/**
* The {@link Server} the plugin is running on
*
* @return the {@link Server} object representing the implementing server
*/
Server getServerData();
/**
* The {@link Database} that stores persistent plugin data
*
@@ -57,6 +51,38 @@ public interface HuskHomes {
*/
Database getDatabase();
/**
* The {@link Cache} that holds cached data
*
* @return the plugin {@link Cache}
*/
Cache getCache();
/**
* Returns true if the position is a valid location on the server
*
* @param position The {@link Position} to check
* @return {@code true} if the position is a valid one on the server; {@code false} otherwise
*/
boolean isValidPositionOnServer(Position position);
/**
* (Re)-load config and message data from files
*/
void loadConfigData();
/**
* Get the HuskHomes plugin version
*
* @return the HuskHomes plugin version string
*/
String getPluginVersion();
/**
* Get the platform type (e.g. Spigot, Paper etc)
*
* @return the type of server platform string
*/
String getPlatformType();
}
@@ -0,0 +1,55 @@
package net.william278.huskhomes.cache;
import net.william278.huskhomes.data.Database;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* A cache used to hold persistently used data
*/
public class Cache {
/**
* Cached home names - maps a {@link UUID} to a list of their homes
*/
public final HashMap<UUID, List<String>> homes;
/**
* Cached home names - maps a username to a list of their public homes
*/
public final HashMap<String, List<String>> publicHomes;
/**
* Cached warp names
*/
public final List<String> warps;
/**
* Create a new cache
*/
public Cache() {
this.homes = new HashMap<>();
this.publicHomes = new HashMap<>();
this.warps = new ArrayList<>();
}
/**
* Initialize the cache, request basic data to load into memory
*
* @param database the database to load data from
*/
public void initialize(@NotNull Database database) {
CompletableFuture.runAsync(() -> {
database.getPublicHomes().thenAccept(publicHomeList -> publicHomeList.forEach(home ->
this.publicHomes.computeIfAbsent(home.owner.username, key -> new ArrayList<>()).add(home.meta.name)));
database.getWarps().thenAccept(warpsList -> warpsList.forEach(warp ->
this.warps.add(warp.meta.name)));
});
}
}
@@ -384,4 +384,10 @@ public abstract class Database {
*/
public abstract CompletableFuture<Void> deleteWarp(@NotNull UUID uuid);
/**
* Close any remaining connection to the database source
*/
public abstract void terminate();
}
@@ -418,11 +418,11 @@ public class MySqlDatabase extends Database {
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`=?;"""))) {
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();
@@ -880,4 +880,13 @@ public class MySqlDatabase extends Database {
});
}
@Override
public void terminate() {
if (dataSource != null) {
if (!dataSource.isClosed()) {
dataSource.close();
}
}
}
}
@@ -0,0 +1,866 @@
package net.william278.huskhomes.data;
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.*;
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.File;
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;
/**
* An SQLite implementation of the plugin {@link Database}
*/
@SuppressWarnings("DuplicatedCode")
public class SqLiteDatabase extends Database {
/**
* Path to the SQLite HuskHomesData.db file
*/
private final File databaseFile;
/**
* The name of the database file
*/
private static final String DATABASE_FILE_NAME = "HuskHomesData.db";
/**
* The persistent SQLite database connection
*/
private Connection connection;
public SqLiteDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
super(settings, logger, resourceReader);
this.databaseFile = new File(resourceReader.getDataFolder(), DATABASE_FILE_NAME);
}
private Connection getConnection() throws SQLException {
if (connection == null) {
setConnection();
} else if (connection.isClosed()) {
setConnection();
}
return connection;
}
private void setConnection() {
try {
// Ensures the database file exists
if (databaseFile.createNewFile()) {
getLogger().log(Level.INFO, "Created the SQLite database file");
}
// Establish the connection using the JDBC SQLite driver
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath());
} catch (IOException e) {
getLogger().log(Level.SEVERE, "An exception occurred creating the database file", e);
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e);
}
}
@Override
public CompletableFuture<Void> initialize() {
return CompletableFuture.runAsync(() -> {
setConnection();
// Prepare database schema; make tables if they don't exist
try {
// Load database schema CREATE statements from schema file
final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql");
try (Statement statement = getConnection().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 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 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<Void> ensureUser(@NotNull Player player) {
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 {
try (PreparedStatement statement = getConnection().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 {
try (PreparedStatement statement = getConnection().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<Optional<UserData>> getUserByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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 UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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 UserData(
UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username"),
resultSet.getInt("home_slots"),
resultSet.getBoolean("ignoring_requests"),
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<List<Home>> getHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>();
try {
try (PreparedStatement statement = getConnection().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<List<Warp>> getWarps() {
return CompletableFuture.supplyAsync(() -> {
final List<Warp> warps = new ArrayList<>();
try {
try (PreparedStatement statement = getConnection().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<List<Home>> getPublicHomes() {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>();
try {
try (PreparedStatement statement = getConnection().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<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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<Optional<Home>> getHome(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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<Optional<Warp>> getWarp(@NotNull String warpName) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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<Optional<Warp>> getWarp(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().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<Optional<Teleport>> getCurrentTeleport(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%teleports_table%`
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Teleport(user,
new Position(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")))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + user.username, e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Void> updateUserData(@NotNull UserData userData) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
WHERE `uuid`=?"""))) {
statement.setInt(1, userData.homeSlots);
statement.setBoolean(2, userData.isIgnoringTeleports);
statement.setLong(3, userData.rtpCooldown);
statement.setString(4, userData.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.username + " on the database", e);
}
});
}
@Override
public CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
return CompletableFuture.runAsync(() -> {
if (teleport == null) {
// Clear the user's current teleport
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%teleports_table%`
WHERE `player_uuid`=?;"""))) {
statement.setString(1, user.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
}
} else {
// Set the user's teleport into the database
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`)
VALUES (?,?);"""))) {
statement.setString(1, user.uuid.toString());
statement.setInt(2, setPosition(teleport.target, getConnection()));
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e);
}
}
});
}
@Override
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Position(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"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `last_position`=?
WHERE `uuid`=?;"""))) {
statement.setInt(1, setPosition(position, getConnection()));
statement.setString(2, user.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
}
});
}
@Override
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Position(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"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
statement.setInt(1, setPosition(position, getConnection()));
statement.setString(2, user.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
}
});
}
@Override
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Position(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"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position) {
return CompletableFuture.runAsync(() -> {
if (position == null) {
// Clear the respawn position
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `respawn_position`=NULL
WHERE `uuid`=?;"""))) {
statement.setString(1, user.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
}
} else {
// Set the respawn position
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
statement.setInt(1, setPosition(position, getConnection()));
statement.setString(2, user.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
}
}
});
}
@Override
public CompletableFuture<Void> setHome(@NotNull Home home) {
return CompletableFuture.runAsync(() -> getHome(home.uuid)
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%homes_table%`
SET `position_id`=?, `metadata_id`=?, `public`=?
WHERE `uuid`=?;"""))) {
statement.setInt(1, setPosition(home, getConnection()));
statement.setInt(2, setPositionMeta(home.meta, getConnection()));
statement.setBoolean(3, home.isPublic);
statement.setString(4, home.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.owner.username, e);
}
}, () -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `owner_uuid`, `position_id`, `metadata_id`, `public`)
VALUES (?,?,?,?,?);"""))) {
statement.setString(1, home.uuid.toString());
statement.setString(2, home.owner.uuid.toString());
statement.setInt(3, setPosition(home, getConnection()));
statement.setInt(4, setPositionMeta(home.meta, getConnection()));
statement.setBoolean(5, home.isPublic);
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e);
}
})));
}
@Override
public CompletableFuture<Void> setWarp(@NotNull Warp warp) {
return CompletableFuture.runAsync(() -> getWarp(warp.uuid)
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%warps_table%`
SET `position_id`=?, `metadata_id`=?
WHERE `uuid`=?;"""))) {
statement.setInt(1, setPosition(warp, getConnection()));
statement.setInt(2, setPositionMeta(warp.meta, getConnection()));
statement.setString(3, warp.uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e);
}
}, () -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `position_id`, `metadata_id`)
VALUES (?,?,?);"""))) {
statement.setString(1, warp.uuid.toString());
statement.setInt(2, setPosition(warp, getConnection()));
statement.setInt(3, setPositionMeta(warp.meta, getConnection()));
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e);
}
})));
}
@Override
public CompletableFuture<Void> deleteHome(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%homes_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e);
}
});
}
@Override
public CompletableFuture<Void> deleteWarp(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%warps_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e);
}
});
}
@Override
public void terminate() {
try {
if (connection != null) {
if (!connection.isClosed()) {
connection.close();
}
}
} catch (SQLException e) {
getLogger().log(Level.WARNING, "Failed to properly close the SQLite connection");
}
}
}
@@ -6,13 +6,15 @@ import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Collectors;
/**
* A handler for when events take place
*/
public class EventProcessor {
@NotNull
private final HuskHomes implementor;
protected final HuskHomes implementor;
public EventProcessor(@NotNull HuskHomes implementor) {
this.implementor = implementor;
@@ -26,6 +28,7 @@ public class EventProcessor {
public void onPlayerJoin(@NotNull Player player) {
// Ensure the player is present on the database first
implementor.getDatabase().ensureUser(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))
@@ -39,7 +42,17 @@ public class EventProcessor {
}
})));
}
// Cache this user's homes
implementor.getDatabase().getHomes(new User(player)).thenAccept(homes ->
implementor.getCache().homes.put(player.getUuid(),
homes.stream().map(home -> home.meta.name).collect(Collectors.toList())));
});
}
public void onPlayerLeave(@NotNull Player player) {
// Remove this user's home cache
implementor.getCache().homes.remove(player.getUuid());
}
}
@@ -0,0 +1,93 @@
package net.william278.huskhomes.messenger;
import com.google.gson.*;
import com.google.gson.annotations.SerializedName;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* A message sent cross-proxy to a player
*/
public class Message {
/**
* A unique ID representing this message
*/
@NotNull
public UUID uuid;
/**
* The type of the message
*/
@NotNull
public MessageType type;
/**
* The kind of message this is - {@link MessageKind#MESSAGE} or a {@link MessageKind#REPLY} to a message.
*/
@NotNull
public MessageKind kind;
/**
* Username of the target player the message is bound for
*/
@SerializedName("target_player")
@NotNull
public String targetPlayer;
/**
* Username of the sender of the message
*/
@NotNull
public String sender;
/**
* ID of the cluster this message is for
*/
@SerializedName("cluster_id")
public int clusterId;
/**
* Data to send in the message
*/
@NotNull
public String payload;
public Message(@NotNull MessageType type, @NotNull String sender, @NotNull String targetPlayer,
@NotNull MessagePayload payload, @NotNull MessageKind messageKind, int clusterId) {
this.type = type;
this.sender = sender;
this.targetPlayer = targetPlayer;
this.payload = payload.toJson();
this.kind = messageKind;
this.clusterId = clusterId;
this.uuid = UUID.randomUUID();
}
public String toJson() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
public static Message fromJson(String json) {
return new GsonBuilder().setPrettyPrinting().create().fromJson(json, Message.class);
}
public enum MessageType {
TP_REQUEST
}
public enum MessageKind {
MESSAGE,
REPLY
}
@Override
public boolean equals(Object other) {
if (other instanceof Message message) {
return message.uuid.equals(this.uuid);
}
return super.equals(other);
}
}
@@ -0,0 +1,10 @@
package net.william278.huskhomes.messenger;
/**
* Represents data that can be sent as a payload in a {@link Message}
*/
public interface MessagePayload {
String toJson();
}
@@ -0,0 +1,142 @@
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.Server;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public abstract class NetworkMessenger {
/**
* Name of the network message channel for HuskHomes messages
*/
public static final String NETWORK_MESSAGE_CHANNEL = "huskhomes:main";
/**
* Map of message UUIDs to messages being processed
*/
protected HashMap<UUID, CompletableFuture<Message>> processingMessages;
/**
* Future for processing {@link #getServerName(Player)} requests
*/
protected CompletableFuture<String> serverNameRequest;
/**
* Future for processing {@link #getOnlinePlayerNames(Player)} requests
*/
protected CompletableFuture<String[]> onlinePlayerNamesRequest;
/**
* Future for processing {@link #getOnlineServers(Player)} requests
*/
protected CompletableFuture<String[]> onlineServersRequest;
/**
* ID of the HuskHomes network cluster this server is on
*/
protected int clusterId;
/**
* Initialize the network messenger
*
* @param implementor Instance of the implementing plugin
*/
public void initialize(@NotNull HuskHomes implementor) {
this.processingMessages = new HashMap<>();
this.clusterId = implementor.getSettings().getIntegerValue(Settings.ConfigOption.CLUSTER_ID);
}
/**
* Fetch a list of online player usernames from the proxy
*
* @param requester {@link Player} to send the request
* @return Future returning a {@link List} of usernames of players on the proxy network
*/
public abstract CompletableFuture<String[]> getOnlinePlayerNames(@NotNull Player requester);
/**
* Fetch the name of this server on the proxy network
*
* @param requester {@link Player} to send the request
* @return Future returning the name of this server on the network
*/
public abstract CompletableFuture<String> getServerName(@NotNull Player requester);
/**
* Fetch a list of online server names proxy
*
* @param requester {@link Player} to send the request
* @return Future returning a {@link List} of online servers connected to the proxy network
*/
public abstract CompletableFuture<String[]> getOnlineServers(@NotNull Player requester);
/**
* Send a {@link Player} to a target {@link Server} on the proxy network
*
* @param server The {@link Server} to send the {@link Player} to
* @return A future, returning {@code true} if the player was sent.<p>
* If the player could not be sent (i.e. the server was offline), this will return {@code false}
*/
public abstract CompletableFuture<Boolean> sendPlayer(@NotNull Player player, @NotNull Server server);
/**
* Send a network {@link Message} to a target player on the proxy
*
* @param message The {@link Message} to send
* @return A future containing a reply to the {@link Message} that was sent
*/
public abstract CompletableFuture<Message> sendMessage(@NotNull Player sender, @NotNull Message message);
/**
* Send a reply to a received {@link Message}
*
* @param reply The reply {@link Message} to send
* @return A future completing when the message has been sent
*/
protected abstract CompletableFuture<Void> sendReply(@NotNull Player replier, @NotNull Message reply);
/**
* Handle and action received network {@link Message}s
*
* @param receiver The online {@link Player} receiving the message
* @param message The received {@link Message}
*/
protected final void handleMessage(@NotNull Player receiver, @NotNull Message message) {
switch (message.kind) {
// Handle a message and send reply
case MESSAGE -> {
// Handle different message types and apply changes for reply message
switch (message.type) {
case TP_REQUEST -> {
message = message;
}
}
// Reply with the modified message
message.targetPlayer = message.sender;
message.sender = receiver.getName();
sendReply(receiver, message);
}
// Handle a reply message
case REPLY -> {
if (processingMessages.containsKey(message.uuid)) {
final Message finalMessage = message;
processingMessages.get(message.uuid).completeAsync(() -> finalMessage);
}
}
}
}
/**
* Close the network messenger
*/
public abstract void terminate();
}
@@ -33,7 +33,7 @@ public interface Player {
*
* @return the player's current {@link Position}
*/
Position getPosition();
CompletableFuture<Position> getPosition();
/**
* Returns if the player has the permission node
@@ -1,6 +1,5 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
@@ -0,0 +1,63 @@
package net.william278.huskhomes.redis;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.NetworkMessenger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.concurrent.CompletableFuture;
/**
* Handles Redis database pub/sub network messaging requests over Jedis
*/
public class RedisWorker {
@NotNull
private final String redisHost;
private final int redisPort;
@Nullable
private final String redisPassword;
private final boolean redisSsl;
public JedisPool jedisPool;
public RedisWorker(@NotNull Settings settings) {
this.redisHost = settings.getStringValue(Settings.ConfigOption.REDIS_HOST);
this.redisPort = settings.getIntegerValue(Settings.ConfigOption.REDIS_PORT);
this.redisPassword = settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD).isEmpty() ? null : settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD);
this.redisSsl = !redisHost.equalsIgnoreCase("localhost") && !redisHost.equalsIgnoreCase("127.0.0.1") && settings.getBooleanValue(Settings.ConfigOption.REDIS_USE_SSL);
}
/**
* Initialize the JedisPool connection
*/
public void initialize() {
if (redisPassword == null) {
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisSsl);
} else {
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisPassword, redisSsl);
}
}
public CompletableFuture<Void> sendMessage(@NotNull Message message) {
return CompletableFuture.runAsync(() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(NetworkMessenger.NETWORK_MESSAGE_CHANNEL, message.toJson());
}
});
}
/**
* Close the JedisPool connection
*/
public void terminate() {
if (jedisPool != null) {
if (!jedisPool.isClosed()) {
jedisPool.close();
}
}
}
}
@@ -1,6 +1,5 @@
package net.william278.huskhomes.teleport;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
@@ -1,5 +1,6 @@
package net.william278.huskhomes.util;
import java.io.File;
import java.io.InputStream;
/**
@@ -15,4 +16,11 @@ public interface ResourceReader {
*/
InputStream getResource(String fileName);
/**
* Gets the plugin data folder where plugin configuration and data are kept
*
* @return the plugin data directory
*/
File getDataFolder();
}
@@ -0,0 +1,88 @@
/* Ensure data gets correctly encoded in UTF-8 */
PRAGMA encoding = 'UTF-8';
/* Ensure foreign key constraints are enforced */
PRAGMA foreign_keys = ON;
/* Create the positions table if it does not exist */
CREATE TABLE IF NOT EXISTS `%positions_table%`
(
`id` integer NOT NULL,
`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,
`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
);