Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2175fb1a28 | ||
|
|
3537060ba5 | ||
|
|
a4d2fc5f5e |
@@ -1,10 +0,0 @@
|
||||
package org.examp.john.client;
|
||||
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
|
||||
public class LocalchatClient implements ClientModInitializer {
|
||||
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package org.examp.john;
|
||||
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Детектить патерн пошуку гравців через локальний чат.
|
||||
*
|
||||
* Якщо одне і те ж повідомлення повторюється >=5 разів за 5 хвилин
|
||||
* і гравець перемістився >50 блоків — логує в консоль.
|
||||
*/
|
||||
public class AntiAbuse {
|
||||
|
||||
private static final int REPEAT_THRESHOLD = 5;
|
||||
private static final double DISTANCE_THRESHOLD = 50.0;
|
||||
private static final long TIME_WINDOW_MS = 5 * 60 * 1000;
|
||||
|
||||
private static final Map<UUID, List<MessageRecord>> history = new HashMap<>();
|
||||
|
||||
public static void recordMessage(ServerPlayer player, String message) {
|
||||
UUID uuid = player.getUUID();
|
||||
List<MessageRecord> records = history.computeIfAbsent(uuid, k -> new ArrayList<>());
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
records.add(new MessageRecord(message, now, player.getX(), player.getZ()));
|
||||
|
||||
long cutoff = now - TIME_WINDOW_MS;
|
||||
records.removeIf(r -> r.timestamp < cutoff);
|
||||
|
||||
if (records.size() >= REPEAT_THRESHOLD) {
|
||||
checkForAbuse(player, records);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkForAbuse(ServerPlayer player, List<MessageRecord> records) {
|
||||
Map<String, int[]> counts = new HashMap<>();
|
||||
Map<String, double[]> bounds = new HashMap<>();
|
||||
|
||||
for (MessageRecord r : records) {
|
||||
counts.merge(r.message, new int[]{1}, (a, b) -> {
|
||||
a[0]++;
|
||||
return a;
|
||||
});
|
||||
|
||||
double[] b = bounds.computeIfAbsent(r.message, k -> new double[]{r.x, r.x, r.z, r.z});
|
||||
if (r.x < b[0]) b[0] = r.x;
|
||||
if (r.x > b[1]) b[1] = r.x;
|
||||
if (r.z < b[2]) b[2] = r.z;
|
||||
if (r.z > b[3]) b[3] = r.z;
|
||||
}
|
||||
|
||||
for (Map.Entry<String, int[]> entry : counts.entrySet()) {
|
||||
if (entry.getValue()[0] < REPEAT_THRESHOLD) continue;
|
||||
|
||||
double[] b = bounds.get(entry.getKey());
|
||||
double spread = Math.max(b[1] - b[0], b[3] - b[2]);
|
||||
|
||||
if (spread > DISTANCE_THRESHOLD) {
|
||||
Localchat.magicModLog.warn(
|
||||
"[ANTI-ABUSE] Гравець {} ймовірно шукає інших: "
|
||||
+ "'{}' ×{} разів, переміщення ~{} блоків",
|
||||
player.getName().getString(),
|
||||
entry.getKey(),
|
||||
entry.getValue()[0],
|
||||
(int) spread
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record MessageRecord(String message, long timestamp, double x, double z) {}
|
||||
}
|
||||
@@ -5,11 +5,14 @@ import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.LuckPermsProvider;
|
||||
import net.luckperms.api.model.user.User;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.HoverEvent;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import org.examp.john.stealth.StealthStorage;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -22,29 +25,11 @@ public class ChatHandler {
|
||||
ServerMessageEvents.ALLOW_CHAT_MESSAGE.register((message, sender, params) -> {
|
||||
String text = message.signedContent();
|
||||
ServerLevel serverLevel = sender.level();
|
||||
MinecraftServer server = serverLevel.getServer();
|
||||
List<ServerPlayer> players = server.getPlayerList().getPlayers();
|
||||
List<ServerPlayer> players = serverLevel.getServer().getPlayerList().getPlayers();
|
||||
|
||||
String playerPrefix = "";
|
||||
try {
|
||||
LuckPerms luckPerms = LuckPermsProvider.get();
|
||||
User user = luckPerms.getUserManager().getUser(sender.getUUID());
|
||||
if (user != null) {
|
||||
String metaPrefix = user.getCachedData().getMetaData().getPrefix();
|
||||
if (metaPrefix != null) {
|
||||
playerPrefix = metaPrefix;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
|
||||
MutableComponent formattedPrefix = Component.literal(playerPrefix.replace("&", "§"));
|
||||
MutableComponent formattedName = Component.empty()
|
||||
.append(formattedPrefix)
|
||||
.append(sender.getDisplayName());
|
||||
MutableComponent formattedName = buildFormattedName(sender);
|
||||
|
||||
if (text.startsWith(prefix)) {
|
||||
// ГЛОБАЛЬНИЙ ЧАТ
|
||||
String actualMessage = text.substring(1).trim();
|
||||
Component globalMessage = Component.empty()
|
||||
.append(formattedName)
|
||||
@@ -54,17 +39,26 @@ public class ChatHandler {
|
||||
player.sendSystemMessage(globalMessage);
|
||||
}
|
||||
|
||||
// Логування: глобальний чат чують всі онлайн-гравці
|
||||
ChatLogger.logGlobal(sender, actualMessage, players);
|
||||
|
||||
} else {
|
||||
// ЛОКАЛЬНИЙ ЧАТ
|
||||
AntiAbuse.recordMessage(sender, text);
|
||||
|
||||
if (StealthStorage.isEnabled(sender.getUUID())) {
|
||||
sender.sendSystemMessage(
|
||||
Component.literal("Вас ніхто не почув...")
|
||||
.withStyle(ChatFormatting.ITALIC, ChatFormatting.YELLOW)
|
||||
);
|
||||
ChatLogger.logUnheard(sender, text);
|
||||
return false;
|
||||
}
|
||||
|
||||
List<ServerPlayer> hearers = new ArrayList<>();
|
||||
for (ServerPlayer player : players) {
|
||||
if (player.level() == serverLevel && player.distanceTo(sender) <= LOCAL_CHAT_RADIUS) {
|
||||
if (player != sender) {
|
||||
hearers.add(player);
|
||||
}
|
||||
if (player != sender
|
||||
&& player.level() == serverLevel
|
||||
&& player.distanceTo(sender) <= LOCAL_CHAT_RADIUS) {
|
||||
hearers.add(player);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,27 +67,52 @@ public class ChatHandler {
|
||||
.append(formattedName)
|
||||
.append(Component.literal(": " + text).withStyle(ChatFormatting.GRAY));
|
||||
|
||||
// ОПТИМІЗАЦІЯ: Замість повторної перевірки всіх гравців сервера,
|
||||
// просто відправляємо повідомлення самому відправнику та вже готовому списку слухачів.
|
||||
sender.sendSystemMessage(localMessage);
|
||||
for (ServerPlayer hearer : hearers) {
|
||||
hearer.sendSystemMessage(localMessage);
|
||||
}
|
||||
|
||||
// Логування: локальний чат, хто почув + координати
|
||||
ChatLogger.logLocal(sender, text, hearers);
|
||||
|
||||
} else {
|
||||
sender.sendSystemMessage(
|
||||
Component.literal("Вас ніхто не почув, додайте на початок повідомлення \"!\" аби написати в глобальний чат")
|
||||
Component.literal("Вас ніхто не почув, додайте \"!\" на початок для глобального чату")
|
||||
.withStyle(ChatFormatting.ITALIC, ChatFormatting.YELLOW)
|
||||
);
|
||||
|
||||
// Логування: ніхто не почув
|
||||
ChatLogger.logUnheard(sender, text);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
private static MutableComponent buildFormattedName(ServerPlayer player) {
|
||||
String luckPermsPrefix = getLuckPermsPrefix(player);
|
||||
String playerName = player.getName().getString();
|
||||
String formattedPrefix = luckPermsPrefix.replace("&", "\u00a7");
|
||||
|
||||
Style clickStyle = Style.EMPTY
|
||||
.withClickEvent(new ClickEvent.SuggestCommand("/msg " + playerName + " "))
|
||||
.withHoverEvent(new HoverEvent.ShowText(
|
||||
Component.literal("Натисніть щоб написати " + playerName)
|
||||
.withStyle(ChatFormatting.GRAY)));
|
||||
|
||||
return Component.literal(formattedPrefix + playerName).withStyle(clickStyle);
|
||||
}
|
||||
|
||||
private static String getLuckPermsPrefix(ServerPlayer player) {
|
||||
try {
|
||||
LuckPerms luckPerms = LuckPermsProvider.get();
|
||||
User user = luckPerms.getUserManager().getUser(player.getUUID());
|
||||
if (user != null) {
|
||||
String metaPrefix = user.getCachedData().getMetaData().getPrefix();
|
||||
if (metaPrefix != null) {
|
||||
return metaPrefix;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import java.util.stream.Collectors;
|
||||
public class ChatLogger {
|
||||
|
||||
public static void logGlobal(ServerPlayer sender, String message, List<ServerPlayer> recipients) {
|
||||
// Для глобального чату ігноруємо список отримувачів і просто пишемо "everyone"
|
||||
Localchat.magicModLog.info(
|
||||
"[CHAT][GLOBAL] {} said: \"{}\" | heard by: everyone | pos: {}",
|
||||
sender.getName().getString(),
|
||||
@@ -23,7 +22,6 @@ public class ChatLogger {
|
||||
}
|
||||
|
||||
public static void logLocal(ServerPlayer sender, String message, List<ServerPlayer> recipients) {
|
||||
// Для локального чату виводимо лише імена отримувачів, без їхніх координат
|
||||
String heardBy = recipients.isEmpty()
|
||||
? "nobody"
|
||||
: recipients.stream()
|
||||
@@ -50,9 +48,6 @@ public class ChatLogger {
|
||||
|
||||
private static String formatPos(ServerPlayer player) {
|
||||
ServerLevel level = player.level();
|
||||
|
||||
// У ResourceKey дістаємо Identifier/ResourceLocation через .identifier(),
|
||||
// після чого через .getPath() беремо чисту назву ("overworld", "the_nether", "the_end")
|
||||
String rawDimension = level.dimension().identifier().getPath();
|
||||
|
||||
return String.format(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package org.examp.john;
|
||||
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import org.examp.john.stealth.StealthCommand;
|
||||
import org.examp.john.stealth.StealthStorage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@@ -10,7 +12,8 @@ public class Localchat implements ModInitializer {
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
// Тепер ChatHandler викликається з того ж пакета без помилок імпорту
|
||||
StealthStorage.load();
|
||||
ChatHandler.register();
|
||||
StealthCommand.register();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package org.examp.john.rules;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.Filterable;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.component.WrittenBookContent;
|
||||
import org.examp.john.Localchat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Реєструє команду /rules. Повністю server-side: не потребує жодного мода
|
||||
* на клієнті гравця. Книга створюється програмно через Data Components API
|
||||
* і відкривається через openItemGui (ClientboundOpenBookPacket).
|
||||
* Книга НЕ залишається в інвентарі — тимчасово ставиться в руку,
|
||||
* відкривається, одразу повертається оригінальний предмет.
|
||||
*/
|
||||
public class RulesCommand {
|
||||
|
||||
private static final Map<UUID, Long> cooldowns = new HashMap<>();
|
||||
private static final long COOLDOWN_MS = 5000;
|
||||
|
||||
public static void register() {
|
||||
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) ->
|
||||
dispatcher.register(buildCommand())
|
||||
);
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<CommandSourceStack> buildCommand() {
|
||||
return Commands.literal("rules").executes(RulesCommand::execute);
|
||||
}
|
||||
|
||||
private static int execute(CommandContext<CommandSourceStack> context) {
|
||||
CommandSourceStack source = context.getSource();
|
||||
|
||||
if (!(source.getEntity() instanceof ServerPlayer player)) {
|
||||
source.sendFailure(Component.literal("Цю команду можна викликати лише в грі."));
|
||||
return 0;
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
Long lastUsed = cooldowns.get(player.getUUID());
|
||||
if (lastUsed != null && (now - lastUsed) < COOLDOWN_MS) {
|
||||
long remainingMs = COOLDOWN_MS - (now - lastUsed);
|
||||
long secondsLeft = (remainingMs + 999) / 1000;
|
||||
player.sendSystemMessage(Component.literal(
|
||||
"Зачекайте ще " + secondsLeft + " сек. перед повторним використанням /rules."
|
||||
));
|
||||
return 0;
|
||||
}
|
||||
cooldowns.put(player.getUUID(), now);
|
||||
|
||||
RulesData.RulesRoot rules = RulesLoader.get();
|
||||
|
||||
if (rules.sections == null || rules.sections.isEmpty()) {
|
||||
source.sendFailure(Component.literal("Правила ще не налаштовані. Зверніться до адміністрації."));
|
||||
return 0;
|
||||
}
|
||||
|
||||
openBook(player, rules);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void openBook(ServerPlayer player, RulesData.RulesRoot rules) {
|
||||
InteractionHand hand = InteractionHand.MAIN_HAND;
|
||||
ItemStack originalItem = player.getItemInHand(hand).copy();
|
||||
|
||||
ItemStack book = createRuleBook(rules);
|
||||
Localchat.magicModLog.info("Відкриваємо книгу правил для {}", player.getName().getString());
|
||||
|
||||
player.setItemInHand(hand, book);
|
||||
player.containerMenu.sendAllDataToRemote();
|
||||
player.openItemGui(book, hand);
|
||||
player.setItemInHand(hand, originalItem);
|
||||
}
|
||||
|
||||
private static ItemStack createRuleBook(RulesData.RulesRoot rules) {
|
||||
ItemStack book = new ItemStack(Items.WRITTEN_BOOK);
|
||||
|
||||
List<Filterable<Component>> pages = new ArrayList<>();
|
||||
for (RulesData.Section section : rules.sections) {
|
||||
pages.add(Filterable.passThrough(buildPageComponent(section)));
|
||||
}
|
||||
|
||||
WrittenBookContent content = new WrittenBookContent(
|
||||
Filterable.passThrough("Правила серверу"),
|
||||
"Server",
|
||||
0,
|
||||
pages,
|
||||
true
|
||||
);
|
||||
book.set(DataComponents.WRITTEN_BOOK_CONTENT, content);
|
||||
|
||||
return book;
|
||||
}
|
||||
|
||||
private static Component buildPageComponent(RulesData.Section section) {
|
||||
StringBuilder pageText = new StringBuilder();
|
||||
pageText.append("§l§n").append(section.title).append("§r\n\n");
|
||||
|
||||
if (section.entries != null) {
|
||||
for (RulesData.Entry entry : section.entries) {
|
||||
pageText.append(entry.severity.colorCode)
|
||||
.append("[!] §r")
|
||||
.append(entry.number)
|
||||
.append(". ")
|
||||
.append(entry.text)
|
||||
.append("\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
return Component.literal(pageText.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package org.examp.john.rules;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Моделі даних для системи правил сервера.
|
||||
* Структура JSON конфігу:
|
||||
* {
|
||||
* "sections": [
|
||||
* {
|
||||
* "title": "Правила будівництва",
|
||||
* "entries": [
|
||||
* { "number": "1.1", "text": "Заборонено будувати без дозволу...", "severity": "MEDIUM" }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*/
|
||||
public class RulesData {
|
||||
|
||||
/**
|
||||
* Рівень тяжкості порушення. Визначає колір символу-значка в книзі правил
|
||||
* через ванільні коди форматування (§) — книга рендериться повністю клієнтом,
|
||||
* без жодного мода на клієнті.
|
||||
* LIGHT -> зелений (§a)
|
||||
* MEDIUM -> жовтий (§e)
|
||||
* HEAVY -> червоний (§c)
|
||||
*/
|
||||
public enum Severity {
|
||||
LIGHT("§a"),
|
||||
MEDIUM("§e"),
|
||||
HEAVY("§c");
|
||||
|
||||
public final String colorCode;
|
||||
|
||||
Severity(String colorCode) {
|
||||
this.colorCode = colorCode;
|
||||
}
|
||||
|
||||
public static Severity fromString(String raw) {
|
||||
if (raw == null) return LIGHT;
|
||||
try {
|
||||
return Severity.valueOf(raw.trim().toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return LIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Один пункт правила всередині розділу. */
|
||||
public static class Entry {
|
||||
public String number; // напр. "1.1" або "IV"
|
||||
public String text; // текст правила / опис порушення
|
||||
public Severity severity;
|
||||
|
||||
public Entry(String number, String text, Severity severity) {
|
||||
this.number = number;
|
||||
this.text = text;
|
||||
this.severity = severity;
|
||||
}
|
||||
}
|
||||
|
||||
/** Розділ правил (вкладка в GUI), напр. "Правила будівництва". */
|
||||
public static class Section {
|
||||
public String title;
|
||||
public List<Entry> entries;
|
||||
|
||||
public Section(String title, List<Entry> entries) {
|
||||
this.title = title;
|
||||
this.entries = entries;
|
||||
}
|
||||
}
|
||||
|
||||
/** Корінь конфігу — список усіх розділів. */
|
||||
public static class RulesRoot {
|
||||
public List<Section> sections;
|
||||
|
||||
public RulesRoot(List<Section> sections) {
|
||||
this.sections = sections;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package org.examp.john.rules;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import org.examp.john.Localchat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* Завантажує та кешує rules.json з папки config мода.
|
||||
* Файл лежить у config/localchat/rules.json — адміни можуть редагувати
|
||||
* без перезбирання мода, зміни підхоплюються після /rules reload (додамо пізніше)
|
||||
* або перезапуску сервера.
|
||||
*/
|
||||
public class RulesLoader {
|
||||
|
||||
private static final Gson GSON = new GsonBuilder().create();
|
||||
private static final Path CONFIG_PATH = Path.of("config", "localchat", "rules.json");
|
||||
|
||||
private static RulesData.RulesRoot cached;
|
||||
|
||||
/** Повертає закешовані правила, або завантажує їх з диску при першому виклику. */
|
||||
public static RulesData.RulesRoot get() {
|
||||
if (cached == null) {
|
||||
cached = load();
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** Примусово перечитує файл з диску (для майбутньої команди /rules reload). */
|
||||
public static RulesData.RulesRoot reload() {
|
||||
cached = load();
|
||||
return cached;
|
||||
}
|
||||
|
||||
private static RulesData.RulesRoot load() {
|
||||
try {
|
||||
if (!Files.exists(CONFIG_PATH)) {
|
||||
createDefaultConfig();
|
||||
}
|
||||
|
||||
try (Reader reader = Files.newBufferedReader(CONFIG_PATH, StandardCharsets.UTF_8)) {
|
||||
RulesData.RulesRoot root = GSON.fromJson(reader, RulesData.RulesRoot.class);
|
||||
if (root == null || root.sections == null) {
|
||||
Localchat.magicModLog.warn("rules.json порожній або невалідний, використовую пустий список правил");
|
||||
return new RulesData.RulesRoot(Collections.emptyList());
|
||||
}
|
||||
return root;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Localchat.magicModLog.error("Не вдалося прочитати rules.json: {}", e.getMessage());
|
||||
return new RulesData.RulesRoot(Collections.emptyList());
|
||||
} catch (JsonSyntaxException e) {
|
||||
Localchat.magicModLog.error("rules.json містить синтаксичну помилку JSON: {}", e.getMessage());
|
||||
return new RulesData.RulesRoot(Collections.emptyList());
|
||||
}
|
||||
}
|
||||
|
||||
private static void createDefaultConfig() throws IOException {
|
||||
Files.createDirectories(CONFIG_PATH.getParent());
|
||||
|
||||
RulesData.Entry defaultEntry = new RulesData.Entry("1.1", "Пункт 1", RulesData.Severity.LIGHT);
|
||||
RulesData.Section defaultSection = new RulesData.Section("Правила", Collections.singletonList(defaultEntry));
|
||||
RulesData.RulesRoot defaultRoot = new RulesData.RulesRoot(Collections.singletonList(defaultSection));
|
||||
|
||||
try (var writer = Files.newBufferedWriter(CONFIG_PATH, StandardCharsets.UTF_8)) {
|
||||
new GsonBuilder().setPrettyPrinting().create().toJson(defaultRoot, writer);
|
||||
}
|
||||
|
||||
Localchat.magicModLog.info("Створено конфіг за замовчуванням: {}", CONFIG_PATH.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package org.examp.john.stealth;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
/**
|
||||
* Команда /stealth — керує режимом прихованості гравця.
|
||||
*
|
||||
* Підкоманди:
|
||||
* /stealth — переключити стан (on/off)
|
||||
* /stealth on — увімкнути stealth
|
||||
* /stealth off — вимкнути stealth
|
||||
* /stealth info — показати інформацію про команду
|
||||
*/
|
||||
public class StealthCommand {
|
||||
|
||||
public static void register() {
|
||||
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) ->
|
||||
dispatcher.register(buildCommand())
|
||||
);
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<CommandSourceStack> buildCommand() {
|
||||
return Commands.literal("stealth")
|
||||
.executes(StealthCommand::executeToggle)
|
||||
.then(Commands.literal("on").executes(StealthCommand::executeOn))
|
||||
.then(Commands.literal("off").executes(StealthCommand::executeOff))
|
||||
.then(Commands.literal("info").executes(StealthCommand::executeInfo));
|
||||
}
|
||||
|
||||
private static int executeToggle(CommandContext<CommandSourceStack> context) {
|
||||
ServerPlayer player = getPlayer(context);
|
||||
if (player == null) return 0;
|
||||
boolean newState = StealthStorage.toggle(player.getUUID());
|
||||
sendStatus(player, newState);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static int executeOn(CommandContext<CommandSourceStack> context) {
|
||||
ServerPlayer player = getPlayer(context);
|
||||
if (player == null) return 0;
|
||||
StealthStorage.set(player.getUUID(), true);
|
||||
sendStatus(player, true);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static int executeOff(CommandContext<CommandSourceStack> context) {
|
||||
ServerPlayer player = getPlayer(context);
|
||||
if (player == null) return 0;
|
||||
StealthStorage.set(player.getUUID(), false);
|
||||
sendStatus(player, false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static int executeInfo(CommandContext<CommandSourceStack> context) {
|
||||
ServerPlayer player = getPlayer(context);
|
||||
if (player == null) return 0;
|
||||
|
||||
boolean enabled = StealthStorage.isEnabled(player.getUUID());
|
||||
|
||||
player.sendSystemMessage(Component.literal("=== Stealth Mode ===").withStyle(ChatFormatting.GOLD));
|
||||
player.sendSystemMessage(Component.empty());
|
||||
player.sendSystemMessage(Component.literal("Статус: ").append(
|
||||
enabled
|
||||
? Component.literal("УВІМКНЕНО").withStyle(ChatFormatting.GREEN)
|
||||
: Component.literal("ВИМКНЕНО").withStyle(ChatFormatting.RED)
|
||||
));
|
||||
player.sendSystemMessage(Component.empty());
|
||||
|
||||
player.sendSystemMessage(Component.literal("Навіщо це потрібно:").withStyle(ChatFormatting.YELLOW));
|
||||
player.sendSystemMessage(Component.literal(" Локальний чат можна зловживати для пошуку")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" гравців: хтось пише в чат, бігає по карті,")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" і дивиться хто відповів — так можна")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" визначити місцеперебування іншого гравця.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" Stealth прибирає вас з локального чату:")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" ваші повідомлення не бачить ніхто,")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" але ви можете бачити чужі якщо вони поруч.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.empty());
|
||||
|
||||
player.sendSystemMessage(Component.literal("Підкоманди:").withStyle(ChatFormatting.YELLOW));
|
||||
player.sendSystemMessage(Component.literal(" /stealth").withStyle(ChatFormatting.AQUA)
|
||||
.append(Component.literal(" — переключити стан (on/off)").withStyle(ChatFormatting.GRAY)));
|
||||
player.sendSystemMessage(Component.literal(" /stealth on").withStyle(ChatFormatting.AQUA)
|
||||
.append(Component.literal(" — увімкнути stealth").withStyle(ChatFormatting.GRAY)));
|
||||
player.sendSystemMessage(Component.literal(" /stealth off").withStyle(ChatFormatting.AQUA)
|
||||
.append(Component.literal(" — вимкнути stealth").withStyle(ChatFormatting.GRAY)));
|
||||
player.sendSystemMessage(Component.literal(" /stealth info").withStyle(ChatFormatting.AQUA)
|
||||
.append(Component.literal(" — ця інформація").withStyle(ChatFormatting.GRAY)));
|
||||
player.sendSystemMessage(Component.empty());
|
||||
|
||||
player.sendSystemMessage(Component.literal("Як працює:").withStyle(ChatFormatting.YELLOW));
|
||||
player.sendSystemMessage(Component.literal(" Звичайний чат: повідомлення бачать лише")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" ті хто в радіусі 100 блоків.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" Якщо stealth ON: ваші повідомлення")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" не доходять взагалі — ви бачите")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" 'Вас ніхто не почув...' замість цього.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" Глобальний чат (! префікс) працює")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
player.sendSystemMessage(Component.literal(" завжди, навіть з stealth.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void sendStatus(ServerPlayer player, boolean enabled) {
|
||||
if (enabled) {
|
||||
player.sendSystemMessage(Component.literal("Stealth-режим УВІМКНЕНО.")
|
||||
.withStyle(ChatFormatting.GREEN));
|
||||
player.sendSystemMessage(Component.literal("Ваші повідомлення в локальному чаті тепер не доходять.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
} else {
|
||||
player.sendSystemMessage(Component.literal("Stealth-режим ВИМКНЕНО.")
|
||||
.withStyle(ChatFormatting.RED));
|
||||
player.sendSystemMessage(Component.literal("Ваші повідомлення в локальному чаті знову чутні.")
|
||||
.withStyle(ChatFormatting.GRAY));
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerPlayer getPlayer(CommandContext<CommandSourceStack> context) {
|
||||
if (!(context.getSource().getEntity() instanceof ServerPlayer player)) {
|
||||
context.getSource().sendFailure(
|
||||
Component.literal("Цю команду можна викликати лише в грі."));
|
||||
return null;
|
||||
}
|
||||
return player;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package org.examp.john.stealth;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import org.examp.john.Localchat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Зберігає стан stealth-режиму для кожного гравця.
|
||||
* Файл: config/localchat/stealth.json — {"uuid1": true, "uuid2": false, ...}
|
||||
*/
|
||||
public class StealthStorage {
|
||||
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final Path CONFIG_PATH = Path.of("config", "localchat", "stealth.json");
|
||||
|
||||
private static Map<UUID, Boolean> data = new HashMap<>();
|
||||
|
||||
public static void load() {
|
||||
try {
|
||||
if (!Files.exists(CONFIG_PATH)) {
|
||||
data = new HashMap<>();
|
||||
save();
|
||||
return;
|
||||
}
|
||||
try (Reader reader = Files.newBufferedReader(CONFIG_PATH, StandardCharsets.UTF_8)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Boolean> raw = GSON.fromJson(reader, Map.class);
|
||||
data = new HashMap<>();
|
||||
if (raw != null) {
|
||||
for (Map.Entry<String, Boolean> entry : raw.entrySet()) {
|
||||
data.put(UUID.fromString(entry.getKey()), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException | JsonSyntaxException | IllegalArgumentException e) {
|
||||
Localchat.magicModLog.warn("Не вдалося прочитати stealth.json: {}", e.getMessage());
|
||||
data = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isEnabled(UUID uuid) {
|
||||
return data.getOrDefault(uuid, false);
|
||||
}
|
||||
|
||||
public static boolean toggle(UUID uuid) {
|
||||
boolean current = isEnabled(uuid);
|
||||
boolean newValue = !current;
|
||||
data.put(uuid, newValue);
|
||||
save();
|
||||
return newValue;
|
||||
}
|
||||
|
||||
public static void set(UUID uuid, boolean value) {
|
||||
data.put(uuid, value);
|
||||
save();
|
||||
}
|
||||
|
||||
private static void save() {
|
||||
try {
|
||||
Files.createDirectories(CONFIG_PATH.getParent());
|
||||
try (Writer writer = Files.newBufferedWriter(CONFIG_PATH, StandardCharsets.UTF_8)) {
|
||||
Map<String, Boolean> raw = new HashMap<>();
|
||||
for (Map.Entry<UUID, Boolean> entry : data.entrySet()) {
|
||||
raw.put(entry.getKey().toString(), entry.getValue());
|
||||
}
|
||||
GSON.toJson(raw, writer);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Localchat.magicModLog.error("Не вдалося зберегти stealth.json: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,6 @@
|
||||
"fabric-datagen": [
|
||||
"org.examp.john.client.LocalchatDataGenerator"
|
||||
],
|
||||
"client": [
|
||||
"org.examp.john.client.LocalchatClient"
|
||||
],
|
||||
"main": [
|
||||
"org.examp.john.Localchat"
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user