273 lines
9.8 KiB
Java
273 lines
9.8 KiB
Java
package online.astradev.packs;
|
|
|
|
import net.minecraft.commands.CommandSourceStack;
|
|
import net.minecraft.network.Connection;
|
|
import net.minecraft.network.chat.Component;
|
|
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
|
import net.minecraft.server.MinecraftServer;
|
|
import net.minecraft.server.level.ServerPlayer;
|
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
|
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.util.Map;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
|
|
public final class PackRuntime implements AutoCloseable {
|
|
public static volatile PackRuntime INSTANCE;
|
|
|
|
private static final String RESOURCE_VERSION = "[88,0]";
|
|
|
|
private final MinecraftServer server;
|
|
private final Path root;
|
|
private final Path configPath;
|
|
private final PackHost host;
|
|
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions =
|
|
new ConcurrentHashMap<>();
|
|
private final Map<UUID, String> pendingWelcome = new ConcurrentHashMap<>();
|
|
private final ExecutorService worker =
|
|
Executors.newSingleThreadExecutor(
|
|
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
|
|
|
private volatile PackConfig config;
|
|
private volatile PackBuilder.Pack current;
|
|
private volatile boolean closed;
|
|
// Only the server thread changes this flag, including publication and failure callbacks.
|
|
private boolean building;
|
|
|
|
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
|
this.server = server;
|
|
this.root = root;
|
|
this.configPath = configPath;
|
|
this.config = config;
|
|
this.host = new PackHost(config.hosting);
|
|
}
|
|
|
|
public void start() throws IOException {
|
|
if (!config.enabled) {
|
|
return;
|
|
}
|
|
if (server.getServerResourcePack().isPresent()) {
|
|
throw new IOException(
|
|
"AstraPacks must be the only pack sender: clear resource-pack in"
|
|
+ " server.properties");
|
|
}
|
|
|
|
Files.createDirectories(config.contents(root));
|
|
PackBuilder.Pack pack = loadStartupPack();
|
|
if (pack != null) {
|
|
host.publish(pack);
|
|
current = pack;
|
|
}
|
|
host.start();
|
|
if (config.hosting.publicAddress.isBlank()) {
|
|
AstraPacks.LOG.error(
|
|
"Set hosting.publicAddress to the public HTTP address (port {}). Pack delivery"
|
|
+ " is unavailable until configured.",
|
|
config.hosting.port);
|
|
}
|
|
AstraPacks.LOG.info(
|
|
"AstraPacks: HTTP port={}, required={}, pack={}",
|
|
config.hosting.port,
|
|
config.delivery.required,
|
|
current == null ? "UNAVAILABLE" : current.path());
|
|
}
|
|
|
|
private PackBuilder.Pack loadStartupPack() {
|
|
if (config.build.onStartup) {
|
|
try {
|
|
return new PackBuilder(config).build(root, RESOURCE_VERSION);
|
|
} catch (IOException e) {
|
|
AstraPacks.LOG.error(
|
|
"Resource-pack build failed; trying the last successful build", e);
|
|
}
|
|
}
|
|
try {
|
|
return PackBuilder.latest(root, config);
|
|
} catch (IOException e) {
|
|
AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public PackConfig config() {
|
|
return config;
|
|
}
|
|
|
|
public PackBuilder.Pack current() {
|
|
return current;
|
|
}
|
|
|
|
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
|
PackSession session = new PackSession(this, listener);
|
|
PackSession previous = sessions.put(listener, session);
|
|
if (previous != null) {
|
|
previous.removeFromClient();
|
|
}
|
|
return session;
|
|
}
|
|
|
|
public boolean intercept(
|
|
ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
|
if (!config.enabled) {
|
|
return false;
|
|
}
|
|
// Consume stale replies too: vanilla treats any terminal UUID as completion of its task.
|
|
server.execute(
|
|
() -> {
|
|
PackSession session = sessions.get(listener);
|
|
if (session != null) {
|
|
session.response(packet);
|
|
}
|
|
});
|
|
return true;
|
|
}
|
|
|
|
public void tick() {
|
|
var iterator = sessions.entrySet().iterator();
|
|
while (iterator.hasNext()) {
|
|
var entry = iterator.next();
|
|
ServerCommonPacketListenerImpl listener = entry.getKey();
|
|
Connection connection = listener.getConnection();
|
|
if (connection.isConnected()) {
|
|
entry.getValue().tick();
|
|
} else {
|
|
pendingWelcome.remove(listener.getOwner().id());
|
|
iterator.remove();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
|
if (listener instanceof ServerGamePacketListenerImpl game) {
|
|
if (!message.isBlank()) {
|
|
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
|
}
|
|
} else {
|
|
pendingWelcome.put(listener.getOwner().id(), message);
|
|
}
|
|
}
|
|
|
|
public void welcome(ServerPlayer player) {
|
|
String message = pendingWelcome.remove(player.getUUID());
|
|
if (message != null && !message.isBlank()) {
|
|
player.sendSystemMessage(PackText.of(message, player.getGameProfile().name()));
|
|
}
|
|
}
|
|
|
|
public String url(PackBuilder.Pack pack) {
|
|
String address = config.hosting.publicAddress;
|
|
if (address.isBlank()) {
|
|
throw new IllegalStateException(
|
|
"Set hosting.publicAddress before sending resource packs");
|
|
}
|
|
return address.replaceAll("/+$", "") + host.issuePath(pack);
|
|
}
|
|
|
|
public void build(CommandSourceStack source) {
|
|
requestBuild(source, false);
|
|
}
|
|
|
|
public void reload(CommandSourceStack source) {
|
|
requestBuild(source, true);
|
|
}
|
|
|
|
private void requestBuild(CommandSourceStack source, boolean reload) {
|
|
if (closed) {
|
|
source.sendFailure(Component.literal("AstraPacks остановлен."));
|
|
return;
|
|
}
|
|
if (building) {
|
|
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
|
|
return;
|
|
}
|
|
|
|
building = true;
|
|
source.sendSuccess(
|
|
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
|
worker.execute(() -> preparePack(source, reload));
|
|
}
|
|
|
|
private void preparePack(CommandSourceStack source, boolean reload) {
|
|
try {
|
|
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
|
if (next.enabled != config.enabled
|
|
|| !next.hosting.sameSettings(config.hosting)
|
|
|| !next.build.storageDirectory.equals(config.build.storageDirectory)) {
|
|
throw new IOException(
|
|
"Изменение enabled, каталога хранения или настроек HTTP-сервера требует"
|
|
+ " перезапуска.");
|
|
}
|
|
PackBuilder.Pack pack = new PackBuilder(next).build(root, RESOURCE_VERSION);
|
|
server.execute(() -> publishPack(source, next, pack));
|
|
} catch (Exception e) {
|
|
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
|
server.execute(() -> failBuild(source, e));
|
|
}
|
|
}
|
|
|
|
private void failBuild(CommandSourceStack source, Exception error) {
|
|
building = false;
|
|
if (closed) return;
|
|
String message = "AstraPacks: " + error.getMessage() + " Рабочий пак сохранён.";
|
|
source.sendFailure(Component.literal(message));
|
|
}
|
|
|
|
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
|
|
building = false;
|
|
if (closed) {
|
|
return;
|
|
}
|
|
config = next;
|
|
host.publish(pack);
|
|
current = pack;
|
|
|
|
String message =
|
|
"AstraPacks: готово, "
|
|
+ pack.files()
|
|
+ " файлов, "
|
|
+ pack.bytes()
|
|
+ " байт. SHA-1: "
|
|
+ pack.sha1();
|
|
source.sendSuccess(() -> Component.literal(message), true);
|
|
if (config.enabled && config.build.resendAfterBuild) {
|
|
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
|
|
session(player.connection).start(player.connection::send);
|
|
}
|
|
}
|
|
}
|
|
|
|
public String status() {
|
|
String pack =
|
|
current == null
|
|
? "UNAVAILABLE"
|
|
: current.path() + " (" + current.files() + " files)";
|
|
String address =
|
|
config.hosting.publicAddress.isBlank() ? "NOT SET" : config.hosting.publicAddress;
|
|
return "AstraPacks HTTP:"
|
|
+ config.hosting.port
|
|
+ ", address="
|
|
+ address
|
|
+ ", required="
|
|
+ config.delivery.required
|
|
+ ", build="
|
|
+ building
|
|
+ ", pack="
|
|
+ pack;
|
|
}
|
|
|
|
@Override
|
|
public void close() {
|
|
closed = true;
|
|
worker.shutdownNow();
|
|
host.close();
|
|
sessions.clear();
|
|
pendingWelcome.clear();
|
|
}
|
|
}
|