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

Chat logging #21

Merged
merged 14 commits into from
May 5, 2024
9 changes: 3 additions & 6 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ repositories {
}

dependencies {
implementation("com.github.Minestom", "Minestom", "7daf8d69b7") // minstom itself
implementation("com.github.Minestom:Minestom:fed512eaf6") // minstom itself
implementation("com.google.code.gson:gson:2.10.1") // serializing
implementation("org.slf4j:slf4j-api:1.7.25") // logging
implementation("net.kyori:adventure-text-minimessage:4.16.0")// better components
implementation("mysql:mysql-connector-java:8.0.28") //mysql connector
implementation("org.tomlj:tomlj:1.1.1") // Config lang
}

Expand All @@ -35,11 +36,6 @@ tasks.withType<JavaCompile> {
options.compilerArgs.add("--enable-preview")
}

tasks.withType<JavaCompile> {
// use String templates
options.compilerArgs.add("--enable-preview")
}

webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
tasks {
assemble {
dependsOn("shadowJar")
Expand All @@ -50,5 +46,6 @@ tasks {
}
mergeServiceFiles()
archiveFileName.set("cytosis.jar")
//destinationDirectory.set(file(providers.gradleProperty("server_dir").get()))
}
}
2 changes: 1 addition & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
rootProject.name = "MinestomBase"
rootProject.name = "Cytosis"

