package io.gitlab.jfronny.libjf.web.impl; import com.mojang.brigadier.Command; import io.gitlab.jfronny.libjf.Flags; import io.gitlab.jfronny.libjf.LibJf; import io.gitlab.jfronny.libjf.coprocess.CoProcess; import io.gitlab.jfronny.libjf.web.api.WebServer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.text.Text; import static net.minecraft.server.command.CommandManager.literal; public class JfWeb implements CoProcess, ModInitializer { public static final WebServer SERVER; static { JfWebConfig.ensureValidPort(); SERVER = new JfWebServer(JfWebConfig.port, JfWebConfig.maxConnections); } @Override public void start() { if (isEnabled()) SERVER.restart(); } @Override public void stop() { if (isEnabled()) SERVER.stop(); } @Override public void onInitialize() { if (isEnabled()) { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { dispatcher.register(literal(LibJf.MOD_ID).then(literal("web").requires((serverCommandSource) -> serverCommandSource.hasPermissionLevel(4)).executes(context -> { if (SERVER.isActive()) { context.getSource().sendFeedback(Text.literal("LibWeb is active. Use libweb restart to reload"), false); } else { context.getSource().sendFeedback(Text.literal("LibWeb is not active. Use libweb restart to reload"), false); } return Command.SINGLE_SUCCESS; }).then(literal("restart").executes(context -> { try { context.getSource().sendFeedback(Text.literal("Restarting LibWeb"), true); SERVER.restart(); } catch (Exception e) { LibJf.LOGGER.error("Failed to run restart command", e); context.getSource().sendError(Text.literal(e.getMessage())); } return Command.SINGLE_SUCCESS; })))); }); } Runtime.getRuntime().addShutdownHook(new Thread(SERVER::stop)); } private boolean isEnabled() { boolean enable = JfWebConfig.enableFileHost; for (Flags.BooleanFlag web : Flags.getBoolFlags("web")) enable |= web.value(); return enable; } }