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

75 lines
3.2 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;
import io.gitlab.jfronny.libjf.web.api.WebServer;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.minecraft.text.LiteralText;
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
public class JfWeb implements ClientModInitializer, DedicatedServerModInitializer, 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
public void onInitializeClient() {
if (isEnabled()) {
2021-11-19 15:23:07 +01:00
ClientLifecycleEvents.CLIENT_STARTED.register(client -> SERVER.restart());
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> SERVER.stop());
2021-11-10 16:47:15 +01:00
}
}
@Override
public void onInitializeServer() {
if (isEnabled()) {
2021-11-19 15:23:07 +01:00
ServerLifecycleEvents.SERVER_STARTED.register(server -> SERVER.restart());
ServerLifecycleEvents.SERVER_STOPPED.register(server -> SERVER.stop());
2021-11-10 16:47:15 +01:00
}
}
@Override
public void onInitialize() {
if (isEnabled()) {
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> {
2022-01-29 12:06:02 +01:00
dispatcher.register(literal(LibJf.MOD_ID).requires((serverCommandSource) -> serverCommandSource.hasPermissionLevel(4))
.then(literal("web").executes(context -> {
if (SERVER.isActive()) {
context.getSource().sendFeedback(new LiteralText("LibWeb is active. Use libweb restart to reload"), false);
}
else {
context.getSource().sendFeedback(new LiteralText("LibWeb is not active. Use libweb restart to reload"), false);
}
return Command.SINGLE_SUCCESS;
}).then(literal("restart").executes(context -> {
try {
context.getSource().sendFeedback(new LiteralText("Restarting LibWeb"), true);
SERVER.restart();
}
catch (Exception e) {
LibJf.LOGGER.error("Failed to run restart command", e);
context.getSource().sendError(new LiteralText(e.getMessage()));
}
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;
}
}