23 changes: 17 additions & 6 deletions src/main/java/net/cytonic/cytosis/Cytosis.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import net.minestom.server.instance.block.Block;
import net.minestom.server.network.ConnectionManager;
import net.minestom.server.permission.Permission;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
Expand All @@ -33,7 +32,7 @@ public class Cytosis {
private static CommandManager COMMAND_MANAGER;
private static CommandHandler COMMAND_HANDLER;
private static FileManager FILE_MANAGER;

private static Manager manager;
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
private static ConsoleSender CONSOLE_SENDER;

public static void main(String[] args) {
Expand All @@ -43,7 +42,7 @@ public static void main(String[] args) {
Logger.info("Starting server.");
MINECRAFT_SERVER = MinecraftServer.init();
MinecraftServer.setBrandName("Cytosis");

Logger.info("Initializing Mojang Authentication");
MojangAuth.init(); //VERY IMPORTANT! (This is online mode!)

Expand All @@ -53,6 +52,9 @@ public static void main(String[] args) {
Logger.info("Starting connection manager.");
CONNECTION_MANAGER = MinecraftServer.getConnectionManager();

Logger.info("Starting manager.");
manager = new Manager();

// Commands
Logger.info("Starting command manager.");
COMMAND_MANAGER = MinecraftServer.getCommandManager();
Expand All @@ -75,6 +77,10 @@ public static void main(String[] args) {
Logger.error("An error occurred whilst initializing the file manager!", throwable);
} else {
Logger.info("File manager initialized!");

Logger.info("Initializing database");
manager.setupDatabase();
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved

Logger.info("Completing nonessential startup tasks.");
completeNonEssentialTasks(start);
}
Expand All @@ -97,6 +103,10 @@ public static CommandManager getCommandManager() {
return COMMAND_MANAGER;
}

public static Manager getManager() {
return manager;
}

public static Set<Player> getOnlinePlayers() {
Set<Player> players = new HashSet<>();
INSTANCE_MANAGER.getInstances().forEach(instance -> players.addAll(instance.getPlayers()));
Expand All @@ -105,9 +115,8 @@ public static Set<Player> getOnlinePlayers() {

public static Optional<Player> getPlayer(String username) {
Player target = null;
for (Player onlinePlayer : getOnlinePlayers()) {
for (Player onlinePlayer : getOnlinePlayers())
if (onlinePlayer.getUsername().equals(username)) target = onlinePlayer;
}
return Optional.ofNullable(target);
}

Expand Down Expand Up @@ -143,6 +152,8 @@ public static void completeNonEssentialTasks(long start) {
Logger.info("Initializing server events");
ServerEventListeners.initServerEvents();

MinecraftServer.getSchedulerManager().buildShutdownTask(() -> manager.shutdown());

Logger.info("Initializing server commands");
COMMAND_HANDLER = new CommandHandler();
COMMAND_HANDLER.setupConsole();
Expand All @@ -152,6 +163,6 @@ public static void completeNonEssentialTasks(long start) {
Logger.info("Server started on port 25565");
MINECRAFT_SERVER.start("0.0.0.0", 25565);
long end = System.currentTimeMillis();
Logger.info(StringTemplate.STR."Server started in \{end - start}ms!");
Logger.info(STR."Server started in \{end - start}ms!");
}
}
36 changes: 36 additions & 0 deletions src/main/java/net/cytonic/cytosis/Manager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package net.cytonic.cytosis;

import net.cytonic.cytosis.data.Database;
import net.cytonic.cytosis.logging.Logger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Manager {
private final ExecutorService worker;
private Database database;

public Manager() {
this.worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisManagerWorker")
.uncaughtExceptionHandler((t, e) -> Logger.error(STR."An uncaught exception occoured on the thread: \{t.getName()}", e)).factory());
}

public void shutdown() {
worker.submit(() -> {
database.disconnect();
Logger.info("Good night!");
});
}

public void setupDatabase() {
worker.submit(() -> {
database = new Database();
database.connect();
database.createChatTable();
});
}

public void setupBedwars() {}


public Database getDatabase() {return database;}
}
10 changes: 5 additions & 5 deletions src/main/java/net/cytonic/cytosis/commands/GamemodeCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public GamemodeCommand() {

// using a gamemode as an argument
var gameModeArgument = ArgumentType.Enum("gamemode", GameMode.class).setFormat(ArgumentEnum.Format.LOWER_CASED);
gameModeArgument.setCallback((sender, exception) -> sender.sendMessage("The gamemode " + exception.getInput() + " is invalid!"));
gameModeArgument.setCallback((sender, exception) -> sender.sendMessage(STR."The gamemode \{exception.getInput()} is invalid!"));

var shorthand = ArgumentType.Word("shorthand").from("c", "s", "sv", "a", "0", "1", "2", "3");
shorthand.setSuggestionCallback((sender, context, suggestion) -> {
Expand All @@ -27,13 +27,13 @@ public GamemodeCommand() {
suggestion.addEntry(new SuggestionEntry("sv", Component.text("Represents the Survival gamemode")));
suggestion.addEntry(new SuggestionEntry("a", Component.text("Represents the Adventure gamemode")));
});
shorthand.setCallback((sender, exception) -> sender.sendMessage(Component.text("The shorthand '" + exception.getInput() + "' is invalid!", NamedTextColor.RED)));
shorthand.setCallback((sender, exception) -> sender.sendMessage(Component.text(STR."The shorthand '\{exception.getInput()}' is invalid!", NamedTextColor.RED)));

addSyntax((sender, context) -> {
if (sender instanceof final Player player) {
final GameMode gameMode = context.get(gameModeArgument);
player.setGameMode(gameMode);
player.sendMessage(Component.text("Updated your gamemode to " + gameMode.name(), NamedTextColor.GREEN));
player.sendMessage(Component.text(STR."Updated your gamemode to \{gameMode.name()}", NamedTextColor.GREEN));
} else {
sender.sendMessage(Component.text("Hey! You can't do this.", NamedTextColor.RED));
}
Expand All @@ -50,11 +50,11 @@ public GamemodeCommand() {
case "sv", "0" -> gm = GameMode.SURVIVAL;
}
if (gm == null) {
sender.sendMessage(Component.text("The shorthand '" + gameMode + "' is invalid!", NamedTextColor.RED));
sender.sendMessage(Component.text(STR."The shorthand '\{gameMode}' is invalid!", NamedTextColor.RED));
return;
}
player.setGameMode(gm);
player.sendMessage(Component.text("Updated your gamemode to " + gm.name(), NamedTextColor.GREEN));
player.sendMessage(Component.text(STR."Updated your gamemode to \{gm.name()}", NamedTextColor.GREEN));
} else {
sender.sendMessage(Component.text("Hey! You can't do this.", NamedTextColor.RED));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public OperatorCommand() {
var playerArg = ArgumentType.Word("player").from(getPlayerNames());
playerArg.setCallback((sender, exception) -> {
final String input = exception.getInput();
sender.sendMessage("The player " + input + " is invalid!");
sender.sendMessage(STR."The player \{input} is invalid!");
});

setDefaultExecutor((sender, context) -> {
Expand All @@ -27,7 +27,7 @@ public OperatorCommand() {
return;
}
final String playerName = context.get(playerArg);
Cytosis.getPlayer(playerName).ifPresentOrElse(Cytosis::opPlayer, () -> sender.sendMessage(Component.text("Couldn't find the player '" + playerName + "'. Did you spell their name right?")));
Cytosis.getPlayer(playerName).ifPresentOrElse(Cytosis::opPlayer, () -> sender.sendMessage(Component.text(STR."Couldn't find the player '\{playerName}'. Did you spell their name right?")));
});
}

Expand Down
108 changes: 108 additions & 0 deletions src/main/java/net/cytonic/cytosis/data/Database.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package net.cytonic.cytosis.data;

import net.cytonic.cytosis.config.CytosisSettings;
import net.cytonic.cytosis.logging.Logger;
import net.minestom.server.MinecraftServer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Database {

private final ExecutorService worker;
private final String host;
private final int port;
private final String database;
private final String username;
private final String password;
private final boolean ssl;
private Connection connection;

public Database() {
this.worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisDatabaseWorker").uncaughtExceptionHandler((t, e) -> Logger.error(STR."An uncaught exception occoured on the thread: \{t.getName()}", e)).factory());
this.host = CytosisSettings.DATABASE_HOST;
this.port = CytosisSettings.DATABASE_PORT;
this.database = CytosisSettings.DATABASE_NAME;
this.username = CytosisSettings.DATABASE_USER;
this.password = CytosisSettings.DATABASE_PASSWORD;
this.ssl = CytosisSettings.DATABASE_USE_SSL;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
Logger.error("Failed to load database driver");
Logger.error(e.toString());
}
}

public boolean isConnected() {
return (connection != null);
}

public void connect() {
worker.submit(() -> {
if (!isConnected()) {
try {
connection = DriverManager.getConnection(STR."jdbc:mysql://\{host}:\{port}/\{database}?useSSL=\{ssl}&autoReconnect=true", username, password);
} catch (SQLException e) {
Logger.error("Invalid Database Credentials!");
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
MinecraftServer.stopCleanly();
}
}
});

}

public void disconnect() {
worker.submit(() -> {
if (isConnected()) {
try {
connection.close();
Logger.info("Database connection closed!");
} catch (SQLException e) {
Logger.error("""
An error occurred whilst disconnecting from the database. Please report the following stacktrace to Foxikle:
""",e);
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
}
}
});
}

private Connection getConnection() {
return connection;
}

public 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.executeUpdate();
} catch (SQLException e) {
Logger.error(STR."""
An error occoured whilst fetching data from the database. Please report the following stacktrace to Foxikle:\s
\{Arrays.toString(e.getStackTrace())}""");
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
}
}
});
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
}

public void addChat(UUID uuid, String message) {
worker.submit(() -> {
PreparedStatement ps;
try {
ps = connection.prepareStatement("INSERT INTO cytonicchat (timestamp,uuid,message) VALUES (CURRENT_TIMESTAMP,?,?)");
ps.setString(1, uuid.toString());
ps.setString(2, message);
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.AsyncPlayerConfigurationEvent;
import net.minestom.server.event.player.PlayerChatEvent;
import net.minestom.server.event.player.PlayerSpawnEvent;

public class ServerEventListeners {
Expand All @@ -23,10 +24,15 @@ public static void initServerEvents() {
Cytosis.getEventHandler().registerGlobalEvent(PlayerSpawnEvent.class, event -> {
final Player player = event.getPlayer();
if (CytosisSettings.LOG_PLAYER_IPS)
Logger.info(event.getPlayer().getUsername() + " (" + event.getPlayer().getUuid() + ") joined with the ip: " + player.getPlayerConnection().getServerAddress());
Logger.info(STR."\{event.getPlayer().getUsername()} (\{event.getPlayer().getUuid()}) joined with the ip: \{player.getPlayerConnection().getServerAddress()}");
else
Logger.info(event.getPlayer().getUsername() + " (" + event.getPlayer().getUuid() + ") joined.");
Logger.info(STR."\{event.getPlayer().getUsername()} (\{event.getPlayer().getUuid()}) joined.");
player.sendMessage("Hello!");
});
Logger.info("Registering player chat event.");
Cytosis.getEventHandler().registerGlobalEvent(PlayerChatEvent.class, event -> {
final Player player = event.getPlayer();
Cytosis.getManager().getDatabase().addChat(player.getUuid(),event.getMessage());
});
webhead1104 marked this conversation as resolved.
Show resolved Hide resolved
}
}
Loading