diff --git a/gradle.properties b/gradle.properties index 8c81087..263a7fe 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,4 +3,4 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false -mod_version=1.19.2-1.3.0 \ No newline at end of file +mod_version=1.19.2-1.3.4 \ No newline at end of file diff --git a/src/main/java/vip/fubuki/playersync/PlayerSync.java b/src/main/java/vip/fubuki/playersync/PlayerSync.java index 6d17f31..4bcb923 100644 --- a/src/main/java/vip/fubuki/playersync/PlayerSync.java +++ b/src/main/java/vip/fubuki/playersync/PlayerSync.java @@ -17,6 +17,7 @@ import vip.fubuki.playersync.sync.VanillaSync; import vip.fubuki.playersync.util.JDBCsetUp; +import java.sql.ResultSet; import java.sql.SQLException; @Mod(PlayerSync.MODID) @@ -41,7 +42,7 @@ private void commonSetup(final FMLCommonSetupEvent event) { @SubscribeEvent public void onServerStarting(ServerStartingEvent event) throws SQLException { - JDBCsetUp.executeUpdate("CREATE DATABASE IF NOT EXISTS `playersync`",1); + JDBCsetUp.executeUpdate("CREATE DATABASE IF NOT EXISTS "+JdbcConfig.DATABASE_NAME.get(),1); JDBCsetUp.executeUpdate(""" CREATE TABLE IF NOT EXISTS `player_data` ( @@ -51,6 +52,8 @@ public void onServerStarting(ServerStartingEvent event) throws SQLException { `advancements` blob, `enderchest` mediumblob, `effects` blob, + `left_hand` blob, + `cursors` blob, `xp` int DEFAULT NULL, `food_level` int DEFAULT NULL, `score` int DEFAULT NULL, @@ -59,8 +62,27 @@ public void onServerStarting(ServerStartingEvent event) throws SQLException { `last_server` int DEFAULT NULL, PRIMARY KEY (`uuid`) );"""); - JDBCsetUp.executeUpdate("CREATE TABLE IF NOT EXISTS chat (player CHAR(36) NOT NULL,message TEXT," + - "timestamp BIGINT)"); + + JDBCsetUp.QueryResult queryResult = JDBCsetUp.executeQuery(""" + SELECT COUNT(*) AS column_count + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_NAME = 'player_data'; + """); + + ResultSet resultSet = queryResult.resultSet(); + int columnCount = 0; + if(resultSet.next()) { + columnCount = resultSet.getInt("column_count"); + } + + if(columnCount<14){ + JDBCsetUp.executeUpdate(""" + ALTER TABLE player_data + ADD COLUMN left_hand blob, + ADD COLUMN cursors blob; + """); + } + JDBCsetUp.executeUpdate(""" CREATE TABLE IF NOT EXISTS server_info ( `id` INT NOT NULL, @@ -72,6 +94,7 @@ CREATE TABLE IF NOT EXISTS server_info ( "VALUES(" + JdbcConfig.SERVER_ID.get() + ",true," + current + ") " + "ON DUPLICATE KEY UPDATE id= " + JdbcConfig.SERVER_ID.get() +",enable = 1," + "last_update=" + current + ";"); + JDBCsetUp.executeUpdate("UPDATE server_info SET enable= 1 WHERE id= "+ JdbcConfig.SERVER_ID.get()); if(ModList.get().isLoaded("curios")) { JDBCsetUp.executeUpdate("CREATE TABLE IF NOT EXISTS curios (uuid CHAR(36) NOT NULL,curios_item BLOB, PRIMARY KEY (uuid))"); diff --git a/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java b/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java index 3408b14..d51ce1f 100644 --- a/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java +++ b/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java @@ -14,9 +14,13 @@ public class JdbcConfig { public static ForgeConfigSpec.IntValue PORT; public static ForgeConfigSpec.ConfigValue USERNAME; public static ForgeConfigSpec.ConfigValue PASSWORD; + public static ForgeConfigSpec.ConfigValue DATABASE_NAME; public static ForgeConfigSpec.ConfigValue> SYNC_WORLD; public static ForgeConfigSpec.BooleanValue USE_SSL; public static ForgeConfigSpec.BooleanValue SYNC_CHAT; + public static ForgeConfigSpec.BooleanValue IS_CHAT_SERVER; + public static ForgeConfigSpec.ConfigValue CHAT_SERVER_IP; + public static ForgeConfigSpec.IntValue CHAT_SERVER_PORT; public static ForgeConfigSpec.ConfigValue SERVER_ID; @@ -29,9 +33,13 @@ public class JdbcConfig { USE_SSL = COMMON_BUILDER.comment("whether use SSL").define("use_ssl", false); USERNAME = COMMON_BUILDER.comment("username").define("user_name", "root"); PASSWORD = COMMON_BUILDER.comment("password").define("password", "password"); + DATABASE_NAME = COMMON_BUILDER.comment("database name").define("db_name","playersync"); SERVER_ID = COMMON_BUILDER.comment("the server id should be unique").define("Server_id", new Random().nextInt(1,Integer.MAX_VALUE-1)); SYNC_WORLD = COMMON_BUILDER.comment("The worlds that will be synchronized.If running in server it is supposed to have only one").define("sync_world", new ArrayList<>()); SYNC_CHAT= COMMON_BUILDER.comment("Whether synchronize chat").define("sync_chat", true); + IS_CHAT_SERVER = COMMON_BUILDER.comment("Whether recieve messages from other servers as host").define("IsChatServer",false); + CHAT_SERVER_IP = COMMON_BUILDER.define("ChatServerIP","127.0.0.1"); + CHAT_SERVER_PORT = COMMON_BUILDER.defineInRange("ChatServerPort",7900,0,65535); COMMON_BUILDER.pop(); COMMON_CONFIG = COMMON_BUILDER.build(); } diff --git a/src/main/java/vip/fubuki/playersync/sync/ChatSync.java b/src/main/java/vip/fubuki/playersync/sync/ChatSync.java index 767210d..52d8b20 100644 --- a/src/main/java/vip/fubuki/playersync/sync/ChatSync.java +++ b/src/main/java/vip/fubuki/playersync/sync/ChatSync.java @@ -2,45 +2,124 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.players.PlayerList; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import vip.fubuki.playersync.util.JDBCsetUp; +import vip.fubuki.playersync.config.JdbcConfig; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Objects; +import java.util.Scanner; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; -@Mod.EventBusSubscriber public class ChatSync { - static int tick = 0; - static long current = System.currentTimeMillis(); - - public static void register(){} - @SubscribeEvent - public static void onPlayerChat(net.minecraftforge.event.ServerChatEvent event) throws SQLException { - JDBCsetUp.executeUpdate("INSERT INTO chat (player, message, timestamp) VALUES ('" + event.getUsername() + "', '" + event.getRawText() + "', '" + current + "')"); + static PlayerList playerList; + + static ServerSocket serverSocket; + static Socket clientSocket; + static Set SocketList; + static ExecutorService executorService = Executors.newCachedThreadPool(); + + public static void register(){ + if(JdbcConfig.IS_CHAT_SERVER.get()) + new Thread(ChatSync::ServerSocket).start(); + ClientSocket(); + MinecraftForge.EVENT_BUS.register(ChatSync.class); } - @SubscribeEvent - public static void Tick(net.minecraftforge.event.TickEvent.ServerTickEvent event) throws SQLException { - tick++; - if(tick == 20) { - ReadMessage(event.getServer().getPlayerList()); + + private static void ServerSocket() { + try { + serverSocket = new ServerSocket(JdbcConfig.CHAT_SERVER_PORT.get()); + while (true) { + Socket newSocket = serverSocket.accept(); + SocketList.add(newSocket); + executorService.submit(() -> handleClient(newSocket)); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private static void handleClient(Socket socket) { + try (InputStream inputStream = socket.getInputStream()) { + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + String message = new String(buffer, 0, bytesRead); + broadcastMessage(socket, message); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + SocketList.remove(socket); + try { + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private static void broadcastMessage(Socket sender, String message) { + for (Socket socket : SocketList) { + if (!socket.equals(sender)) { + try { + OutputStream outputStream = socket.getOutputStream(); + outputStream.write(message.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } } } - public static void ReadMessage(PlayerList playerList) throws SQLException { - JDBCsetUp.QueryResult queryResult=JDBCsetUp.executeQuery("SELECT * FROM chat WHERE timestamp > " + current); - ResultSet resultSet= queryResult.getResultSet(); - current = System.currentTimeMillis(); - tick = 0; - while(resultSet.next()) { - String player = resultSet.getString("player"); - String message = resultSet.getString("message"); - Component textComponents = Component.literal(player+": "+message); - playerList.broadcastSystemMessage(textComponents, true); + private static void ClientSocket() { + try { + clientSocket = new Socket(JdbcConfig.CHAT_SERVER_IP.get(), JdbcConfig.CHAT_SERVER_PORT.get()); + Scanner scanner = new Scanner(clientSocket.getInputStream()); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + Component textComponents = Component.nullToEmpty(line); + playerList.broadcastSystemMessage(textComponents,true); + } + } catch (IOException e) { + e.printStackTrace(); + reconnectClient(); } - resultSet.close(); - queryResult.getConnection().close(); + } + + private static void reconnectClient() { + //TODO + } + + @SubscribeEvent + public static void onPlayerChat(net.minecraftforge.event.ServerChatEvent event) throws IOException { + String message= event.getUsername()+":"+event.getMessage(); + OutputStream outputStream = clientSocket.getOutputStream(); + outputStream.write(message.getBytes()); + } + + @SubscribeEvent + public static void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event){ + playerList= Objects.requireNonNull(event.getEntity().getServer()).getPlayerList(); + } + + @SubscribeEvent + public static void onPlayerLeave(PlayerEvent.PlayerLoggedOutEvent event){ + playerList= Objects.requireNonNull(event.getEntity().getServer()).getPlayerList(); } } diff --git a/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java b/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java index 4b0f3ed..9bba2b7 100644 --- a/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java +++ b/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java @@ -25,7 +25,7 @@ public void onPlayerJoin(Player player) throws SQLException { */ LazyOptional itemHandler = top.theillusivec4.curios.api.CuriosApi.getCuriosHelper().getEquippedCurios(player); JDBCsetUp.QueryResult queryResult=JDBCsetUp.executeQuery("SELECT curios_item FROM curios WHERE uuid = '"+player.getUUID()+"'"); - ResultSet resultSet = queryResult.getResultSet(); + ResultSet resultSet = queryResult.resultSet(); if(resultSet.next()) { String curios_data=resultSet.getString("curios_item"); if(curios_data.length()>2) { @@ -34,7 +34,7 @@ public void onPlayerJoin(Player player) throws SQLException { for (int i = 0; i < handler.getSlots(); i++) { try { if (curios.get(i) == null) continue; - handler.setStackInSlot(i, ItemStack.of(NbtUtils.snbtToStructure(curios.get(i).replace("|", ",")))); + handler.setStackInSlot(i, ItemStack.of(NbtUtils.snbtToStructure(curios.get(i).replace("|", ",").replace("^","\"").replace("<","{").replace(">","}").replace("~", "'")))); } catch (CommandSyntaxException e) { throw new RuntimeException(e); } @@ -42,7 +42,7 @@ public void onPlayerJoin(Player player) throws SQLException { }); } resultSet.close(); - queryResult.getConnection().close(); + queryResult.connection().close(); }else{ StoreCurios(player,true); } @@ -61,7 +61,7 @@ public void StoreCurios(Player player,boolean init) throws SQLException { itemHandler.ifPresent(handler -> { for (int i = 0; i < handler.getSlots(); i++) { if (!handler.getStackInSlot(i).isEmpty()) { - String sNBT= handler.getStackInSlot(i).serializeNBT().toString().replace(",", "|"); + String sNBT= VanillaSync.serialize(handler.getStackInSlot(i).serializeNBT().toString()); curios.put(i, sNBT); } } diff --git a/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java b/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java index e6035b4..0bbd07a 100644 --- a/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java +++ b/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java @@ -5,12 +5,14 @@ import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.server.ServerStoppedEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -42,20 +44,20 @@ public static void register(){} public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQLException, CommandSyntaxException, IOException { String player_uuid = event.getEntity().getUUID().toString(); JDBCsetUp.QueryResult queryResult=JDBCsetUp.executeQuery("SELECT online, last_server FROM player_data WHERE uuid='"+player_uuid+"'"); - ResultSet resultSet=queryResult.getResultSet(); + ResultSet resultSet=queryResult.resultSet(); ServerPlayer serverPlayer = (ServerPlayer) event.getEntity(); if(!resultSet.next()){ - Store(event.getEntity(),true,Dist.CLIENT.isDedicatedServer()); + store(event.getEntity(),true,Dist.CLIENT.isDedicatedServer()); return; } boolean online = resultSet.getBoolean("online"); int lastServer = resultSet.getInt("last_server"); queryResult=JDBCsetUp.executeQuery("SELECT * FROM player_data WHERE uuid='"+player_uuid+"'"); - resultSet= queryResult.getResultSet(); - if(online) { + resultSet= queryResult.resultSet(); + if(online && lastServer != JdbcConfig.SERVER_ID.get()) { queryResult=JDBCsetUp.executeQuery("SELECT last_update,enable FROM server_info WHERE id='"+lastServer+"'"); - ResultSet getServerInfo = queryResult.getResultSet(); + ResultSet getServerInfo = queryResult.resultSet(); if(getServerInfo.next()){ long last_update = getServerInfo.getLong("last_update"); boolean enable = getServerInfo.getBoolean("enable"); @@ -64,7 +66,7 @@ public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQ serverPlayer.connection.disconnect(Component.translatable("playersync.already_online")); return; } - JDBCsetUp.executeUpdate("UPDATE server_info SET enable=false WHERE id=" + lastServer); + JDBCsetUp.executeUpdate("UPDATE server_info SET enable= '0' WHERE id=" + lastServer); } getServerInfo.close(); @@ -72,7 +74,7 @@ public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQ } JDBCsetUp.executeUpdate("UPDATE server_info SET last_update=" + System.currentTimeMillis() + " WHERE id=" + JdbcConfig.SERVER_ID.get()); - JDBCsetUp.executeUpdate("UPDATE player_data SET online=true,last_server=" + JdbcConfig.SERVER_ID.get() + " WHERE uuid='"+player_uuid+"'"); + JDBCsetUp.executeUpdate("UPDATE player_data SET online= '1',last_server=" + JdbcConfig.SERVER_ID.get() + " WHERE uuid='"+player_uuid+"'"); if(resultSet.next()) { //Easy Part serverPlayer.setHealth(resultSet.getInt("health")); @@ -82,23 +84,27 @@ public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQ serverPlayer.experienceProgress=0; serverPlayer.giveExperiencePoints(resultSet.getInt("xp")); serverPlayer.setScore(resultSet.getInt("score")); + //Left Hand + serverPlayer.setItemInHand(InteractionHand.OFF_HAND,ItemStack.of(NbtUtils.snbtToStructure(resultSet.getString("left_hand").replace("|",",").replace("^","\"").replace("<","{").replace(">","}").replace("~", "'")))); + //Cursor + serverPlayer.containerMenu.setCarried(ItemStack.of(NbtUtils.snbtToStructure(resultSet.getString("cursors").replace("|",",").replace("^","\"").replace("<","{").replace(">","}").replace("~", "'")))); //Equipment String armor_data=resultSet.getString("armor"); if(armor_data.length()>2) { Map equipment = LocalJsonUtil.StringToEntryMap(armor_data); for (Map.Entry entry : equipment.entrySet()) { - serverPlayer.getInventory().armor.set(entry.getKey(), Deserialize(entry)); + serverPlayer.getInventory().armor.set(entry.getKey(), deserialize(entry)); } } //Inventory Map inventory = LocalJsonUtil.StringToEntryMap(resultSet.getString("inventory")); for (Map.Entry entry : inventory.entrySet()) { - serverPlayer.getInventory().setItem(entry.getKey(),Deserialize(entry)); + serverPlayer.getInventory().setItem(entry.getKey(), deserialize(entry)); } //Ender chest Map ender_chest = LocalJsonUtil.StringToEntryMap(resultSet.getString("enderchest")); for (Map.Entry entry : ender_chest.entrySet()) { - serverPlayer.getEnderChestInventory().setItem(entry.getKey(),Deserialize(entry)); + serverPlayer.getEnderChestInventory().setItem(entry.getKey(), deserialize(entry)); } //Effects String effectData=resultSet.getString("effects"); @@ -122,7 +128,7 @@ public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQ byte [] bytes=resultSet.getString("advancements").getBytes(); Files.write(advancements.toPath(),bytes); }else{ - File[] files= ScanAdvancementsFile(player_uuid, gameDir); + File[] files= scanAdvancementsFile(player_uuid, gameDir); for (File file : files) { if(file==null) continue; byte [] bytes=resultSet.getString("advancements").getBytes(); @@ -139,7 +145,7 @@ public static void doPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQ } @SubscribeEvent - public static void OnPlayerJoin(PlayerEvent.PlayerLoggedInEvent event){ + public static void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event){ executorService.submit(()->{ try { doPlayerJoin(event); @@ -150,19 +156,20 @@ public static void OnPlayerJoin(PlayerEvent.PlayerLoggedInEvent event){ } - private static ItemStack Deserialize(Map.Entry entry) throws CommandSyntaxException { + public static ItemStack deserialize(Map.Entry entry) throws CommandSyntaxException { String nbt= entry.getValue().replace("|",",").replace("^","\"").replace("<","{").replace(">","}").replace("~", "'"); CompoundTag compoundTag = NbtUtils.snbtToStructure(nbt); return ItemStack.of(compoundTag); } + public static String serialize(String object){ + return object.replace(",","|").replace("\"","^").replace("{","<").replace("}",">").replace("'","~"); + } + public static void doPlayerSaveToFile(PlayerEvent.SaveToFile event) throws SQLException, IOException { JDBCsetUp.executeUpdate("UPDATE server_info SET last_update=" + System.currentTimeMillis() + " WHERE id=" + JdbcConfig.SERVER_ID.get()); if(!event.getEntity().getTags().contains("player_synced")) return; - Store(event.getEntity(),false,Dist.CLIENT.isDedicatedServer()); - //Mod support - ModsSupport modsSupport = new ModsSupport(); - modsSupport.onPlayerLeave(event.getEntity()); + store(event.getEntity(),false,Dist.CLIENT.isDedicatedServer()); } @SubscribeEvent @@ -178,22 +185,21 @@ public static void onPlayerSaveToFile(PlayerEvent.SaveToFile event) { @SubscribeEvent public static void onServerShutdown(ServerStoppedEvent event) throws SQLException { - JDBCsetUp.executeUpdate("UPDATE server_info SET enable= 'false' WHERE id=" + JdbcConfig.SERVER_ID.get()); + JDBCsetUp.executeUpdate("UPDATE server_info SET enable= '0' WHERE id=" + JdbcConfig.SERVER_ID.get()); } public static void doPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) throws SQLException, IOException { - if(!event.getEntity().getTags().contains("player_synced")) return; String player_uuid = event.getEntity().getUUID().toString(); - JDBCsetUp.executeUpdate("UPDATE player_data SET online= 'false' WHERE uuid='"+player_uuid+"'"); - Store(event.getEntity(),false,Dist.CLIENT.isDedicatedServer()); - //Mod support - ModsSupport modsSupport = new ModsSupport(); - modsSupport.onPlayerLeave(event.getEntity()); - event.getEntity().removeTag("player_synced"); + JDBCsetUp.executeUpdate("UPDATE player_data SET online= '0' WHERE uuid='"+player_uuid+"'"); + store(event.getEntity(),false,Dist.CLIENT.isDedicatedServer()); + } @SubscribeEvent - public static void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) { + public static void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) throws SQLException { + //Mod support + ModsSupport modsSupport = new ModsSupport(); + modsSupport.onPlayerLeave(event.getEntity()); executorService.submit(()->{ try { doPlayerLogout(event); @@ -204,32 +210,36 @@ public static void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) { } - public static void Store(Player player, boolean init,boolean isServer) throws SQLException, IOException { + public static void store(Player player, boolean init, boolean isServer) throws SQLException, IOException { String player_uuid = player.getUUID().toString(); //Easy part int XP = player.totalExperience; int score=player.getScore(); int food_level=player.getFoodData().getFoodLevel(); int health=(int) player.getHealth(); + //Left hand + String left_hand = serialize(player.getItemInHand(InteractionHand.OFF_HAND).serializeNBT().toString()); + //Cursor + String cursors = serialize(player.containerMenu.getCarried().serializeNBT().toString()); //Equipment Map equipment =new HashMap<>() ; for (int i = 0; i < player.getInventory().armor.size(); i++) { ItemStack itemStack = player.getInventory().armor.get(i); if(itemStack.isEmpty()) continue; - equipment.put(i,itemStack.serializeNBT().toString().replace(",","|").replace("\"","^").replace("{","<").replace("}",">").replace("'","~")); + equipment.put(i,serialize(itemStack.serializeNBT().toString())); } //inventory Inventory inventory = player.getInventory(); - Map inventoryMap=new HashMap<>(); + Map inventoryMap = new HashMap<>(); for (int i = 0; i < inventory.items.size(); i++) { CompoundTag itemNBT = inventory.items.get(i).serializeNBT(); - inventoryMap.put(i,itemNBT.toString().replace(",","|").replace("\"","^").replace("{","<").replace("}",">").replace("'","~")); + inventoryMap.put(i,serialize(itemNBT.toString())); } //EnderChest - Map ender_chest=new HashMap<>(); + Map ender_chest = new HashMap<>(); for (int i=0;i< player.getEnderChestInventory().getContainerSize();i++) { CompoundTag itemNBT = player.getEnderChestInventory().getItem(i).serializeNBT(); - ender_chest.put(i,itemNBT.toString().replace(",","|").replace("\"","^").replace("{","<").replace("}",">").replace("'","~")); + ender_chest.put(i,serialize(itemNBT.toString())); } //Effects Map effects= player.getActiveEffectsMap(); @@ -246,7 +256,7 @@ public static void Store(Player player, boolean init,boolean isServer) throws SQ advancements = new File(gameDir, JdbcConfig.SYNC_WORLD.get().get(0)+"/advancements"+"/"+player_uuid+".json"); }else{ // File gameDir = Minecraft.getInstance().gameDirectory; - File[] files=ScanAdvancementsFile(player_uuid, gameDir); + File[] files= scanAdvancementsFile(player_uuid, gameDir); //Get LastModified long latestModifiedDate = 0; for (File file : files) { @@ -265,11 +275,11 @@ public static void Store(Player player, boolean init,boolean isServer) throws SQ //SQL Operation if(init){ - JDBCsetUp.executeUpdate("INSERT INTO player_data (uuid,armor,inventory,enderchest,advancements,effects,xp,food_level,health,score,online) VALUES ('"+player_uuid+"','"+equipment+"','"+inventoryMap+"','"+ender_chest+"','"+advancements+"','"+effectMap+"','"+XP+"','"+food_level+"','"+health+"','"+score+"',online=true)"); - }else JDBCsetUp.executeUpdate("UPDATE player_data SET inventory = '"+inventoryMap+"',armor='"+equipment+"' ,xp='"+XP+"',effects='"+effectMap+"',enderchest='"+ender_chest+"',score='"+score+"',food_level='"+food_level+"',health='"+health+"',advancements='"+json+"' WHERE uuid = '"+player_uuid+"'"); + JDBCsetUp.executeUpdate("INSERT INTO player_data (uuid,armor,inventory,enderchest,advancements,effects,xp,food_level,health,score,left_hand,cursors,online) VALUES ('"+player_uuid+"','"+equipment+"','"+inventoryMap+"','"+ender_chest+"','"+advancements+"','"+effectMap+"','"+XP+"','"+food_level+"','"+health+"','"+score+"','"+left_hand+"','"+cursors+"',online=true)"); + }else JDBCsetUp.executeUpdate("UPDATE player_data SET inventory = '"+inventoryMap+"',armor='"+equipment+"' ,xp='"+XP+"',effects='"+effectMap+"',enderchest='"+ender_chest+"',score='"+score+"',food_level='"+food_level+"',health='"+health+"',advancements='"+json+"',left_hand='"+left_hand+"',cursors='"+cursors+"' WHERE uuid = '"+player_uuid+"'"); } - private static File[] ScanAdvancementsFile(String player_uuid, File gameDir) { + private static File[] scanAdvancementsFile(String player_uuid, File gameDir) { File[] files = new File[JdbcConfig.SYNC_WORLD.get().size()]; for (int i = 0; i < JdbcConfig.SYNC_WORLD.get().size(); i++) { File advanceFile=new File(gameDir, "saves/"+JdbcConfig.SYNC_WORLD.get().get(i)+"/advancements"+"/"+player_uuid+".json"); @@ -279,15 +289,17 @@ private static File[] ScanAdvancementsFile(String player_uuid, File gameDir) { return files; } -// @SubscribeEvent -// public void RegisterCommand(RegisterCommandsEvent event){ -// CommandDispatcher dispatcher=event.getDispatcher(); -// LiteralCommandNode cmd = dispatcher.register( -// Commands.literal("serializeNBT").executes(context -> {context.getSource().sendSuccess(Component.literal(context.getSource().getPlayer().getItemInHand(InteractionHand.MAIN_HAND).serializeNBT().toString()),true); -// return 0; -// }) -// ); -// } + static int tick = 0; + + @SubscribeEvent + public static void onUpdate(TickEvent.LevelTickEvent event) throws SQLException { + tick++; + if(tick == 1800) { + tick=0; + long current = System.currentTimeMillis(); + JDBCsetUp.executeUpdate("UPDATE server_info SET last_update ="+current+" WHERE id= "+ JdbcConfig.SERVER_ID.get()); + } + } } diff --git a/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java b/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java index b6b6300..436e750 100644 --- a/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java +++ b/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java @@ -13,51 +13,52 @@ public static Connection getConnection() throws SQLException { } public static QueryResult executeQuery(String sql) throws SQLException{ - Connection connection = getConnection(); - PreparedStatement useStatement = connection.prepareStatement("USE `playersync`"); - useStatement.executeUpdate(); + Connection connection = getConnection(); + try (Statement useStatement = connection.createStatement()) { + useStatement.execute("USE " + JdbcConfig.DATABASE_NAME.get()); + } PreparedStatement queryStatement = connection.prepareStatement(sql); ResultSet resultSet = queryStatement.executeQuery(); return new QueryResult(connection,resultSet); } - public static int executeUpdate(String sql) throws SQLException{ + public static void executeUpdate(String sql) throws SQLException{ try (Connection connection = getConnection()) { - PreparedStatement useStatement = connection.prepareStatement("USE `playersync`"); - useStatement.executeUpdate(); + try (Statement useStatement = connection.createStatement()) { + useStatement.execute("USE " + JdbcConfig.DATABASE_NAME.get()); + } try (PreparedStatement updateStatement = connection.prepareStatement(sql)) { - return updateStatement.executeUpdate(); + updateStatement.executeUpdate(); } } } - public static int executeUpdate(String sql,int i) throws SQLException{ - try (Connection connection = getConnection()) { + public static void update(String sql, String... argument) throws SQLException{ + Connection connection = getConnection(); - try (PreparedStatement updateStatement = connection.prepareStatement(sql)) { - return updateStatement.executeUpdate(); - } + try (Statement useStatement = connection.createStatement()) { + useStatement.execute("USE " + JdbcConfig.DATABASE_NAME.get()); } - } - public static class QueryResult{ - private final Connection connection; - private final ResultSet resultSet; + PreparedStatement updateStatement = connection.prepareStatement(sql); + for (int i = 1; i <= argument.length; i++) { + updateStatement.setString(i,argument[i]); + } + updateStatement.executeUpdate(); + } - public QueryResult(Connection connection, ResultSet resultSet) { - this.connection = connection; - this.resultSet = resultSet; - } + public static void executeUpdate(String sql, int i) throws SQLException{ + try (Connection connection = getConnection()) { - public Connection getConnection() { - return connection; + try (PreparedStatement updateStatement = connection.prepareStatement(sql)) { + updateStatement.executeUpdate(); + } } + } - public ResultSet getResultSet() { - return resultSet; - } + public record QueryResult(Connection connection, ResultSet resultSet) { } }