Files
AstraPacks/src/main/java/online/astradev/packs/PackRuntime.java
T

269 lines
10 KiB
Java
Raw Normal View History

package online.astradev.packs;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
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;
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 online.astradev.packs.mixin.CommonAccessor;
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, InterruptedException {
if (!config.enabled) {
return;
}
if (server.getServerResourcePack().isPresent()) {
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
}
// Custom source paths are not created: a typo in the configuration must be visible.
Files.createDirectories(root.resolve("astrapacks/contents"));
PackBuilder.Pack pack = loadStartupPack();
if (pack != null) {
try {
PackBuilder.verifyExternal(config, pack);
host.publish(pack);
current = pack;
} catch (IOException e) {
AstraPacks.LOG.error("External ZIP is not ready. Required-pack logins will be refused.", e);
}
}
host.start();
AstraPacks.LOG.info("AstraPacks: mode={}, required={}, pack={}",
config.hosting.mode, 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.previous(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 PackHost host() {
return host;
}
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 = ((CommonAccessor) listener).astrapacks$connection();
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(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
if (config.hosting.mode.equals("no_host")) {
return config.hosting.externalUrl;
}
String base = config.hosting.publicAddress;
if (base.equals("auto")) {
base = automaticAddress(listener);
}
return base.replaceAll("/+$", "") + host.issuePath(pack);
}
private String automaticAddress(ServerCommonPacketListenerImpl listener) {
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
String address = ((ConnectionData) connection).astrapacks$host();
if (address == null || address.isBlank()) {
throw new IllegalArgumentException("Cannot determine server address; set hosting.publicAddress");
}
int port = config.hosting.mode.equals("self_host") ? config.hosting.port : server.getPort();
try {
return new URI("http", null, address, port, null, null, null).toASCIIString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid server address", e);
}
}
public void build(CommandSourceStack source) {
requestBuild(source, false, false);
}
public void reload(CommandSourceStack source) {
requestBuild(source, true, false);
}
public void publish(CommandSourceStack source) {
requestBuild(source, false, true);
}
private void requestBuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
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, publishOnly));
}
private void preparePack(CommandSourceStack source, boolean reload, boolean publishOnly) {
try {
PackConfig next = reload ? PackConfig.load(configPath) : config;
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
}
PackBuilder.Pack pack = publishOnly
? PackBuilder.previous(root, next)
: new PackBuilder(next).build(root, RESOURCE_VERSION);
PackBuilder.verifyExternal(next, pack);
server.execute(() -> publishPack(source, next, pack));
} catch (Exception e) {
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
server.execute(() -> {
building = false;
if (!closed) {
source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён."));
}
});
}
}
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)";
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
+ ", build=" + building + ", pack=" + pack;
}
@Override
public void close() {
closed = true;
worker.shutdownNow();
host.close();
sessions.clear();
pendingWelcome.clear();
}
}