Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polar #47

Merged
merged 3 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ dependencies {
annotationProcessor("org.projectlombok:lombok:1.18.32") // lombok
implementation("org.tomlj:tomlj:1.1.1") // Config lang
implementation("com.rabbitmq:amqp-client:5.21.0") // Message broker
implementation("dev.hollowcube:polar:1.8.1") // Polar
}

tasks.withType<Jar> {
Expand Down
46 changes: 30 additions & 16 deletions src/main/java/net/cytonic/cytosis/Cytosis.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import net.cytonic.cytosis.logging.Logger;
import net.cytonic.cytosis.messaging.MessagingManager;
import net.cytonic.cytosis.ranks.RankManager;
import net.hollowcube.polar.PolarLoader;
import net.minestom.server.MinecraftServer;
import net.minestom.server.command.CommandManager;
import net.minestom.server.command.ConsoleSender;
Expand All @@ -22,10 +23,8 @@
import net.minestom.server.instance.block.Block;
import net.minestom.server.network.ConnectionManager;
import net.minestom.server.permission.Permission;

import java.util.*;


@Getter
public class Cytosis {

Expand Down Expand Up @@ -72,10 +71,6 @@ public static void main(String[] args) {
Logger.info("Starting connection manager.");
connectionManager = MinecraftServer.getConnectionManager();


Logger.info("Starting manager.");
databaseManager = new DatabaseManager();

// Commands
Logger.info("Starting command manager.");
commandManager = MinecraftServer.getCommandManager();
Expand Down Expand Up @@ -144,23 +139,42 @@ public static void mojangAuth() {
MojangAuth.init(); //VERY IMPORTANT! (This is online mode!)
}

public static void completeNonEssentialTasks(long start) {
// basic world generator
Logger.info("Generating basic world");
defaultInstance.setGenerator(unit -> unit.modifier().fillHeight(0, 1, Block.WHITE_STAINED_GLASS));
defaultInstance.setChunkSupplier(LightingChunk::new);
public static void loadWorld() {
if (CytosisSettings.SERVER_WORLD_NAME.isEmpty()) {
Logger.info("Generating basic world");
defaultInstance.setGenerator(unit -> unit.modifier().fillHeight(0, 1, Block.WHITE_STAINED_GLASS));
defaultInstance.setChunkSupplier(LightingChunk::new);
Logger.info("Basic world loaded!");
return;
}
Logger.info(STR."Loading world '\{CytosisSettings.SERVER_WORLD_NAME}'");
databaseManager.getDatabase().getWorld(CytosisSettings.SERVER_WORLD_NAME).whenComplete((polarWorld, throwable) -> {
if (throwable != null) {
Logger.error("An error occurred whilst initializing the world!", throwable);
} else {
defaultInstance.setChunkLoader(new PolarLoader(polarWorld));
defaultInstance.setChunkSupplier(LightingChunk::new);
Logger.info("World loaded!");
}
});
}

public static void completeNonEssentialTasks(long start) {
Logger.info("Initializing database");
databaseManager = new DatabaseManager();
databaseManager.setupDatabase();
Logger.info("Database initialized!");
Logger.info("Setting up event handlers");
eventHandler = new EventHandler(MinecraftServer.getGlobalEventHandler());
eventHandler.init();

Logger.info("Initializing server events");
ServerEventListeners.initServerEvents();

Logger.info("Initializing database");
databaseManager.setupDatabase();

MinecraftServer.getSchedulerManager().buildShutdownTask(() -> databaseManager.shutdown());
MinecraftServer.getSchedulerManager().buildShutdownTask(() -> {
databaseManager.shutdown();
Logger.info("Good night!");
});

Logger.info("Initializing server commands");
commandHandler = new CommandHandler();
Expand All @@ -183,7 +197,7 @@ public static void completeNonEssentialTasks(long start) {
// Start the server
Logger.info(STR."Server started on port \{CytosisSettings.SERVER_PORT}");
minecraftServer.start("0.0.0.0", CytosisSettings.SERVER_PORT);

long end = System.currentTimeMillis();
Logger.info(STR."Server started in \{end - start}ms!");

Expand Down
20 changes: 0 additions & 20 deletions src/main/java/net/cytonic/cytosis/DatabaseManager.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import net.cytonic.cytosis.Cytosis;
import net.minestom.server.command.CommandManager;
import net.minestom.server.entity.Player;

import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/net/cytonic/cytosis/commands/RankCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,15 @@
import net.minestom.server.command.builder.arguments.ArgumentType;
import net.minestom.server.command.builder.suggestion.SuggestionEntry;
import net.minestom.server.entity.Player;

import java.util.Locale;

import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM;

public class RankCommand extends Command {

public RankCommand() {
super("rank");
setCondition((sender, _) -> sender.hasPermission("cytosis.commands.rank"));
setDefaultExecutor((sender, _) -> sender.sendMessage(MM."<red>You must specify a valid rank and player!"));
setDefaultExecutor((sender, _) -> sender.sendMessage(MM."<red>You must specify a valid player and rank!"));

var rankArg = ArgumentType.Enum("rank", PlayerRank.class).setFormat(ArgumentEnum.Format.LOWER_CASED);
rankArg.setCallback((sender, exception) -> sender.sendMessage(STR."The rank \{exception.getInput()} is invalid!"));
Expand Down Expand Up @@ -50,7 +48,7 @@ public RankCommand() {

Cytosis.getDatabaseManager().getDatabase().getPlayerRank(player.getUuid()).whenComplete((rank, throwable) -> {
if (throwable != null) {
sender.sendMessage("An error occured whilst fetching the old rank!");
sender.sendMessage("An error occurred whilst fetching the old rank!");
return;
}

Expand Down
10 changes: 10 additions & 0 deletions src/main/java/net/cytonic/cytosis/config/CytosisSettings.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package net.cytonic.cytosis.config;

import net.cytonic.cytosis.logging.Logger;
import net.cytonic.cytosis.utils.PosSerializer;
import net.minestom.server.coordinate.Pos;
import java.util.Map;

/**
Expand All @@ -25,6 +27,8 @@ public class CytosisSettings {
public static boolean SERVER_PROXY_MODE = false;
public static String SERVER_SECRET = "";
public static int SERVER_PORT = 25565;
public static String SERVER_WORLD_NAME = "";
public static Pos SERVER_SPAWN_POS = new Pos(0,1,0);
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
// RabbitMQ
public static boolean RABBITMQ_ENABLED = false;
public static String RABBITMQ_HOST = "";
Expand Down Expand Up @@ -57,6 +61,8 @@ public static void inportConfig(Map<String, Object> config) {
case "server.proxy_mode" -> SERVER_PROXY_MODE = (boolean) value;
case "server.secret" -> SERVER_SECRET = (String) value;
case "server.port" -> SERVER_PORT = toInt(value);
case "server.world_name" -> SERVER_WORLD_NAME = (String) value;
case "server.spawn_point" -> SERVER_SPAWN_POS = PosSerializer.deserialize((String) value);

// RabbitMQ
case "rabbitmq.host" -> RABBITMQ_HOST = (String) value;
Expand Down Expand Up @@ -98,6 +104,8 @@ public static void loadEnvironmentVariables() {
if (!(System.getenv("SERVER_PROXY_MODE") == null)) CytosisSettings.SERVER_PROXY_MODE = Boolean.parseBoolean(System.getenv("SERVER_PROXY_MODE"));
if (!(System.getenv("SERVER_SECRET") == null)) CytosisSettings.SERVER_SECRET = System.getenv("SERVER_SECRET");
if (!(System.getenv("SERVER_PORT") == null)) CytosisSettings.SERVER_PORT = Integer.parseInt(System.getenv("SERVER_PORT"));
if (!(System.getenv("SERVER_WORLD_NAME") == null)) CytosisSettings.SERVER_WORLD_NAME = System.getenv("SERVER_WORLD_NAME");
if (!(System.getenv("SERVER_SPAWN_POINT") == null)) CytosisSettings.SERVER_SPAWN_POS = PosSerializer.deserialize(System.getenv("SERVER_SPAWN_POINT"));
// RabbitMQ
if (!(System.getenv("RABBITMQ_ENABLED") == null)) CytosisSettings.RABBITMQ_ENABLED = Boolean.parseBoolean(System.getenv("RABBITMQ_ENABLED"));
if (!(System.getenv("RABBITMQ_HOST") == null)) CytosisSettings.RABBITMQ_HOST = System.getenv("RABBITMQ_HOST");
Expand Down Expand Up @@ -125,6 +133,8 @@ public static void loadCommandArgs() {
if (!(System.getProperty("SERVER_PROXY_MODE") == null)) CytosisSettings.SERVER_PROXY_MODE = Boolean.parseBoolean(System.getProperty("SERVER_PROXY_MODE"));
if (!(System.getProperty("SERVER_SECRET") == null)) CytosisSettings.SERVER_SECRET = System.getProperty("SERVER_SECRET");
if (!(System.getProperty("SERVER_PORT") == null)) CytosisSettings.SERVER_PORT = Integer.parseInt(System.getProperty("SERVER_PORT"));
if (!(System.getProperty("SERVER_WORLD_NAME") == null)) CytosisSettings.SERVER_WORLD_NAME = System.getProperty("SERVER_WORLD_NAME");
if (!(System.getProperty("SERVER_SPAWN_POINT") == null)) CytosisSettings.SERVER_SPAWN_POS = PosSerializer.deserialize(System.getProperty("SERVER_SPAWN_POINT"));
// RabbitMQ
if (!(System.getProperty("RABBITMQ_ENABLED") == null)) CytosisSettings.RABBITMQ_ENABLED = Boolean.parseBoolean(System.getProperty("RABBITMQ_ENABLED"));
if (!(System.getProperty("RABBITMQ_HOST") == null)) CytosisSettings.RABBITMQ_HOST = System.getProperty("RABBITMQ_HOST");
Expand Down
118 changes: 113 additions & 5 deletions src/main/java/net/cytonic/cytosis/data/Database.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package net.cytonic.cytosis.data;

import net.cytonic.cytosis.Cytosis;
import net.cytonic.cytosis.config.CytosisSettings;
import net.cytonic.cytosis.logging.Logger;
import net.cytonic.cytosis.ranks.PlayerRank;
import net.cytonic.cytosis.utils.PosSerializer;
import net.hollowcube.polar.PolarReader;
import net.hollowcube.polar.PolarWorld;
import net.hollowcube.polar.PolarWriter;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import org.jetbrains.annotations.NotNull;

import java.sql.*;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -48,6 +53,7 @@ public void connect() {
try {
connection = DriverManager.getConnection(STR."jdbc:mysql://\{host}:\{port}/\{database}?useSSL=\{ssl}&autoReconnect=true&allowPublicKeyRetrieval=true", username, password);
Logger.info("Successfully connected to the MySQL Database!");
Cytosis.loadWorld();
} catch (SQLException e) {
Logger.error("Invalid Database Credentials!", e);
MinecraftServer.stopCleanly();
Expand All @@ -73,26 +79,39 @@ public void disconnect() {
public void createTables() {
createRanksTable();
createChatTable();
createWorldTable();
}

private Connection getConnection() {
return connection;
}

/**
* Creates the 'cytonic_chat' table in the database if it doesn't exist.
* The table contains information about player chat messages.
*
* @throws IllegalStateException if the database connection is not open.
*/
private void createChatTable() {
worker.submit(() -> {
if (isConnected()) {
PreparedStatement ps;
try {
ps = getConnection().prepareStatement("CREATE TABLE IF NOT EXISTS cytonicchat (id INT NOT NULL AUTO_INCREMENT, timestamp TIMESTAMP, uuid VARCHAR(36), message TEXT, PRIMARY KEY(id))");
ps = getConnection().prepareStatement("CREATE TABLE IF NOT EXISTS cytonic_chat (id INT NOT NULL AUTO_INCREMENT, timestamp TIMESTAMP, uuid VARCHAR(36), message TEXT, PRIMARY KEY(id))");
ps.executeUpdate();
} catch (SQLException e) {
Logger.error("An error occoured whilst fetching data from the database. Please report the following stacktrace to Foxikle:", e);
Logger.error("An error occurred whilst creating the `cytonic_chat` table.", e);
}
}
});
}

/**
* Creates the 'cytonic_ranks' table in the database if it doesn't exist.
* The table contains information about player ranks.
*
* @throws IllegalStateException if the database connection is not open.
*/
private void createRanksTable() {
worker.submit(() -> {
if (isConnected()) {
Expand All @@ -101,7 +120,27 @@ private void createRanksTable() {
ps = getConnection().prepareStatement("CREATE TABLE IF NOT EXISTS cytonic_ranks (uuid VARCHAR(36), rank_id VARCHAR(16), PRIMARY KEY(uuid))");
ps.executeUpdate();
} catch (SQLException e) {
Logger.error("An error occoured whilst creating the `cytonic_ranks` table.", e);
Logger.error("An error occurred whilst creating the `cytonic_ranks` table.", e);
}
}
});
}

/**
* Creates the 'cytonic_worlds' table in the database if it doesn't exist.
* The table contains information about the worlds stored in the database.
*
* @throws IllegalStateException if the database connection is not open.
*/
public void createWorldTable() {
worker.submit(() -> {
if (isConnected()) {
PreparedStatement ps;
try {
ps = getConnection().prepareStatement("CREATE TABLE IF NOT EXISTS cytonic_worlds (world_name TEXT, world_type TEXT, last_modified TIMESTAMP, world_data MEDIUMBLOB, spawn_point TEXT, extra_data varchar(100))");
ps.executeUpdate();
} catch (SQLException e) {
Logger.error("An error occurred whilst creating the `cytonic_worlds` table.", e);
}
}
});
Expand Down Expand Up @@ -156,16 +195,26 @@ public CompletableFuture<Void> setPlayerRank(UUID uuid, PlayerRank rank) {
future.complete(null);
} catch (SQLException e) {
Logger.error(STR."An error occurred whilst setting the rank of '\{uuid}'");
future.completeExceptionally(e);
}
});
return future;
}

/**
* Adds a players chat message to the database.
*
* @param uuid The player's UUID.
* @param message The player's message.
* @throws IllegalStateException if the database isn't connected.
*/
public void addChat(UUID uuid, String message) {
worker.submit(() -> {
if (!isConnected())
throw new IllegalStateException("The database must have an open connection to add a player's chat!");
PreparedStatement ps;
try {
ps = connection.prepareStatement("INSERT INTO cytonicchat (timestamp, uuid, message) VALUES (CURRENT_TIMESTAMP,?,?)");
ps = connection.prepareStatement("INSERT INTO cytonic_chat (timestamp, uuid, message) VALUES (CURRENT_TIMESTAMP,?,?)");
ps.setString(1, uuid.toString());
ps.setString(2, message);
ps.executeUpdate();
Expand All @@ -174,4 +223,63 @@ public void addChat(UUID uuid, String message) {
}
});
}

/**
* Adds a new world to the database.
*
* @param worldName The name of the world to be added.
* @param worldType The type of the world.
* @param world The PolarWorld object representing the world.
* @param spawnPoint The spawn point of the world.
* @throws IllegalStateException If the database connection is not open.
*/
public void addWorld(String worldName, String worldType, PolarWorld world, Pos spawnPoint) {
if (!isConnected())
throw new IllegalStateException("The database must have an open connection to add a world!");
worker.submit(() -> {
try {
PreparedStatement ps = connection.prepareStatement("INSERT INTO cytonic_worlds (world_name, world_type, last_modified, world_data, spawn_point) VALUES (?,?, CURRENT_TIMESTAMP,?,?)");
ps.setString(1, worldName);
ps.setString(2, worldType);
ps.setBytes(3, PolarWriter.write(world));
ps.setString(4, PosSerializer.serialize(spawnPoint));
ps.executeUpdate();
} catch (SQLException e) {
Logger.error("An error occurred whilst adding a world!",e);
}
});
}

/**
* Retrieves a world from the database.
*
* @param worldName The name of the world to fetch.
* @return A {@link CompletableFuture} that completes with the fetched {@link PolarWorld}.
* If the world does not exist in the database, the future will complete exceptionally with a {@link RuntimeException}.
* @throws IllegalStateException If the database connection is not open.
*/
public CompletableFuture<PolarWorld> getWorld(String worldName) {
CompletableFuture<PolarWorld> future = new CompletableFuture<>();
if (!isConnected())
throw new IllegalStateException("The database must have an open connection to fetch a world!");
worker.submit(() -> {
try (PreparedStatement ps = connection.prepareStatement("SELECT * FROM cytonic_worlds WHERE world_name = ?")) {
ps.setString(1, worldName);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
PolarWorld world = PolarReader.read(rs.getBytes("world_data"));
CytosisSettings.SERVER_SPAWN_POS = PosSerializer.deserialize(rs.getString("spawn_point"));
future.complete(world);
} else {
Logger.error("The result set is empty!");
throw new RuntimeException(STR."World not found: \{worldName}");
}
} catch (Exception e) {
Logger.error("An error occurred whilst fetching a world!", e);
future.completeExceptionally(e);
throw new RuntimeException(e);
}
});
return future;
}
}
Loading