LibJF/libjf-web-v0/src/main/java/io/gitlab/jfronny/libjf/web/impl/JfWeb.java

65 lines
2.6 KiB
Java
Raw Normal View History

2021-11-10 16:47:15 +01:00
package io.gitlab.jfronny.libjf.web.impl;
import com.mojang.brigadier.Command;
import io.gitlab.jfronny.libjf.Flags;
import io.gitlab.jfronny.libjf.LibJf;
2022-02-12 12:16:19 +01:00
import io.gitlab.jfronny.libjf.coprocess.CoProcess;
2021-11-10 16:47:15 +01:00
import io.gitlab.jfronny.libjf.web.api.WebServer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
2023-03-11 21:24:59 +01:00
import net.minecraft.text.Text;
2022-02-06 16:40:17 +01:00
2022-01-29 12:06:02 +01:00
import static net.minecraft.server.command.CommandManager.literal;
2021-11-10 16:47:15 +01:00
2022-02-12 12:16:19 +01:00
public class JfWeb implements CoProcess, ModInitializer {
public static final WebServer SERVER;
static {
2021-11-10 16:47:15 +01:00
JfWebConfig.ensureValidPort();
SERVER = new JfWebServer(JfWebConfig.port, JfWebConfig.maxConnections);
2021-11-10 16:47:15 +01:00
}
@Override
2022-02-12 12:16:19 +01:00
public void start() {
if (isEnabled()) SERVER.restart();
2021-11-10 16:47:15 +01:00
}
@Override
2022-02-12 12:16:19 +01:00
public void stop() {
if (isEnabled()) SERVER.stop();
2021-11-10 16:47:15 +01:00
}
@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 -> {
2022-01-29 12:06:02 +01:00
if (SERVER.isActive()) {
context.getSource().sendFeedback(Text.literal("LibWeb is active. Use libweb restart to reload"), false);
2022-01-29 12:06:02 +01:00
}
else {
context.getSource().sendFeedback(Text.literal("LibWeb is not active. Use libweb restart to reload"), false);
2022-01-29 12:06:02 +01:00
}
return Command.SINGLE_SUCCESS;
}).then(literal("restart").executes(context -> {
try {
context.getSource().sendFeedback(Text.literal("Restarting LibWeb"), true);
2022-01-29 12:06:02 +01:00
SERVER.restart();
}
catch (Exception e) {
LibJf.LOGGER.error("Failed to run restart command", e);
context.getSource().sendError(Text.literal(e.getMessage()));
2022-01-29 12:06:02 +01:00
}
return Command.SINGLE_SUCCESS;
}))));
2021-11-10 16:47:15 +01:00
});
}
Runtime.getRuntime().addShutdownHook(new Thread(SERVER::stop));
2021-11-10 16:47:15 +01:00
}
private boolean isEnabled() {
boolean enable = JfWebConfig.enableFileHost;
for (Flags.BooleanFlag web : Flags.getBoolFlags("web")) enable |= web.value();
return enable;
}
}