Reapply "mongodb integration (doesn't work)"

This reverts commit 4db4aa8c7d.
This commit is contained in:
Infinityy committed 2024-08-09 02:36:29 +02:00
1 parent 21298372e5
commit 8073813763
10 files changed
+173 -66

No files matched your search

+5
View File
@@ -60,6 +60,11 @@ dependencies {
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
include(implementation(annotationProcessor("io.github.llamalad7:mixinextras-fabric:${project.mixin_extras_version}")))
// MongoDB
include(implementation("org.mongodb:mongodb-driver-sync:${project.mongodb_version}"))
include(implementation("org.mongodb:mongodb-driver-core:${project.mongodb_version}"))
include(implementation("org.mongodb:bson:${project.mongodb_version}"))
// Will be replaced by Nexus
include(modApi("eu.pb4:sgui:${project.sgui_version}") { exclude(group: "net.fabricmc.fabric-api") })
modApi("xyz.nucleoid:fantasy:${project.fantasy_version}") {exclude(group: "net.fabricmc.fabric-api") }
+1
View File
@@ -15,6 +15,7 @@ archives_base_name = nexia
# Dependencies
fabric_version=0.42.0+1.16
mongodb_version=5.1.2
jda_version=5.0.0-beta.20
mixin_extras_version=0.4.0
nexus_version=0.1.15
@@ -90,7 +90,7 @@ public class NexiaPlayer extends WrappedPlayer {
public void safeReset(boolean heal, Minecraft.GameMode gameMode) {
this.setGameMode(gameMode);
this.setInvulnerabilityTime(20);
this.setInvulnerabilityTime(0);
this.clearEffects();
this.setRemainingFireTicks(0);
this.setGlowing(false);
@@ -1,6 +1,9 @@
package com.nexia.base.player;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import com.nexia.core.NexiaCore;
import com.nexia.core.utilities.player.CorePlayerData;
import com.nexia.core.utilities.player.CoreSavedPlayerData;
@@ -16,14 +19,10 @@ import com.nexia.minigames.games.football.util.player.FootballPlayerData;
import com.nexia.minigames.games.football.util.player.FootballSavedPlayerData;
import com.nexia.minigames.games.oitc.util.player.OITCPlayerData;
import com.nexia.minigames.games.skywars.util.player.SkywarsPlayerData;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.resources.ResourceLocation;
import org.bson.Document;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@@ -31,18 +30,16 @@ import java.util.UUID;
public class PlayerDataManager {
public static Map<ResourceLocation, PlayerDataManager> dataManagerMap = new HashMap<>();
private final String configDir;
private final String collectionName;
HashMap<UUID, PlayerData> allPlayerData = new HashMap<>();
public Class<? extends SavedPlayerData> savedPlayerDataClass;
public Class<? extends PlayerData> playerDataClass;
public String getDataDirectory() {
return FabricLoader.getInstance().getConfigDir().toString() + configDir;
}
public PlayerDataManager(ResourceLocation id, String configDir, Class<? extends SavedPlayerData> savedPlayerDataClass, Class<? extends PlayerData> playerDataClass) {
this.configDir = configDir;
public PlayerDataManager(ResourceLocation id, String collectionName, Class<? extends SavedPlayerData> savedPlayerDataClass, Class<? extends PlayerData> playerDataClass) {
this.collectionName = collectionName;
this.savedPlayerDataClass = savedPlayerDataClass;
this.playerDataClass = playerDataClass;
dataManagerMap.put(id, this);
@@ -53,32 +50,32 @@ public class PlayerDataManager {
}
public static void init() {
// <----------- Core --------------->
new PlayerDataManager(NexiaCore.CORE_DATA_MANAGER, "/nexia/core", CoreSavedPlayerData.class, CorePlayerData.class);
new PlayerDataManager(NexiaCore.CORE_DATA_MANAGER, "core", CoreSavedPlayerData.class, CorePlayerData.class);
// <----------- Discord --------------->
new PlayerDataManager(NexiaCore.DISCORD_DATA_MANAGER, "/nexia/discord", DiscordSavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.DISCORD_DATA_MANAGER, "discord", DiscordSavedPlayerData.class, PlayerData.class);
// <----------- FFAs --------------->
new PlayerDataManager(NexiaCore.FFA_CLASSIC_DATA_MANAGER, "/nexia/ffa/classic", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_KITS_DATA_MANAGER, "/nexia/ffa/kits", FFASavedPlayerData.class, KitFFAPlayerData.class);
new PlayerDataManager(NexiaCore.FFA_POT_DATA_MANAGER, "/nexia/ffa/pot", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_SKY_DATA_MANAGER, "/nexia/ffa/sky", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_UHC_DATA_MANAGER, "/nexia/ffa/uhc", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_CLASSIC_DATA_MANAGER, "ffa_classic", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_KITS_DATA_MANAGER, "ffa_kits", FFASavedPlayerData.class, KitFFAPlayerData.class);
new PlayerDataManager(NexiaCore.FFA_POT_DATA_MANAGER, "ffa_pot", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_SKY_DATA_MANAGER, "ffa_sky", FFASavedPlayerData.class, PlayerData.class);
new PlayerDataManager(NexiaCore.FFA_UHC_DATA_MANAGER, "ffa_uhc", FFASavedPlayerData.class, PlayerData.class);
// <----------- BedWars --------------->
new PlayerDataManager(NexiaCore.BEDWARS_DATA_MANAGER, "/nexia/bedwars", BedwarsSavedPlayerData.class, BedwarsPlayerData.class);
new PlayerDataManager(NexiaCore.BEDWARS_DATA_MANAGER, "bedwars", BedwarsSavedPlayerData.class, BedwarsPlayerData.class);
// <----------- Duels --------------->
new PlayerDataManager(NexiaCore.DUELS_DATA_MANAGER, "/nexia/duels", DuelsSavedPlayerData.class, DuelsPlayerData.class);
new PlayerDataManager(NexiaCore.DUELS_DATA_MANAGER, "duels", DuelsSavedPlayerData.class, DuelsPlayerData.class);
// <----------- Football --------------->
new PlayerDataManager(NexiaCore.FOOTBALL_DATA_MANAGER, "/nexia/football", FootballSavedPlayerData.class, FootballPlayerData.class);
new PlayerDataManager(NexiaCore.FOOTBALL_DATA_MANAGER, "football", FootballSavedPlayerData.class, FootballPlayerData.class);
// <----------- OITC --------------->
new PlayerDataManager(NexiaCore.OITC_DATA_MANAGER, "/nexia/oitc", WLKSavedPlayerData.class, OITCPlayerData.class);
new PlayerDataManager(NexiaCore.OITC_DATA_MANAGER, "oitc", WLKSavedPlayerData.class, OITCPlayerData.class);
// <----------- SkyWars --------------->
new PlayerDataManager(NexiaCore.SKYWARS_DATA_MANAGER, "/nexia/skywars", WLKSavedPlayerData.class, SkywarsPlayerData.class);
new PlayerDataManager(NexiaCore.SKYWARS_DATA_MANAGER, "skywars", WLKSavedPlayerData.class, SkywarsPlayerData.class);
}
public PlayerData get(NexiaPlayer player) {
@@ -93,7 +90,6 @@ public class PlayerDataManager {
removePlayerData(player.getUUID());
}
public PlayerData get(UUID uuid) {
if (!allPlayerData.containsKey(uuid)) {
addPlayerData(uuid);
@@ -118,41 +114,23 @@ public class PlayerDataManager {
}
private void savePlayerData(UUID uuid) {
try {
Document document = NexiaCore.mongoManager.toDocument(get(uuid).savedData);
document.append("uuid", uuid.toString());
document.remove("data");
PlayerData playerData = get(uuid);
Gson gson = new Gson();
String json = gson.toJson(playerData.savedData);
UpdateResult isReplaced = NexiaCore.mongoManager.getCollection(collectionName).replaceOne(Filters.eq("uuid", uuid), document);
String directory = getDataDir();
FileWriter fileWriter = new FileWriter(directory + "/" + uuid + ".json");
fileWriter.write(json);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
if (!isReplaced.wasAcknowledged()) {
NexiaCore.mongoManager.getCollection(collectionName).insertOne(document);
}
}
private <T extends SavedPlayerData> T loadPlayerData(UUID uuid, Class<T> toLoad) throws InstantiationException, IllegalAccessException {
try {
T savedPlayerData = NexiaCore.mongoManager.getObject(collectionName, Filters.eq("uuid", uuid), toLoad);
if (savedPlayerData != null) {
return savedPlayerData;
}
String directory = getDataDir();
String json = Files.readString(Path.of(directory + "/" + uuid + ".json"));
Gson gson = new Gson();
return gson.fromJson(json, toLoad);
} catch (Exception e) {
return toLoad.newInstance();
}
}
private String getDataDir() {
String playerDataDirectory = getDataDirectory() + "/playerdata";
new File(playerDataDirectory).mkdirs();
return playerDataDirectory;
}
}
@@ -1,6 +1,7 @@
package com.nexia.core;
import com.nexia.base.player.PlayerDataManager;
import com.nexia.core.utilities.database.MongoManager;
import com.nexia.nexus.api.NexusAPI;
import com.nexia.nexus.api.NexusServer;
import com.nexia.nexus.api.entrypoint.NexusPlugin;
@@ -26,6 +27,7 @@ public class NexiaCore implements ModInitializer, NexusPlugin {
public static final String modConfigDir = NxFileUtil.makeDir(FabricLoader.getInstance().getConfigDir().toString() + "/nexia");
public NetworkingHandler networkingHandler;
public static MongoManager mongoManager;
public static final ResourceLocation CONVENTIONAL_BRIDGING_UPDATE_ID = new ResourceLocation("c", "update_status");
@@ -61,11 +63,16 @@ public class NexiaCore implements ModInitializer, NexusPlugin {
logger.info("Registered commands.");
networkingHandler = new NetworkingHandler();
}
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onNexusLoad(NexusAPI api, NexusServer server) {
logger.info("Connecting to database...");
mongoManager = new MongoManager();
logger.info("Connected to database.");
logger.info("Loading Nexus API...");
ServerTime.nexusServer = server;
@@ -11,4 +11,10 @@ public class ModConfig implements ConfigData {
public String serverType = "";
public boolean debugMode = false;
public String host = "";
public String database = "";
public String username = "";
public String password = "";
public int port = 27017;
}
@@ -14,6 +14,7 @@ public class PlayerLeaveListener {
//setLeaveMessage(player, playerDisconnectEvent);
if (playerDisconnectEvent.getPlayer().hasTag("bot")) return;
PlayerDataManager.dataManagerMap.forEach((resourceLocation, playerDataManager) -> playerDataManager.removePlayerData(player));
});
}
@@ -0,0 +1,115 @@
package com.nexia.core.utilities.database;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.bind.TypeAdapters;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static com.nexia.core.NexiaCore.config;
@SuppressWarnings("unused")
public class MongoManager {
private final static Gson GSON = new GsonBuilder()
.registerTypeAdapter(UUID.class, TypeAdapters.UUID)
.create();
private final ExecutorService service;
private MongoClient client;
private MongoDatabase database;
public MongoManager() {
this.service = Executors.newCachedThreadPool();
this.openConnection();
}
public void openConnection() {
final MongoCredential mongoCredential = MongoCredential.createCredential(
config.username,
config.database,
config.password.toCharArray()
);
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.credential(mongoCredential)
.applyConnectionString(new ConnectionString("mongodb://" + config.host + ":" + config.port))
.build();
this.client = MongoClients.create(mongoClientSettings);
this.database = this.client.getDatabase(config.database);
}
public void closeConnection() {
if (this.client != null) {
this.client.close();
}
}
public <T> void insertObject(String collection, T type) {
getCollection(collection)
.insertOne(toDocument(type));
}
public <T> void replaceObject(String collection, Bson filter, T type) {
getCollection(collection)
.replaceOne(filter, toDocument(type));
}
public <T> T getObject(String collection, Bson filter, Class<T> aClass) {
final Document document = getCollection(collection)
.find(filter)
.first();
if (document == null) {
return null;
}
return toObject(document, aClass);
}
public void runAsync(Runnable runnable) {
this.service.submit(runnable);
}
public <T> Future<T> callAsync(Callable<T> callable) {
return this.service.submit(callable);
}
public <T> T toObject(Document document, Class<T> aClass) {
return GSON.fromJson(GSON.toJson(document), aClass);
}
public <T> Document toDocument(T type) {
return GSON.fromJson(GSON.toJson(type), Document.class);
}
public MongoClient getClient() {
return this.client;
}
public MongoDatabase getDatabase() {
return this.database;
}
public MongoCollection<Document> getCollection(String collection) {
return this.database.getCollection(collection);
}
public void shutdown() {
this.client.close();
}
}
@@ -24,6 +24,7 @@ import com.nexia.nexus.api.world.util.Location;
import com.nexia.nexus.builder.implementation.world.entity.projectile.WrappedProjectile;
import io.github.blumbo.inventorymerger.InventoryMerger;
import io.github.blumbo.inventorymerger.saving.SavableInventory;
import net.fabricmc.loader.api.FabricLoader;
import net.kyori.adventure.text.Component;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
@@ -120,15 +121,7 @@ public abstract class BaseFfaUtil {
SavableInventory savableInventory = new SavableInventory(player.unwrap().inventory);
String stringInventory = savableInventory.toSave();
try {
String file = getDataManager().getDataDirectory() + "/inventory/savedInventories/" + player.getUUID() + ".json";
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(stringInventory);
fileWriter.close();
} catch (Exception var6) {
LobbyUtil.returnToLobby(player, true);
player.sendMessage(Component.text("Failed to save " + getName() + " FFA inventory. Please try again or contact a developer.", ChatFormat.failColor));
}
getDataManager().get(player).savedData.set(String.class, "savedInventory", stringInventory);
}
public void calculateKill(NexiaPlayer attacker, NexiaPlayer player, boolean sendMessage) {
@@ -240,7 +233,7 @@ public abstract class BaseFfaUtil {
SavableInventory layout = null;
try {
String file = getDataManager().getDataDirectory() + "/inventory";
String file = FabricLoader.getInstance().getConfigDir() + "/nexia/ffa/" + this.getNameLowercase() + "/inventory";
String defaultJson = Files.readString(Path.of(file + "/default.json"));
Gson gson = new Gson();
defaultInventory = gson.fromJson(defaultJson, SavableInventory.class);
@@ -3,22 +3,23 @@ package com.nexia.ffa.base.player;
import com.nexia.base.player.SavedPlayerData;
public class FFASavedPlayerData extends SavedPlayerData {
public int kills;
public int killstreak;
public int bestKillstreak;
public int deaths;
public String savedInventory;
public FFASavedPlayerData() {
super();
this.kills = 0;
this.killstreak = 0;
this.bestKillstreak = 0;
this.deaths = 0;
this.savedInventory = "";
set(Integer.class, "kills", kills);
set(Integer.class, "killstreak", killstreak);
set(Integer.class, "bestKillstreak", bestKillstreak);
set(Integer.class, "deaths", deaths);
set(String.class, "savedInventory", savedInventory);
}
}