Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 223
src/main/java/dev/kodari/automute/AutoMuteClient.java
package dev.kodari.automute;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Pattern;
public final class AutoMuteClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("raidkp_automute");
private static final Path CONFIG = FabricLoader.getInstance().getConfigDir().resolve("raidkp_automute.json");
private static final long DELAY_NANOS = 1_000_000_000L;
private static final Pattern USERNAME = Pattern.compile("[A-Za-z0-9_]{1,16}");
private static final Pattern DURATION = Pattern.compile("[1-9][0-9]*[smhdw]", Pattern.CASE_INSENSITIVE);
private final Queue<PendingMute> pending = new ArrayDeque<>();
private List<Rule> rules = List.of();
private boolean enabled = true;
private Object connection;
private long lastSend;
@Override
public void onInitializeClient() {
try {
reload();
} catch (Exception e) {
LOGGER.error("Could not load AutoMute configuration; no rules are active", e);
}
ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, timestamp) -> {
MinecraftClient client = MinecraftClient.getInstance();
if (!enabled || client.player == null || client.getNetworkHandler() == null || sender == null
|| sender.getId().equals(client.player.getUuid())) {
return;
}
String name = sender.getName();
if (name == null || !USERNAME.matcher(name).matches()) {
return;
}
String content = signedMessage == null ? message.getString() : signedMessage.getSignedContent();
for (Rule rule : rules) {
if (rule.patterns().stream().anyMatch(pattern -> pattern.matcher(content).find())) {
String command = "tempmute " + name + " " + rule.duration() + " " + rule.reason();
if (command.length() <= 256) {
pending.add(new PendingMute(command, System.nanoTime(), client.getNetworkHandler()));
} else {
LOGGER.warn("AutoMute command for {} exceeds the chat command limit", name);
}
break;
}
}
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
Object current = client.getNetworkHandler();
if (current != connection) {
pending.clear();
connection = current;
lastSend = 0;
}
if (!enabled || current == null || client.player == null || pending.isEmpty()) {
return;
}
PendingMute next = pending.peek();
long now = System.nanoTime();
if (next.connection() != current) {
pending.remove();
} else if (now - next.queuedAt() >= DELAY_NANOS && (lastSend == 0 || now - lastSend >= DELAY_NANOS)) {
pending.remove();
client.getNetworkHandler().sendChatCommand(next.command());
lastSend = now;
}
});
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(
ClientCommandManager.literal("automute")
.then(ClientCommandManager.literal("toggle").executes(context -> {
enabled = !enabled;
if (!enabled) pending.clear();
context.getSource().sendFeedback(Text.literal("AutoMute " + (enabled ? "enabled" : "disabled") + "."));
return 1;
}))
.then(ClientCommandManager.literal("reload").executes(context -> {
try {
reload();
pending.clear();
context.getSource().sendFeedback(Text.literal("AutoMute config reloaded: " + rules.size() + " rules."));
return 1;
} catch (Exception e) {
LOGGER.error("Could not reload AutoMute configuration", e);
context.getSource().sendError(Text.literal("AutoMute reload failed: " + e.getMessage()));
return 0;
}
}))));
}
private void reload() throws IOException {
if (Files.notExists(CONFIG)) {
Files.createDirectories(CONFIG.getParent());
Files.writeString(CONFIG, "{\n \"rules\": []\n}\n", StandardCharsets.UTF_8);
}
JsonObject root = JsonParser.parseString(Files.readString(CONFIG, StandardCharsets.UTF_8)).getAsJsonObject();
JsonArray entries = root.getAsJsonArray("rules");
if (entries == null) throw new IllegalArgumentException("Missing rules array");
List<Rule> loaded = new ArrayList<>();
for (JsonElement entry : entries) {
JsonObject object = entry.getAsJsonObject();
JsonArray triggers = object.getAsJsonArray("triggers");
if (triggers == null || triggers.isEmpty()) throw new IllegalArgumentException("Each rule needs triggers");
List<Pattern> patterns = new ArrayList<>();
for (JsonElement trigger : triggers) {
String expression = trigger.getAsString();
if (expression.isBlank()) throw new IllegalArgumentException("Triggers cannot be blank");
patterns.add(Pattern.compile(expression, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
}
String duration = object.get("duration").getAsString();
String reason = object.get("reason").getAsString();
if (!DURATION.matcher(duration).matches()) throw new IllegalArgumentException("Invalid duration: " + duration);
if (reason.isBlank() || reason.chars().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException("Reason must be nonempty and contain no control characters");
}
loaded.add(new Rule(List.copyOf(patterns), duration, reason));
}
rules = List.copyOf(loaded);
}
private record Rule(List<Pattern> patterns, String duration, String reason) {}
private record PendingMute(String command, long queuedAt, Object connection) {}
}