Skip to content

Commit

Permalink
1.3.4 release
Browse files Browse the repository at this point in the history
  • Loading branch information
mlus-asuka committed Oct 11, 2024
1 parent 8de71e8 commit c3d2b92
Show file tree
Hide file tree
Showing 7 changed files with 230 additions and 107 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false

mod_version=1.19.2-1.3.0
mod_version=1.19.2-1.3.4
29 changes: 26 additions & 3 deletions src/main/java/vip/fubuki/playersync/PlayerSync.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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` (
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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))");
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/vip/fubuki/playersync/config/JdbcConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ public class JdbcConfig {
public static ForgeConfigSpec.IntValue PORT;
public static ForgeConfigSpec.ConfigValue<String> USERNAME;
public static ForgeConfigSpec.ConfigValue<String> PASSWORD;
public static ForgeConfigSpec.ConfigValue<String> DATABASE_NAME;
public static ForgeConfigSpec.ConfigValue<List<String>> 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<String> CHAT_SERVER_IP;
public static ForgeConfigSpec.IntValue CHAT_SERVER_PORT;

public static ForgeConfigSpec.ConfigValue<Integer> SERVER_ID;

Expand All @@ -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();
}
Expand Down
137 changes: 108 additions & 29 deletions src/main/java/vip/fubuki/playersync/sync/ChatSync.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Socket> 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();
}
}
8 changes: 4 additions & 4 deletions src/main/java/vip/fubuki/playersync/sync/ModsSupport.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void onPlayerJoin(Player player) throws SQLException {
*/
LazyOptional<IItemHandlerModifiable> 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) {
Expand All @@ -34,15 +34,15 @@ 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);
}
}
});
}
resultSet.close();
queryResult.getConnection().close();
queryResult.connection().close();
}else{
StoreCurios(player,true);
}
Expand All @@ -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);
}
}
Expand Down
Loading

0 comments on commit c3d2b92

Please sign in to comment.