initial release

This commit is contained in:
2021-01-27 22:41:16 +01:00
parent c3ff68b5ce
commit 97de58e8ec
3 changed files with 28 additions and 136 deletions

View File

@ -1,126 +1,50 @@
package de.mrgeorgen.wolfSignal;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientCommandSource;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.nbt.*;
import net.minecraft.util.Formatting;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.IntStream;
import static com.mojang.brigadier.Command.SINGLE_SUCCESS;
import static de.mrgeorgen.wolfSignal.ClientCommands.*;
import static de.mrgeorgen.wolfSignal.Util.*;
import static net.minecraft.command.arguments.NbtTagArgumentType.nbtTag;
import static net.minecraft.util.Formatting.*;
import com.mojang.brigadier.arguments.IntegerArgumentType;
public class Main implements ModInitializer
{
public class Main implements ModInitializer {
public static final String MOD_ID = "wolfsignal";
public static int[] delayList = { 3, 10, 30, 60 };
public static int ticks = -1;
public static int attempt = -1;
public static ServerInfo lastServerEntry = null;
public static boolean pause = false;
public static int signal = -1;
public static int disconnectTicks = -1;
public static int signalIndex = -1;
public static boolean disconnectedCausedByWolfSignal = false;
@Override
public void onInitialize()
{
ClientCommands.register(literal("reload").executes(Main::cmdReload));
ClientCommands.register(literal("config").then(argument("delayList", nbtTag()).executes(Main::cmdConfig)));
loadConfig();
public void onInitialize() {
ClientCommands.register(literal("signal").then(argument("signal", IntegerArgumentType.integer(0, 31)).executes(Main::cmdSignal)));
ClientTickEvents.END_CLIENT_TICK.register(client -> disconnectTimeout());
}
private static int cmdReload(CommandContext<ClientCommandSource> ctx)
{
loadConfig();
private static int cmdSignal(CommandContext<ClientCommandSource> ctx) {
signal = ctx.getArgument("signal", int.class);
MinecraftClient.getInstance().world.disconnect();
signalIndex = 4;
setTick();
return SINGLE_SUCCESS;
}
private static int cmdConfig(CommandContext<ClientCommandSource> ctx)
{
Tag tag = ctx.getArgument("delayList", Tag.class);
try
{
// if tag is not a list or a list not containing integers it will pass null or an empty list
setDelayList(tag instanceof AbstractListTag ? ((AbstractListTag<? extends Tag>) tag).stream().filter(IntTag.class::isInstance).map(IntTag.class::cast).mapToInt(IntTag::getInt).toArray() : null);
saveConfig();
send(colored("Current configuration: " + Arrays.toString(delayList), GREEN));
}
catch (IOException | IllegalArgumentException ex)
{
send(err(ex));
}
return SINGLE_SUCCESS;
}
private static void loadConfig()
{
Path configPath = FabricLoader.getInstance().getConfigDir().resolve(MOD_ID + ".json");
try
{
setDelayList(new Gson().fromJson(Files.newBufferedReader(configPath), int[].class));
send(colored("Current configuration: " + Arrays.toString(delayList), GREEN));
}
catch (IOException | IllegalArgumentException | JsonParseException ex)
{
send(err(ex));
try
{
send(colored("Creating default config...", GREEN));
saveConfig();
}
catch (IOException ex2)
{
send(err(ex2));
}
private static void disconnectTimeout() {
if(disconnectTicks >= 0 && --disconnectTicks == 0) {
MinecraftClient.getInstance().world.disconnect();
setTick();
}
}
private static void saveConfig() throws IOException
{
Path configPath = FabricLoader.getInstance().getConfigDir().resolve(MOD_ID + ".json");
File configFile = configPath.toFile();
// if file already exists or could successfully be created
if (configFile.exists() || configFile.createNewFile())
{
Files.write(configPath, new Gson().toJson(delayList).getBytes());
send(colored("Saved config", GREEN));
private static void setTick() {
if(signalIndex >= 0) {
ticks = (signal & 1 << signalIndex--) != 0 ? 12 * 20 : 6 * 20;
}
}
private static void setDelayList(int[] delayList) throws IllegalArgumentException
{
// if null or empty or contains negatives or zeros
if (delayList == null || delayList.length == 0 || IntStream.of(delayList).anyMatch(i -> i <= 0))
throw new IllegalArgumentException("delayList must be a non-empty list of strictly positive integers");
Main.delayList = delayList;
}
public static void resetAttempts()
{
ticks = -1;
attempt = -1;
log("reset");
}
public static String getMessage()
{
return attempt < 0 ? "Could not reconnect" : String.format("Reconnect in %d...", ticks / 20 + 1);
}
public static int getColor()
{
return Optional.of(attempt < 0 ? RED : GREEN).filter(Formatting::isColor).map(Formatting::getColorValue).orElse(0xFFFFFF);
}
}

View File

@ -26,11 +26,11 @@ public class Util
Logger logger = LogManager.getLogger("AutoReconnect");
if (Objects.equals(text.getStyle().getColor(), TextColor.fromFormatting(RED)))
{
logger.error("[AutoReconnect] " + text.getString());
logger.error("[wolfSignal] " + text.getString());
}
else
{
logger.info("[AutoReconnect] " + text.getString());
logger.info("[wolfSignal] " + text.getString());
}
}
else player.sendMessage(text, false);

View File

@ -35,45 +35,13 @@ public class MixinMinecraftClient
// if not paused, decrements countdown until its negative, succeeds if its 0
if (ticks >= 0 && --ticks == 0)
{
if (lastServerEntry == null)
{
resetAttempts();
}
else
if (lastServerEntry != null)
{
MinecraftClient mc = MinecraftClient.getInstance();
mc.openScreen(new ConnectScreen(new MultiplayerScreen(new TitleScreen()), mc, lastServerEntry));
}
}
}
@Inject(at = @At("INVOKE"), method = "openScreen")
private void openScreen(Screen newScreen, CallbackInfo info)
{
// old and new screen must not be the same type, actually happens very often for some reason
if ((currentScreen == null ? null : currentScreen.getClass()) != (newScreen == null ? null : newScreen.getClass()))
{
if (currentScreen instanceof DisconnectedScreen && ( // exited disconnect screen using...
newScreen instanceof MultiplayerScreen || // ...cancel button on disconnect screen
newScreen instanceof TitleScreen || // ...escape key
newScreen != null && newScreen.getClass().getSimpleName().equals("AuthScreen")) || // ...AuthMe re-authenticate button
(currentScreen instanceof ConnectScreen && !(newScreen instanceof DisconnectedScreen))) // connection successful or cancelled using cancel button on connect screen
{
resetAttempts();
}
// player got disconnected
else if (newScreen instanceof DisconnectedScreen)
{
// if last known server is not null and next attempt is configured
if (lastServerEntry != null && ++attempt < delayList.length)
{
ticks = delayList[attempt] * 20;
if(disconnectedCausedByWolfSignal = signalIndex >= 0) {
disconnectTicks = 2 * 20;
}
else
{
resetAttempts();
}
log("lastServerEntry: %s, attempt: %d", lastServerEntry == null ? "null" : lastServerEntry.name, attempt);
}
}
}