Simplify pack validation and merge response mixins

This commit is contained in:
2026-09-13 21:55:44 +03:00
parent 33eaec8b19
commit 47967b55ea
13 changed files with 266 additions and 181 deletions
@@ -1,12 +1,9 @@
package online.astradev.packs;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
@@ -24,9 +21,14 @@ import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
public final class AstraPacks {
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
@@ -103,15 +105,19 @@ public final class AstraPacks {
}
private void registerCommands(RegisterCommandsEvent event) {
LiteralArgumentBuilder<CommandSourceStack> command = Commands.literal("astrapacks")
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
.executes(this::status);
LiteralArgumentBuilder<CommandSourceStack> command =
Commands.literal("astrapacks")
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
.executes(this::status);
command.then(Commands.literal("status").executes(this::status));
command.then(Commands.literal("build").executes(this::build));
command.then(Commands.literal("reload").executes(this::reload));
command.then(Commands.literal("send")
.then(Commands.argument("players", EntityArgument.players()).executes(this::send)));
command.then(
Commands.literal("send")
.then(
Commands.argument("players", EntityArgument.players())
.executes(this::send)));
event.getDispatcher().register(command);
}
@@ -144,7 +150,8 @@ public final class AstraPacks {
for (ServerPlayer player : players) {
runtime.session(player.connection).start(player.connection::send);
}
source.sendSuccess(() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
source.sendSuccess(
() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
return players.size();
}
}
@@ -1,5 +1,8 @@
package online.astradev.packs;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
@@ -16,9 +19,6 @@ import java.util.HexFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/** Archives the shared content directory, keeping the current and one previous ZIP. */
public final class PackBuilder {
public record Pack(Path path, String sha1, int files, long bytes) {}
@@ -71,19 +71,29 @@ public final class PackBuilder {
}
}
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
// Shared with server-side exporters (AstraPlus). A build must see one complete asset generation.
String lock = "AstraPacks:contents:" + contents.toAbsolutePath().normalize().toString().toLowerCase(java.util.Locale.ROOT);
private int writeArchive(Path contents, Path target, String resourceVersion)
throws IOException {
// Shared with server-side exporters (AstraPlus). A build must see one complete asset
// generation.
String lock =
"AstraPacks:contents:"
+ contents.toAbsolutePath()
.normalize()
.toString()
.toLowerCase(java.util.Locale.ROOT);
synchronized (lock.intern()) {
return writeLockedArchive(contents, target, resourceVersion);
}
}
private int writeLockedArchive(Path contents, Path target, String resourceVersion) throws IOException {
private int writeLockedArchive(Path contents, Path target, String resourceVersion)
throws IOException {
int files = 0;
long totalBytes = 0;
try (var paths = Files.walk(contents);
var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) {
var zip =
new ZipOutputStream(
new BufferedOutputStream(Files.newOutputStream(target)))) {
for (Path file : paths.sorted().toList()) {
if (Files.isSymbolicLink(file)) {
throw new IOException("Symbolic links are not supported: " + file);
@@ -105,8 +115,10 @@ public final class PackBuilder {
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
long limit = Math.min(config.build.maxFileMiB * 1024L * 1024L,
config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
long limit =
Math.min(
config.build.maxFileMiB * 1024L * 1024L,
config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
totalBytes += copyResource(file, zip, limit);
zip.closeEntry();
}
@@ -119,7 +131,8 @@ public final class PackBuilder {
return files + 1;
}
private static long copyResource(Path file, OutputStream output, long limit) throws IOException {
private static long copyResource(Path file, OutputStream output, long limit)
throws IOException {
byte[] buffer = new byte[8192];
long size = 0;
try (var input = Files.newInputStream(file)) {
@@ -168,14 +181,14 @@ public final class PackBuilder {
try (var paths = Files.list(output)) {
for (Path path : paths.toList()) {
String name = path.getFileName().toString();
if (name.matches("[a-f0-9]{40}\\.zip") && !name.equals(pack.sha1() + ".zip")
&& (previous == null || !name.equals(previous + ".zip"))
&& Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
Files.delete(path);
}
if (!name.matches("[a-f0-9]{40}\\.zip")) continue;
if (name.equals(pack.sha1() + ".zip")) continue;
if (previous != null && name.equals(previous + ".zip")) continue;
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) Files.delete(path);
}
}
PackFiles.atomicWrite(manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
PackFiles.atomicWrite(
manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
}
public static Pack latest(Path root, PackConfig config) throws IOException {
@@ -192,11 +205,16 @@ public final class PackBuilder {
private static JsonObject readManifest(Path path) throws IOException {
try {
JsonObject info = JsonParser.parseString(Files.readString(path)).getAsJsonObject();
if (!info.get("sha1").getAsString().matches("[a-f0-9]{40}")
|| (info.has("previousSha1") && !info.get("previousSha1").getAsString().matches("[a-f0-9]{40}"))
|| info.get("files").getAsInt() < 1) {
throw new IOException("Invalid resource pack manifest: " + path);
String current = info.get("sha1").getAsString();
if (!current.matches("[a-f0-9]{40}"))
throw new IOException("Invalid current pack hash: " + path);
if (info.has("previousSha1")) {
String previous = info.get("previousSha1").getAsString();
if (!previous.matches("[a-f0-9]{40}"))
throw new IOException("Invalid previous pack hash: " + path);
}
if (info.get("files").getAsInt() < 1)
throw new IOException("Empty resource pack manifest: " + path);
return info;
} catch (RuntimeException e) {
throw new IOException("Invalid resource pack manifest: " + path, e);
@@ -1,5 +1,8 @@
package online.astradev.packs;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@@ -8,12 +11,10 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/** Server-local configuration, deliberately never synchronized to clients. */
public final class PackConfig {
public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public static final Gson JSON =
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public boolean enabled = true;
public Build build = new Build();
@@ -62,13 +63,18 @@ public final class PackConfig {
}
public static final class Messages {
public String prompt = "&6Привет, {player}!\\n"
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
+ "&aНажми «Продолжить», чтобы загрузить его.";
public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n"
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова.";
public String failed = "&cНе удалось загрузить ресурспак сервера.\\n"
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации.";
public String prompt =
"&6Привет, {player}!\\n"
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
+ "&aНажми «Продолжить», чтобы загрузить его.";
public String declined =
"&cДля входа необходимо принять ресурспак сервера.\\n"
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись"
+ " снова.";
public String failed =
"&cНе удалось загрузить ресурспак сервера.\\n"
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи"
+ " администрации.";
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
public String loaded = "&aРесурспак AstraDev загружен.";
@@ -76,7 +82,8 @@ public final class PackConfig {
public static PackConfig load(Path path) throws IOException {
if (!Files.exists(path)) {
byte[] defaults = (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8);
byte[] defaults =
(JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8);
PackFiles.atomicWrite(path, defaults);
}
try {
@@ -112,8 +119,14 @@ public final class PackConfig {
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
}
var texts = List.of(messages.prompt, messages.declined, messages.failed,
messages.timeout, messages.unavailable, messages.loaded);
var texts =
List.of(
messages.prompt,
messages.declined,
messages.failed,
messages.timeout,
messages.unavailable,
messages.loaded);
for (String message : texts) {
if (message.length() > 8192) {
throw new IllegalArgumentException("Message exceeds 8192 characters");
@@ -135,8 +148,10 @@ public final class PackConfig {
private void validateHosting() {
Objects.requireNonNull(hosting.bindAddress, "hosting.bindAddress");
Objects.requireNonNull(hosting.publicAddress, "hosting.publicAddress");
if (!hosting.publicAddress.isBlank() && validateUrl(hosting.publicAddress).getQuery() != null) {
throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters");
if (!hosting.publicAddress.isBlank()
&& validateUrl(hosting.publicAddress).getQuery() != null) {
throw new IllegalArgumentException(
"hosting.publicAddress must not contain query parameters");
}
range(hosting.port, 1, 65535, "port");
range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp");
@@ -148,7 +163,10 @@ public final class PackConfig {
public static URI validateUrl(String value) {
URI uri = URI.create(value);
boolean http = "http".equals(uri.getScheme()) || "https".equals(uri.getScheme());
if (!http || uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null) {
if (!http
|| uri.getHost() == null
|| uri.getUserInfo() != null
|| uri.getFragment() != null) {
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
}
return uri;
@@ -15,7 +15,11 @@ final class PackFiles {
try {
Files.write(temporary, bytes);
try {
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
Files.move(
temporary,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
}
@@ -1,5 +1,8 @@
package online.astradev.packs;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -15,9 +18,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
/** Serves only published archives, with expiring links and bounded downloads. */
public final class PackHost implements AutoCloseable {
private record Grant(String hash, long expires) {}
@@ -112,9 +112,12 @@ public final class PackHost implements AutoCloseable {
for (String parameter : query.split("&")) {
if (parameter.startsWith("token=")) {
try {
String token = URLDecoder.decode(parameter.substring(6), StandardCharsets.UTF_8);
String token =
URLDecoder.decode(parameter.substring(6), StandardCharsets.UTF_8);
Grant grant = grants.get(token);
return grant != null && grant.hash().equals(hash) && grant.expires() >= System.currentTimeMillis();
return grant != null
&& grant.hash().equals(hash)
&& grant.expires() >= System.currentTimeMillis();
} catch (IllegalArgumentException e) {
return false;
}
@@ -123,7 +126,8 @@ public final class PackHost implements AutoCloseable {
return false;
}
private void sendFile(HttpExchange exchange, Path file, String hash) throws IOException, InterruptedException {
private void sendFile(HttpExchange exchange, Path file, String hash)
throws IOException, InterruptedException {
var headers = exchange.getResponseHeaders();
headers.set("Content-Type", "application/zip");
headers.set("ETag", '"' + hash + '"');
@@ -144,7 +148,9 @@ public final class PackHost implements AutoCloseable {
int read;
while ((read = input.read(buffer)) != -1) {
transferred += read;
long delay = transferred * 1_000_000_000L / bytesPerSecond - (System.nanoTime() - started);
long delay =
transferred * 1_000_000_000L / bytesPerSecond
- (System.nanoTime() - started);
if (delay > 0) {
TimeUnit.NANOSECONDS.sleep(delay);
}
@@ -1,14 +1,5 @@
package online.astradev.packs;
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;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
@@ -18,6 +9,15 @@ 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;
@@ -27,10 +27,12 @@ public final class PackRuntime implements AutoCloseable {
private final Path root;
private final Path configPath;
private final PackHost host;
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions = new ConcurrentHashMap<>();
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 final ExecutorService worker =
Executors.newSingleThreadExecutor(
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
private volatile PackConfig config;
private volatile PackBuilder.Pack current;
@@ -51,7 +53,9 @@ public final class PackRuntime implements AutoCloseable {
return;
}
if (server.getServerResourcePack().isPresent()) {
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
throw new IOException(
"AstraPacks must be the only pack sender: clear resource-pack in"
+ " server.properties");
}
Files.createDirectories(config.contents(root));
@@ -62,10 +66,16 @@ public final class PackRuntime implements AutoCloseable {
}
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.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());
AstraPacks.LOG.info(
"AstraPacks: HTTP port={}, required={}, pack={}",
config.hosting.port,
config.delivery.required,
current == null ? "UNAVAILABLE" : current.path());
}
private PackBuilder.Pack loadStartupPack() {
@@ -73,7 +83,8 @@ public final class PackRuntime implements AutoCloseable {
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);
AstraPacks.LOG.error(
"Resource-pack build failed; trying the last successful build", e);
}
}
try {
@@ -101,17 +112,19 @@ public final class PackRuntime implements AutoCloseable {
return session;
}
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
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);
}
});
server.execute(
() -> {
PackSession session = sessions.get(listener);
if (session != null) {
session.response(packet);
}
});
return true;
}
@@ -150,7 +163,8 @@ public final class PackRuntime implements AutoCloseable {
public String url(PackBuilder.Pack pack) {
String address = config.hosting.publicAddress;
if (address.isBlank()) {
throw new IllegalStateException("Set hosting.publicAddress before sending resource packs");
throw new IllegalStateException(
"Set hosting.publicAddress before sending resource packs");
}
return address.replaceAll("/+$", "") + host.issuePath(pack);
}
@@ -174,27 +188,36 @@ public final class PackRuntime implements AutoCloseable {
}
building = true;
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
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)
if (next.enabled != config.enabled
|| !next.hosting.sameSettings(config.hosting)
|| !next.build.storageDirectory.equals(config.build.storageDirectory)) {
throw new IOException("Изменение enabled, каталога хранения или настроек HTTP-сервера требует перезапуска.");
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(() -> {
building = false;
if (!closed) {
source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён."));
}
});
server.execute(
() -> {
building = false;
if (!closed) {
source.sendFailure(
Component.literal(
"AstraPacks: "
+ e.getMessage()
+ " Рабочий пак сохранён."));
}
});
}
}
@@ -207,8 +230,13 @@ public final class PackRuntime implements AutoCloseable {
host.publish(pack);
current = pack;
String message = "AstraPacks: готово, " + pack.files() + " файлов, "
+ pack.bytes() + " байт. SHA-1: " + pack.sha1();
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()) {
@@ -218,10 +246,22 @@ public final class PackRuntime implements AutoCloseable {
}
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;
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
@@ -1,9 +1,5 @@
package online.astradev.packs;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
@@ -12,7 +8,13 @@ import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
/** Keeps the configuration task open until the client reports a loaded pack or an allowed failure. */
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
/**
* Keeps the configuration task open until the client reports a loaded pack or an allowed failure.
*/
public final class PackSession implements ConfigurationTask {
public static final Type TYPE = new Type("astrapacks:resource_pack");
@@ -59,8 +61,9 @@ public final class PackSession implements ConfigurationTask {
prompt = Optional.of(PackText.of(config.messages.prompt, playerName()));
}
String url = runtime.url(pack);
listener.send(new ClientboundResourcePackPushPacket(
requestId, url, pack.sha1(), config.delivery.required, prompt));
listener.send(
new ClientboundResourcePackPushPacket(
requestId, url, pack.sha1(), config.delivery.required, prompt));
} catch (RuntimeException e) {
AstraPacks.LOG.error("Cannot send resource pack to {}", playerName(), e);
fail(config.messages.unavailable);
@@ -72,7 +75,8 @@ public final class PackSession implements ConfigurationTask {
return;
}
if (config.delivery.logStatus) {
AstraPacks.LOG.info("Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
AstraPacks.LOG.info(
"Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
}
switch (packet.action()) {
case SUCCESSFULLY_LOADED -> {
@@ -1,26 +0,0 @@
package online.astradev.packs.mixin;
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import online.astradev.packs.PackRuntime;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerCommonPacketListenerImpl.class)
public abstract class CommonResponseMixin {
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
private void astrapacks$handleResponse(ServerboundResourcePackPacket packet, CallbackInfo callback) {
PackRuntime runtime = PackRuntime.INSTANCE;
if (runtime == null) {
return;
}
// At runtime, this mixin is part of the Minecraft listener.
var listener = (ServerCommonPacketListenerImpl) (Object) this;
if (runtime.intercept(listener, packet)) {
callback.cancel();
}
}
}
@@ -3,16 +3,19 @@ package online.astradev.packs.mixin;
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
import online.astradev.packs.PackRuntime;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerConfigurationPacketListenerImpl.class)
public abstract class ConfigurationResponseMixin {
@Mixin({ServerCommonPacketListenerImpl.class, ServerConfigurationPacketListenerImpl.class})
public abstract class ResourcePackResponseMixin {
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
private void astrapacks$handleResponse(ServerboundResourcePackPacket packet, CallbackInfo callback) {
private void astrapacks$handleResponse(
ServerboundResourcePackPacket packet, CallbackInfo callback) {
PackRuntime runtime = PackRuntime.INSTANCE;
if (runtime == null) {
return;