From f1c5c32a0ef9474e802255b2be55c71872d9f580 Mon Sep 17 00:00:00 2001 From: creeper123123321 Date: Mon, 4 Mar 2019 18:34:04 -0300 Subject: [PATCH] /viaver, fix scheduler, do not add clientsidereference to server --- .../viafabric/VRViaVersionInitializer.java | 40 +++++------ .../creeper123123321/viafabric/ViaFabric.java | 21 ++---- .../MixinClientConnectionServerChInit.java | 3 +- .../viafabric/platform/VRPlatform.java | 68 ++++++++++++------- .../Protocol1_8TO1_7_6_10.java | 44 +++++------- .../util/ManagedBlockerRunnable.java | 49 ------------- 6 files changed, 83 insertions(+), 142 deletions(-) delete mode 100644 src/main/java/com/github/creeper123123321/viafabric/util/ManagedBlockerRunnable.java diff --git a/src/main/java/com/github/creeper123123321/viafabric/VRViaVersionInitializer.java b/src/main/java/com/github/creeper123123321/viafabric/VRViaVersionInitializer.java index b4e4563..8c31148 100644 --- a/src/main/java/com/github/creeper123123321/viafabric/VRViaVersionInitializer.java +++ b/src/main/java/com/github/creeper123123321/viafabric/VRViaVersionInitializer.java @@ -36,7 +36,6 @@ import net.fabricmc.api.EnvType; import net.fabricmc.fabric.api.registry.CommandRegistry; import net.fabricmc.loader.FabricLoader; import net.minecraft.server.command.CommandSource; -import net.minecraft.server.command.ServerCommandSource; import us.myles.ViaVersion.ViaManager; import us.myles.ViaVersion.api.Via; import us.myles.ViaVersion.api.protocol.ProtocolRegistry; @@ -64,17 +63,8 @@ public class VRViaVersionInitializer { Class.forName("io.github.cottonmc.clientcommands.ClientCommands") .getMethod("registerCommand", Consumer.class) .invoke(null, - (Consumer>) command -> command - .register( - LiteralArgumentBuilder.literal("viafabricclient") - .then( - RequiredArgumentBuilder - .argument("args", StringArgumentType.greedyString()) - .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute) - .suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion) - ) - .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute) - ) + (Consumer>) c -> + c.register(command("viafabricclient")) ); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { Via.getPlatform().getLogger().warning("ClientCommands isn't installed"); @@ -83,20 +73,22 @@ public class VRViaVersionInitializer { try { Class.forName("net.fabricmc.fabric.api.registry.CommandRegistry"); - CommandRegistry.INSTANCE.register(false, command -> command - .register( - LiteralArgumentBuilder.literal("viafabric") - .then( - RequiredArgumentBuilder - .argument("args", StringArgumentType.greedyString()) - .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute) - .suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion) - ) - .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute) - ) - ); + CommandRegistry.INSTANCE.register(false, c -> c.register(command("viaversion"))); + CommandRegistry.INSTANCE.register(false, c -> c.register(command("viaver"))); + CommandRegistry.INSTANCE.register(false, c -> c.register(command("vvfabric"))); } catch (ClassNotFoundException e) { Via.getPlatform().getLogger().warning("Fabric API isn't installed"); } } + + private static LiteralArgumentBuilder command(String commandName) { + return LiteralArgumentBuilder.literal(commandName) + .then( + RequiredArgumentBuilder + .argument("args", StringArgumentType.greedyString()) + .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute) + .suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion) + ) + .executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute); + } } diff --git a/src/main/java/com/github/creeper123123321/viafabric/ViaFabric.java b/src/main/java/com/github/creeper123123321/viafabric/ViaFabric.java index 9fa0903..7c3a1d3 100644 --- a/src/main/java/com/github/creeper123123321/viafabric/ViaFabric.java +++ b/src/main/java/com/github/creeper123123321/viafabric/ViaFabric.java @@ -67,17 +67,14 @@ public class ViaFabric implements ModInitializer { } public static String getVersion() { - return FabricLoader.INSTANCE.getModContainers() - .stream() - .filter(container -> container.getInfo().getId().equals("viafabric")) - .findFirst() - .get().getInfo().getVersion().getFriendlyString(); + return FabricLoader.INSTANCE.getModContainer("viafabric") + .get().getMetadata().getVersion().getFriendlyString(); } private void checkForUpdates(File jar, String artifactName, String groupIdPath, String depName) throws Exception { int timeDivisor = 1000 * 60 * 60 * 24; long cachedTime = System.currentTimeMillis() / timeDivisor; - if (!(jar.exists() && jar.lastModified() / timeDivisor == cachedTime)) { + if (!(jar.exists() && jar.lastModified() / timeDivisor >= cachedTime)) { String localMd5 = null; if (jar.exists()) { try (InputStream is = Files.newInputStream(jar.toPath())) { @@ -131,19 +128,11 @@ public class ViaFabric implements ModInitializer { @Override public void onInitialize() { File viaVersionJar = FabricLoader.INSTANCE.getConfigDirectory().toPath().resolve("ViaFabric").resolve("viaversion.jar").toFile(); - try { - checkForUpdates(viaVersionJar, "viaversion", "us/myles", "ViaVersion"); - } catch (Exception e) { - e.printStackTrace(); - } File viaRewindJar = FabricLoader.INSTANCE.getConfigDirectory().toPath().resolve("ViaFabric").resolve("viarewind.jar").toFile(); - try { - checkForUpdates(viaRewindJar, "viarewind-core", "de/gerrygames", "ViaRewind"); - } catch (Exception e) { - e.printStackTrace(); - } File viaBackwardsJar = FabricLoader.INSTANCE.getConfigDirectory().toPath().resolve("ViaFabric").resolve("viabackwards.jar").toFile(); try { + checkForUpdates(viaVersionJar, "viaversion", "us/myles", "ViaVersion"); + checkForUpdates(viaRewindJar, "viarewind-core", "de/gerrygames", "ViaRewind"); checkForUpdates(viaBackwardsJar, "viabackwards-core", "nl/matsv", "ViaBackwards"); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/github/creeper123123321/viafabric/mixin/MixinClientConnectionServerChInit.java b/src/main/java/com/github/creeper123123321/viafabric/mixin/MixinClientConnectionServerChInit.java index b1f9cef..63ae1f0 100644 --- a/src/main/java/com/github/creeper123123321/viafabric/mixin/MixinClientConnectionServerChInit.java +++ b/src/main/java/com/github/creeper123123321/viafabric/mixin/MixinClientConnectionServerChInit.java @@ -26,7 +26,6 @@ package com.github.creeper123123321.viafabric.mixin; import com.github.creeper123123321.viafabric.handler.serverside.FabricDecodeHandler; import com.github.creeper123123321.viafabric.handler.serverside.FabricEncodeHandler; -import com.github.creeper123123321.viafabric.protocol.ClientSideReference; import io.netty.channel.Channel; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; @@ -44,7 +43,7 @@ public class MixinClientConnectionServerChInit { private void onInitChannel(Channel channel, CallbackInfo ci) { if (channel instanceof SocketChannel) { UserConnection user = new UserConnection(channel); - new ProtocolPipeline(user).add(new ClientSideReference()); + new ProtocolPipeline(user); MessageToByteEncoder oldEncoder = (MessageToByteEncoder) channel.pipeline().get("encoder"); ByteToMessageDecoder oldDecoder = (ByteToMessageDecoder) channel.pipeline().get("decoder"); diff --git a/src/main/java/com/github/creeper123123321/viafabric/platform/VRPlatform.java b/src/main/java/com/github/creeper123123321/viafabric/platform/VRPlatform.java index 55be7ef..e892032 100644 --- a/src/main/java/com/github/creeper123123321/viafabric/platform/VRPlatform.java +++ b/src/main/java/com/github/creeper123123321/viafabric/platform/VRPlatform.java @@ -57,6 +57,7 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.util.stream.Collectors; @@ -82,7 +83,7 @@ public class VRPlatform implements ViaPlatform { @Override public String getPluginVersion() { try { - return VersionInfo.class.getField("VERSION").get(null) + "-ViaFabric"; + return VersionInfo.class.getField("VERSION").get(null).toString(); } catch (IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } @@ -102,21 +103,33 @@ public class VRPlatform implements ViaPlatform { @Override public TaskId runSync(Runnable runnable) { - return new FutureTaskId(ViaFabric.EVENT_LOOP - .submit(runnable) - .addListener(future -> { - if (!future.isSuccess()) { - future.cause().printStackTrace(); - } - }) + // Kick task needs to be on main thread + Executor executor = ViaFabric.EVENT_LOOP; + boolean alreadyLogged; + MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); + if (server != null) { + alreadyLogged = true; + executor = server; + } else { + alreadyLogged = false; + } + return new FutureTaskId( + CompletableFuture.runAsync(runnable, executor) + .exceptionally(throwable -> { + if (!alreadyLogged) { + throwable.printStackTrace(); + } + return null; + }) ); } @Override public TaskId runSync(Runnable runnable, Long ticks) { + // ViaVersion seems to not need to run delayed tasks on main thread return new FutureTaskId( ViaFabric.EVENT_LOOP - .schedule(runnable, ticks * 50, TimeUnit.SECONDS) + .schedule(runnable, ticks * 50, TimeUnit.MILLISECONDS) .addListener(future -> { if (!future.isSuccess()) { future.cause().printStackTrace(); @@ -127,9 +140,10 @@ public class VRPlatform implements ViaPlatform { @Override public TaskId runRepeatingSync(Runnable runnable, Long ticks) { + // ViaVersion seems to not need to run repeating tasks on main thread return new FutureTaskId( ViaFabric.EVENT_LOOP - .scheduleAtFixedRate(runnable, 0, ticks * 50, TimeUnit.SECONDS) + .scheduleAtFixedRate(runnable, 0, ticks * 50, TimeUnit.MILLISECONDS) .addListener(future -> { if (!future.isSuccess()) { future.cause().printStackTrace(); @@ -148,7 +162,8 @@ public class VRPlatform implements ViaPlatform { @Override public ViaCommandSender[] getOnlinePlayers() { MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); - if (server != null) { + if (server != null && server.isMainThread()) { + // Not thread safe return server.getPlayerManager().getPlayerList().stream() .map(Entity::getCommandSource) .map(NMSCommandSender::new) @@ -174,11 +189,13 @@ public class VRPlatform implements ViaPlatform { e.printStackTrace(); } } else { - MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); - if (server == null) return; - ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); - if (player == null) return; - player.sendChatMessage(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s)), ChatMessageType.SYSTEM); + runSync(() -> { + MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); + if (server == null) return; + ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); + if (player == null) return; + player.sendChatMessage(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s)), ChatMessageType.SYSTEM); + }); } } @@ -190,18 +207,19 @@ public class VRPlatform implements ViaPlatform { chat.write(Type.STRING, ChatRewriter.legacyTextToJson(s)); try { chat.sendFuture(ClientSideReference.class).addListener(future -> user.getChannel().close()); + return true; } catch (Exception e) { e.printStackTrace(); - return false; } } else { MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); - if (server == null) return false; - ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); - if (player == null) return false; - player.networkHandler.disconnect(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s))); + if (server != null && server.isMainThread()) { + ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); + if (player == null) return false; + player.networkHandler.disconnect(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s))); + } } - return true; + return false; } @Override @@ -235,11 +253,11 @@ public class VRPlatform implements ViaPlatform { List mods = new ArrayList<>(); for (ModContainer mod : FabricLoader.INSTANCE.getModContainers()) { mods.add(new PluginInfo(true, - mod.getInfo().getName(), - mod.getInfo().getVersionString(), + mod.getMetadata().getName(), + mod.getMetadata().getVersion().getFriendlyString(), String.join(", ", mod.getInfo().getInitializers()), mod.getInfo().getAuthors().stream() - .map(info -> info.getName() + " <" + info.getEmail() + "> " + "[" + info.getWebsite() + "]") + .map(info -> info.getName() + " <" + info.getEmail() + "> (" + info.getWebsite() + ")") .collect(Collectors.toList()) )); } diff --git a/src/main/java/com/github/creeper123123321/viafabric/protocol/protocol1_8to1_7_6_10/Protocol1_8TO1_7_6_10.java b/src/main/java/com/github/creeper123123321/viafabric/protocol/protocol1_8to1_7_6_10/Protocol1_8TO1_7_6_10.java index fa6177a..192a719 100644 --- a/src/main/java/com/github/creeper123123321/viafabric/protocol/protocol1_8to1_7_6_10/Protocol1_8TO1_7_6_10.java +++ b/src/main/java/com/github/creeper123123321/viafabric/protocol/protocol1_8to1_7_6_10/Protocol1_8TO1_7_6_10.java @@ -49,6 +49,7 @@ import us.myles.ViaVersion.api.type.types.VoidType; import us.myles.ViaVersion.api.type.types.version.Types1_8; import us.myles.ViaVersion.packets.State; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -278,14 +279,11 @@ public class Protocol1_8TO1_7_6_10 extends Protocol { delayedPacket.write(Type.SHORT, item); delayedPacket.write(Types1_8.METADATA_LIST, metadata); - Via.getPlatform().runSync(new Runnable() { - @Override - public void run() { - try { - delayedPacket.send(Protocol1_8TO1_7_6_10.class); - } catch (Exception ex) { - ex.printStackTrace(); - } + Via.getPlatform().runSync(() -> { + try { + delayedPacket.send(Protocol1_8TO1_7_6_10.class); + } catch (Exception ex) { + ex.printStackTrace(); } }, 1L); } else { @@ -925,14 +923,11 @@ public class Protocol1_8TO1_7_6_10 extends Protocol { this.registerOutgoing(State.PLAY, 0x33, 0x33, new PacketRemapper() { @Override public void registerMap() { - map(new ValueReader() { - @Override - public Position read(PacketWrapper packetWrapper) throws Exception { - long x = packetWrapper.read(Type.INT); - long y = packetWrapper.read(Type.SHORT); - long z = packetWrapper.read(Type.INT); - return new Position(x, y, z); - } + map(packetWrapper -> { + long x = packetWrapper.read(Type.INT); + long y = packetWrapper.read(Type.SHORT); + long z = packetWrapper.read(Type.INT); + return new Position(x, y, z); }, new TypeRemapper<>(Type.POSITION)); //Position handler(new PacketHandler() { @Override @@ -1008,14 +1003,11 @@ public class Protocol1_8TO1_7_6_10 extends Protocol { this.registerOutgoing(State.PLAY, 0x35, 0x35, new PacketRemapper() { @Override public void registerMap() { - map(new ValueReader() { - @Override - public Position read(PacketWrapper packetWrapper) throws Exception { - long x = packetWrapper.read(Type.INT); - long y = packetWrapper.read(Type.SHORT); - long z = packetWrapper.read(Type.INT); - return new Position(x, y, z); - } + map(packetWrapper -> { + long x = packetWrapper.read(Type.INT); + long y = packetWrapper.read(Type.SHORT); + long z = packetWrapper.read(Type.INT); + return new Position(x, y, z); }, new TypeRemapper<>(Type.POSITION)); //Position map(Type.UNSIGNED_BYTE); //Action map(Types1_7_6_10.COMPRESSED_NBT, Type.NBT); @@ -1180,7 +1172,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol { short length = packetWrapper.read(Type.SHORT); if (channel.equals("MC|Brand")) { byte[] data = packetWrapper.read(new CustomByteType((int) length)); - String brand = new String(data, "UTF-8"); + String brand = new String(data, StandardCharsets.UTF_8); packetWrapper.write(Type.STRING, brand); } else if (channel.equals("MC|AdvCdm")) { byte type = packetWrapper.passthrough(Type.BYTE); @@ -1690,7 +1682,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol { public final String name; public final int extra; - private static final HashMap particleMap = new HashMap(); + private static final HashMap particleMap = new HashMap<>(); Particle(String name) { this(name, 0); diff --git a/src/main/java/com/github/creeper123123321/viafabric/util/ManagedBlockerRunnable.java b/src/main/java/com/github/creeper123123321/viafabric/util/ManagedBlockerRunnable.java deleted file mode 100644 index f24406d..0000000 --- a/src/main/java/com/github/creeper123123321/viafabric/util/ManagedBlockerRunnable.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 creeper123123321 and contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.creeper123123321.viafabric.util; - -import java.util.concurrent.ForkJoinPool; - -public class ManagedBlockerRunnable implements ForkJoinPool.ManagedBlocker { - private final Runnable runnable; - private boolean release; - - public ManagedBlockerRunnable(Runnable runnable) { - this.runnable = runnable; - release = false; - } - - @Override - public boolean block() { - runnable.run(); - release = true; - return true; - } - - @Override - public boolean isReleasable() { - return release; - } -}