Skip to content

Commit

Permalink
beta release
Browse files Browse the repository at this point in the history
  • Loading branch information
crackscout123 committed Nov 29, 2024
1 parent e830623 commit bc445ee
Show file tree
Hide file tree
Showing 7 changed files with 258 additions and 30 deletions.
8 changes: 5 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ repositories {

// If you have mod jar dependencies in ./libs, you can declare them as a repository like so.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
flatDir {
dir 'libs'
}
}

dependencies {
Expand All @@ -129,6 +129,8 @@ dependencies {
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
implementation name: 'mariadb-java-client-3.5.1'


// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
Expand Down
Binary file added libs/mariadb-java-client-3.5.1.jar
Binary file not shown.
Binary file added screenshots/Screenshot_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 18 additions & 4 deletions src/main/java/eu/crackscout/crackcore/CrackCoreMod.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package eu.crackscout.crackcore;


import java.util.function.Consumer;

import org.slf4j.Logger;

import com.mojang.logging.LogUtils;

import eu.crackscout.crackcore.events.ChestLogger;
import eu.crackscout.crackcore.events.GeneralEventHandler;
import eu.crackscout.crackcore.utils.DatabaseManager;
import net.minecraft.client.Minecraft;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.food.FoodProperties;
Expand Down Expand Up @@ -66,8 +65,10 @@ public class CrackCoreMod {
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());

public CrackCoreMod()
{

private static DatabaseManager databaseManager;

public CrackCoreMod() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();

// Register the commonSetup method for modloading
Expand All @@ -91,6 +92,19 @@ public CrackCoreMod()

// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);

// Datenbankverbindung herstellen
// databaseManager = new DatabaseManager();
// try {
// databaseManager.connect("localhost", 3306, "database", "user", "password");
// } catch (Exception e) {
// e.printStackTrace();
// }
}

public static DatabaseManager getDatabaseManager() {
return databaseManager;

}

private void commonSetup(final FMLCommonSetupEvent event)
Expand Down
152 changes: 129 additions & 23 deletions src/main/java/eu/crackscout/crackcore/events/ChestLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,29 @@
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import eu.crackscout.crackcore.CrackCoreMod;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
//import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

@SuppressWarnings("preview")
public class ChestLogger {


private final Map<ServerPlayer, ItemStack[]> trackedInventories = new HashMap<>();

public ChestLogger() {
// Event-Handler registrieren
MinecraftForge.EVENT_BUS.register(this);
Expand All @@ -29,30 +41,30 @@ public ChestLogger() {
/**
* Event, wenn ein Spieler mit einer Kiste interagiert.
*/
@SubscribeEvent
public void onPlayerInteract(PlayerInteractEvent.RightClickBlock event) {
// Sicherstellen, dass die Logik nur auf der Serverseite läuft
if (!event.getLevel().isClientSide) {
BlockPos pos = event.getPos();
var world = event.getLevel();
var blockState = world.getBlockState(pos);

// Prüfen, ob der Block eine normale oder gefangene Kiste ist
if (blockState.is(Blocks.CHEST) || blockState.is(Blocks.TRAPPED_CHEST)) {
var player = event.getEntity();

// Nur Spieler auf dem Server protokollieren (Multiplayer)
if (player instanceof ServerPlayer serverPlayer) {
logToFile(serverPlayer.getName().getString(), "Interacted with chest", pos.getX(), pos.getY(), pos.getZ());
}
}
}
}
// @SubscribeEvent
// public void onPlayerInteract(PlayerInteractEvent.RightClickBlock event) {
// // Sicherstellen, dass die Logik nur auf der Serverseite läuft
// if (!event.getLevel().isClientSide) {
// BlockPos pos = event.getPos();
// var world = event.getLevel();
// var blockState = world.getBlockState(pos);
//
// // Prüfen, ob der Block eine normale oder gefangene Kiste ist
// if (blockState.is(Blocks.CHEST) || blockState.is(Blocks.TRAPPED_CHEST)) {
// var player = event.getEntity();
//
// // Nur Spieler auf dem Server protokollieren (Multiplayer)
// if (player instanceof ServerPlayer serverPlayer) {
// logToFile(serverPlayer.getName().getString(), "Interacted with chest", pos.getX(), pos.getY(), pos.getZ());
// }
// }
// }
// }

/**
* Protokollieren der Änderungen am Container (z.B. Hinzufügen oder Entfernen von Items).
*/
@SubscribeEvent
@SubscribeEvent
public void onBlockInventoryChange(BlockEvent.EntityPlaceEvent event) {
// Stelle sicher, dass dies serverseitig ausgeführt wird
if (!event.getLevel().isClientSide()) {
Expand All @@ -69,17 +81,111 @@ public void onBlockInventoryChange(BlockEvent.EntityPlaceEvent event) {
}
}


/**
* Event wenn Spieler Ksite öffnet
*/
@SubscribeEvent
public void onContainerOpen(PlayerContainerEvent.Open event) {
if (event.getEntity() instanceof ServerPlayer player) {
AbstractContainerMenu menu = event.getContainer();

// Nur Kisten überwachen
if (menu instanceof ChestMenu chestMenu) {
// Kisteninventar initial speichern
trackedInventories.put(player, copyInventory(chestMenu));
logToFile(player.getName().getString(), "Opened chest", (int)getBlockPos(player).x, (int)getBlockPos(player).y, (int)getBlockPos(player).z);
}
}
}

/**
* Event, wenn ein Spieler eine Kiste schließt.
*/
@SubscribeEvent
public void onContainerClose(PlayerContainerEvent.Close event) {
if (event.getEntity() instanceof ServerPlayer player) {
AbstractContainerMenu menu = event.getContainer();

// Nur Kisten überprüfen
if (menu instanceof ChestMenu chestMenu) {
// Vergleiche Änderungen
ItemStack[] previousInventory = trackedInventories.remove(player);
if (previousInventory != null) {
logInventoryChanges(player, previousInventory, chestMenu);
}
}
}
}

/**
* Protokolliere Änderungen im Inventar der Kiste.
*/
private void logInventoryChanges(ServerPlayer player, ItemStack[] oldInventory, ChestMenu chestMenu) {
ItemStack[] currentInventory = copyInventory(chestMenu);

for (int i = 0; i < oldInventory.length; i++) {
ItemStack oldStack = oldInventory[i];
ItemStack currentStack = currentInventory[i];

if (!ItemStack.isSameItemSameTags(oldStack, currentStack)) {
int difference = currentStack.getCount() - oldStack.getCount();
String action = difference > 0 ? "Added" : "Removed";
int count = Math.abs(difference);
String itemName = (difference > 0 ? currentStack : oldStack).getDisplayName().getString();

if (count > 0) {
logToFile(
player.getName().getString(),
String.format("%s %d x %s", action, count, itemName),
(int)getBlockPos(player).x, (int)getBlockPos(player).y, (int)getBlockPos(player).z
);
}
}
}
}

/**
* Hilfsmethode zum Schreiben von Logeinträgen in eine Datei.
* Kopiert das Inventar eines ChestMenus in ein Array von ItemStacks.
*/
private ItemStack[] copyInventory(ChestMenu chestMenu) {
int size = chestMenu.getContainer().getContainerSize();
ItemStack[] copy = new ItemStack[size];
for (int i = 0; i < size; i++) {
copy[i] = chestMenu.getContainer().getItem(i).copy();
}
return copy;
}



/**
* Holt die Position des Blocks, mit dem der Spieler interagiert.
*/
private Vec3 getBlockPos(ServerPlayer player) {
BlockPos pos = player.blockPosition();
return new Vec3(pos.getX(), pos.getY(), pos.getZ());
}


private void logToFile(String playerName, String action, int x, int y, int z) {
//logToDatabase(playerName, action, x, y, z); // passing the information to the database - coming soon
String logEntry = String.format("[%s] Player: %s Action: %s Position: (%d, %d, %d)%n",
LocalDateTime.now(), playerName, action, x, y, z);
System.out.println(logEntry); // DEBUG
try (BufferedWriter writer = new BufferedWriter(new FileWriter("chest_log.txt", true))) {
writer.write(logEntry);
} catch (IOException e) {
e.printStackTrace();
}
}

@SuppressWarnings("unused")
private void logToDatabase(String playerName, String action, int x, int y, int z) {
String query = "INSERT INTO chest_logs (player_name, action, x, y, z, timestamp) VALUES (?, ?, ?, ?, ?, NOW())";
try {
CrackCoreMod.getDatabaseManager().executeUpdate(query, playerName, action, x, y, z);
} catch (Exception e) {
e.printStackTrace();
}
}
}
92 changes: 92 additions & 0 deletions src/main/java/eu/crackscout/crackcore/utils/DatabaseManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* @author rzepk
*
* Nov 29, 2024 5:46:47 AM
*/
package eu.crackscout.crackcore.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseManager {
private Connection connection;

/**
* Initialisiert die Verbindung zur MariaDB-Datenbank.
*
* @param host Die IP-Adresse oder der Hostname der Datenbank.
* @param port Der Port der Datenbank (Standard: 3306).
* @param database Der Name der Datenbank.
* @param username Der Benutzername für die Verbindung.
* @param password Das Passwort für die Verbindung.
* @throws SQLException Falls ein Fehler beim Aufbau der Verbindung auftritt.
* @throws ClassNotFoundException Falls der JDBC-Treiber nicht gefunden wird.
*/
public void connect(String host, int port, String database, String username, String password) throws SQLException, ClassNotFoundException {
// MariaDB/MySQL JDBC-Treiber laden
Class.forName("org.mariadb.jdbc.Driver");

// Verbindung zur Datenbank aufbauen
String url = "jdbc:mariadb://" + host + ":" + port + "/" + database;
connection = DriverManager.getConnection(url, username, password);
System.out.println("Verbindung zur Datenbank erfolgreich hergestellt!");
}

/**
* Führt eine SELECT-Abfrage aus.
*
* @param query Die SQL-Abfrage.
* @param params Parameter für die Abfrage (falls benötigt).
* @return Das ResultSet mit den Ergebnissen.
* @throws SQLException Falls ein Fehler bei der Abfrage auftritt.
*/
public ResultSet executeQuery(String query, Object... params) throws SQLException {
PreparedStatement statement = connection.prepareStatement(query);
setParameters(statement, params);
return statement.executeQuery();
}

/**
* Führt eine INSERT, UPDATE oder DELETE-Abfrage aus.
*
* @param query Die SQL-Abfrage.
* @param params Parameter für die Abfrage (falls benötigt).
* @throws SQLException Falls ein Fehler bei der Abfrage auftritt.
*/
public void executeUpdate(String query, Object... params) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(query)) {
setParameters(statement, params);
statement.executeUpdate();
}
}

/**
* Beendet die Verbindung zur Datenbank.
*/
public void disconnect() {
if (connection != null) {
try {
connection.close();
System.out.println("Verbindung zur Datenbank geschlossen.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

/**
* Setzt Parameter für eine vorbereitete Abfrage.
*
* @param statement Die vorbereitete SQL-Anweisung.
* @param params Die Parameter für die Abfrage.
* @throws SQLException Falls ein Fehler beim Setzen der Parameter auftritt.
*/
private void setParameters(PreparedStatement statement, Object... params) throws SQLException {
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
}
}
14 changes: 14 additions & 0 deletions src/main/java/eu/crackscout/crackcore/utils/MySQL.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* @author rzepk
*
* Nov 29, 2024 5:45:07 AM
*/
package eu.crackscout.crackcore.utils;

/**
* @author rzepk
*
*/
public class MySQL {

}

0 comments on commit bc445ee

Please sign in to comment.