package io.gitlab.jfronny.libjf.web.impl; import com.mojang.brigadier.Command; import io.gitlab.jfronny.commons.ref.R; 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.v1.WebServer; import io.gitlab.jfronny.libjf.web.impl.variant.hosted.HostedWebServer; import io.gitlab.jfronny.libjf.web.impl.variant.shared.SharedWebServer; import net.fabricmc.api.EnvType; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.text.Text; import org.jetbrains.annotations.ApiStatus; import java.time.chrono.IsoEra; import static net.minecraft.server.command.CommandManager.literal; public class JfWeb implements CoProcess, ModInitializer { private static final RequestHandler handler; public static final WebServer SERVER; static { JfWebConfig.ensureValidPort(); handler = new RequestHandler(); if (JfWebConfig.port != -1) SERVER = new HostedWebServer(handler, JfWebConfig.port, JfWebConfig.maxConnections); else if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) SERVER = new HostedWebServer(handler, 0, JfWebConfig.maxConnections); else SERVER = new SharedWebServer(handler); } @ApiStatus.Internal public static RequestHandler getHandler() { return handler; } @Override public void start() { if (isEnabled()) SERVER.queueRestart(R::nop); } @Override public void stop() { if (!(SERVER instanceof SharedWebServer)) 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.queueRestart(() -> { context.getSource().sendFeedback(() -> Text.literal("LibWeb restarted"), true); }); } catch (Exception e) { LibJf.LOGGER.error("Failed to run restart command", e); context.getSource().sendError(Text.literal(e.getMessage())); } return Command.SINGLE_SUCCESS; })))); }); } } private boolean isEnabled() { boolean enable = JfWebConfig.enableFileHost; for (Flags.BooleanFlag web : Flags.getBoolFlags("web")) enable |= web.value(); return enable; } }