/viaver, fix scheduler, do not add clientsidereference to server

This commit is contained in:
creeper123123321 2019-03-04 18:34:04 -03:00
parent 04d5ec9d46
commit f1c5c32a0e
No known key found for this signature in database
GPG Key ID: 0AC57D54786721D1
6 changed files with 83 additions and 142 deletions

View File

@ -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<CommandDispatcher<CommandSource>>) command -> command
.register(
LiteralArgumentBuilder.<CommandSource>literal("viafabricclient")
.then(
RequiredArgumentBuilder
.<CommandSource, String>argument("args", StringArgumentType.greedyString())
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute)
.suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion)
)
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute)
)
(Consumer<CommandDispatcher<CommandSource>>) 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.<ServerCommandSource>literal("viafabric")
.then(
RequiredArgumentBuilder
.<ServerCommandSource, String>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 <S extends CommandSource> LiteralArgumentBuilder<S> command(String commandName) {
return LiteralArgumentBuilder.<S>literal(commandName)
.then(
RequiredArgumentBuilder
.<S, String>argument("args", StringArgumentType.greedyString())
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute)
.suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion)
)
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute);
}
}

View File

@ -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();

View File

@ -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");

View File

@ -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 {
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;
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<PluginInfo> 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())
));
}

View File

@ -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,15 +279,12 @@ 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() {
Via.getPlatform().runSync(() -> {
try {
delayedPacket.send(Protocol1_8TO1_7_6_10.class);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 1L);
} else {
entryByUUID.properties = properties;
@ -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<Position>() {
@Override
public Position read(PacketWrapper packetWrapper) throws Exception {
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<Position>() {
@Override
public Position read(PacketWrapper packetWrapper) throws Exception {
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<String, Particle> particleMap = new HashMap();
private static final HashMap<String, Particle> particleMap = new HashMap<>();
Particle(String name) {
this(name, 0);

View File

@ -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;
}
}