Compare commits

..

No commits in common. "b78e25ceaca91b3d23b87b48b59386966be2546d" and "2ccaa6927cda68ce2b3c2d3fe3d2ebaabf996471" have entirely different histories.

9 changed files with 24 additions and 126 deletions

View File

@ -4,37 +4,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/). The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/).
## [0.1.4] - 2024-10-28
### Added
- **Console Error Logging**:
- Implemented comprehensive error logging to the console.
- Facilitates easier debugging and monitoring by providing detailed error messages during runtime.
- **Configurable Message Text**:
- Introduced the ability to customize message texts via configuration.
- Users can now modify the default messages to better fit their server's communication style.
### Fixed
- **Tick Timeout Error**:
- Resolved the tick timeout issue that caused the server to lag or crash under high load.
- Enhanced the stability and performance of the mod by ensuring smoother execution of tick cycles.
### Changed
- **Renamed Command Class**:
- Renamed the command class from `ChatitCommand.java` to `ChatITCommand.java`.
- Improves consistency and readability within the codebase, aligning with naming conventions.
### Summary of Changes
- **Enhanced Debugging**: With the addition of console error logs, developers can now trace and fix issues more efficiently.
- **Increased Configurability**: Allowing message texts to be configured provides greater flexibility for server administrators.
- **Improved Stability**: Fixing the tick timeout error ensures that the mod runs more reliably, even under heavy usage.
- **Codebase Refinement**: Renaming the command class contributes to a more organized and maintainable code structure.
## [0.1.3] - 2024-10-21 ## [0.1.3] - 2024-10-21
### Added ### Added

View File

@ -4,37 +4,6 @@
Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.0.0/), и этот проект придерживается [Семантического Версионирования](https://semver.org/lang/ru/). Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.0.0/), и этот проект придерживается [Семантического Версионирования](https://semver.org/lang/ru/).
## [0.1.4] - 2024-10-28
### Добавлено
- **Логирование ошибок в консоль**:
- Реализовано комплексное логирование ошибок в консоль.
- Облегчает отладку и мониторинг, предоставляя подробные сообщения об ошибках во время выполнения.
- **Настраиваемый текст сообщений**:
- Введена возможность настройки текста сообщений через конфигурацию.
- Пользователи теперь могут изменять стандартные сообщения, чтобы они лучше соответствовали стилю общения сервера.
### Исправлено
- **Ошибка таймаута тика**:
- Исправлена проблема с таймаутом тика, которая вызывала зависание или сбой сервера при высокой нагрузке.
- Повышена стабильность и производительность мода за счет обеспечения более плавного выполнения циклов тиков.
### Изменено
- **Переименование класса команды**:
- Переименован класс команды с `ChatitCommand.java` на `ChatITCommand.java`.
- Улучшает согласованность и читаемость в кодовой базе, соответствуя стандартам именования.
### Сводка изменений
- **Улучшенная отладка**: С добавлением логирования ошибок в консоль разработчики теперь могут более эффективно отслеживать и исправлять проблемы.
- **Повышенная настраиваемость**: Возможность настройки текста сообщений предоставляет большую гибкость для администраторов серверов.
- **Повышенная стабильность**: Исправление ошибки таймаута тика обеспечивает более надежную работу мода, даже при высокой нагрузке.
- **Улучшение кодовой базы**: Переименование класса команды способствует более организованной и поддерживаемой структуре кода.
## [0.1.3] - 2024-10-21 ## [0.1.3] - 2024-10-21
### Добавлено ### Добавлено

View File

@ -38,7 +38,7 @@ mod_name=ChatIT
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved mod_license=All Rights Reserved
# The mod version. See https://semver.org/ # The mod version. See https://semver.org/
mod_version=0.1.4-BETA mod_version=0.1.3-BETA
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. # The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources. # This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html # See https://maven.apache.org/guides/mini/guide-naming-conventions.html

View File

@ -1,17 +1,17 @@
package org.itqop.chatit; package org.itqop.chatit;
import com.mojang.logging.LogUtils;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.config.ModConfig;
import org.itqop.chatit.commands.ChatITCommand; import org.itqop.chatit.commands.ChatitCommand;
import org.itqop.chatit.handlers.ChatEventHandler; import org.itqop.chatit.handlers.ChatEventHandler;
import org.itqop.chatit.utils.Config; import org.itqop.chatit.utils.Config;
import org.itqop.chatit.utils.PlayerConfigManager; import org.itqop.chatit.utils.PlayerConfigManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
@Mod(ChatIT.MODID) @Mod(ChatIT.MODID)
public class ChatIT { public class ChatIT {
@ -22,7 +22,7 @@ public class ChatIT {
public ChatIT() { public ChatIT() {
MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(this);
MinecraftForge.EVENT_BUS.register(ChatEventHandler.class); MinecraftForge.EVENT_BUS.register(ChatEventHandler.class);
MinecraftForge.EVENT_BUS.register(ChatITCommand.class); MinecraftForge.EVENT_BUS.register(ChatitCommand.class);
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.COMMON_CONFIG); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.COMMON_CONFIG);
} }

View File

@ -11,7 +11,7 @@ import net.minecraftforge.fml.common.Mod;
import org.itqop.chatit.utils.PlayerConfigManager; import org.itqop.chatit.utils.PlayerConfigManager;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class ChatITCommand { public class ChatitCommand {
@SubscribeEvent @SubscribeEvent
public static void onRegisterCommands(RegisterCommandsEvent event) { public static void onRegisterCommands(RegisterCommandsEvent event) {

View File

@ -11,20 +11,15 @@ import net.minecraft.ChatFormatting;
import org.itqop.chatit.utils.Config; import org.itqop.chatit.utils.Config;
import org.itqop.chatit.utils.PlayerConfigManager; import org.itqop.chatit.utils.PlayerConfigManager;
import org.itqop.chatit.utils.ProfanityChecker; import org.itqop.chatit.utils.ProfanityChecker;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class ChatEventHandler { public class ChatEventHandler {
private static final Logger LOGGER = LogUtils.getLogger();
@SubscribeEvent @SubscribeEvent
public static void onServerChat(ServerChatEvent event) { public static void onServerChat(ServerChatEvent event) {
ServerPlayer sender = event.getPlayer(); ServerPlayer sender = event.getPlayer();
MinecraftServer server = sender.getServer(); MinecraftServer server = sender.getServer();
String originalMessage = event.getMessage().getString(); String originalMessage = event.getMessage().getString();
@ -42,33 +37,32 @@ public class ChatEventHandler {
future.thenAccept(profanityScore -> { future.thenAccept(profanityScore -> {
if (server != null) { if (server != null) {
server.execute(() -> { server.execute(() -> {
double threshold = Config.profanityThreshold; double threshold = Config.profanityThreshold; // Получаем порог из конфигурации
if (profanityScore > threshold && !PlayerConfigManager.hasAdultContentEnabled(sender)) { if (profanityScore > threshold && !PlayerConfigManager.hasAdultContentEnabled(sender)) {
MutableComponent adultComponent = createAdultMessage(sender, message); MutableComponent errorComponent = createErrorMessage(sender, message);
sender.sendSystemMessage(adultComponent); sender.sendSystemMessage(errorComponent);
} else { } else {
boolean messageSent = false;
for (ServerPlayer receiver : server.getPlayerList().getPlayers()) { for (ServerPlayer receiver : server.getPlayerList().getPlayers()) {
PlayerConfigManager.ensurePlayerExists(receiver); PlayerConfigManager.ensurePlayerExists(receiver);
if (profanityScore > threshold && !PlayerConfigManager.hasAdultContentEnabled(receiver)) { if (profanityScore > threshold && !PlayerConfigManager.hasAdultContentEnabled(receiver)) {
continue; continue;
} }
if (((receiver.getCommandSenderWorld() == sender.getCommandSenderWorld() && receiver.position().distanceTo(sender.position()) <= 50) && (sender != receiver)) || isGlobal) {
receiver.sendSystemMessage(chatComponent); try (var senderLevel = sender.level(); var receiverLevel = receiver.level()) {
messageSent = true; if (isGlobal || (receiverLevel == senderLevel && receiver.position().distanceTo(sender.position()) <= 50)) {
receiver.sendSystemMessage(chatComponent);
}
} catch (Exception e) {
e.printStackTrace();
} }
} }
if (!messageSent) {
MutableComponent errorComponent = createErrorMessage(sender, Config.messageLocal);
sender.sendSystemMessage(errorComponent);
}
} }
}); });
} }
}).exceptionally(ex -> { }).exceptionally(ex -> {
LOGGER.error(ex.toString()); ex.printStackTrace();
if (server != null) { if (server != null) {
server.execute(() -> { server.execute(() -> {
MutableComponent errorComponent = createErrorMessage(sender, message); MutableComponent errorComponent = createErrorMessage(sender, message);
@ -87,22 +81,10 @@ public class ChatEventHandler {
MutableComponent prefixComponent = openBracket.append(errorText).append(closeBracket); MutableComponent prefixComponent = openBracket.append(errorText).append(closeBracket);
Component messageComponent = Component.literal(": " + message).withStyle(ChatFormatting.RED);; Component playerName = Component.literal(player.getName().getString());
Component messageComponent = Component.literal(": " + message);
return prefixComponent.append(messageComponent); return prefixComponent.append(playerName).append(messageComponent);
}
private static MutableComponent createAdultMessage(ServerPlayer player, String message) {
MutableComponent openBracket = Component.literal("[");
MutableComponent errorText = Component.literal("ADULT")
.withStyle(ChatFormatting.RED);
MutableComponent closeBracket = Component.literal("] ");
MutableComponent prefixComponent = openBracket.append(errorText).append(closeBracket);
Component errorMessage = Component.literal(Config.messageAdult).withStyle(ChatFormatting.RED);
return prefixComponent.append(errorMessage);
} }
private static MutableComponent createChatMessage(ServerPlayer player, String message, boolean isGlobal) { private static MutableComponent createChatMessage(ServerPlayer player, String message, boolean isGlobal) {

View File

@ -16,10 +16,8 @@ public class Config {
public static ForgeConfigSpec.ConfigValue<String> HOST_API; public static ForgeConfigSpec.ConfigValue<String> HOST_API;
public static ForgeConfigSpec.BooleanValue DEFAULT_ADULT; public static ForgeConfigSpec.BooleanValue DEFAULT_ADULT;
public static ForgeConfigSpec.BooleanValue USE_REGEX; public static ForgeConfigSpec.BooleanValue USE_REGEX;
public static ForgeConfigSpec.DoubleValue PROFANITY_THRESHOLD; public static ForgeConfigSpec.DoubleValue PROFANITY_THRESHOLD; // Новое
public static ForgeConfigSpec.ConfigValue<String> PROFANITY_REGEX; public static ForgeConfigSpec.ConfigValue<String> PROFANITY_REGEX; // Новое
public static ForgeConfigSpec.ConfigValue<String> MESSAGE_ADULT;
public static ForgeConfigSpec.ConfigValue<String> MESSAGE_LOCAL;
static { static {
BUILDER.comment("Настройки ChatIT"); BUILDER.comment("Настройки ChatIT");
@ -44,14 +42,6 @@ public class Config {
.comment("Регулярное выражение для проверки мата") .comment("Регулярное выражение для проверки мата")
.define("profanity_regex", "(?iu)\\b(?:(?:(?:у|[нз]а|(?:хитро|не)?вз?[ыьъ]|с[ьъ]|(?:и|ра)[зс]ъ?|(?:.\\B)+?[оаеи-])-?)?(?:[её](?:б(?!о[рй]|рач)|п[уа](?:ц|тс))|и[пб][ае][тцд][ьъ]).*?|(?:(?:н[иеа]|(?:ра|и)[зс]|[зд]?[ао](?:т|дн[оа])?|с(?:м[еи])?|а[пб]ч|в[ъы]?|пр[еи])-?)?ху(?:[яйиеёю]|л+и(?!ган)).*?|бл(?:[эя]|еа?)(?:[дт][ьъ]?)?|\\S*?(?:п(?:[иеё]зд|ид[аое]?р|ед(?:р(?!о)|[аое]р|ик)|охую)|бля(?:[дбц]|тс)|[ое]ху[яйиеё]|хуйн).*?|(?:о[тб]?|про|на|вы)?м(?:анд(?:[ауеыи](?:л(?:и[сзщ])?[ауеиы])?|ой|[ао]в.*?|юк(?:ов|[ауи])?|е[нт]ь|ища)|уд(?:[яаиое].+?|е?н(?:[ьюия]|ей))|[ао]л[ао]ф[ьъ](?:[яиюе]|[еёо]й))|елд[ауые].*?|ля[тд]ь|(?:[нз]а|по)х)\\b"); // Дефолтное регулярное выражение .define("profanity_regex", "(?iu)\\b(?:(?:(?:у|[нз]а|(?:хитро|не)?вз?[ыьъ]|с[ьъ]|(?:и|ра)[зс]ъ?|(?:.\\B)+?[оаеи-])-?)?(?:[её](?:б(?!о[рй]|рач)|п[уа](?:ц|тс))|и[пб][ае][тцд][ьъ]).*?|(?:(?:н[иеа]|(?:ра|и)[зс]|[зд]?[ао](?:т|дн[оа])?|с(?:м[еи])?|а[пб]ч|в[ъы]?|пр[еи])-?)?ху(?:[яйиеёю]|л+и(?!ган)).*?|бл(?:[эя]|еа?)(?:[дт][ьъ]?)?|\\S*?(?:п(?:[иеё]зд|ид[аое]?р|ед(?:р(?!о)|[аое]р|ик)|охую)|бля(?:[дбц]|тс)|[ое]ху[яйиеё]|хуйн).*?|(?:о[тб]?|про|на|вы)?м(?:анд(?:[ауеыи](?:л(?:и[сзщ])?[ауеиы])?|ой|[ао]в.*?|юк(?:ов|[ауи])?|е[нт]ь|ища)|уд(?:[яаиое].+?|е?н(?:[ьюия]|ей))|[ао]л[ао]ф[ьъ](?:[яиюе]|[еёо]й))|елд[ауые].*?|ля[тд]ь|(?:[нз]а|по)х)\\b"); // Дефолтное регулярное выражение
MESSAGE_ADULT = BUILDER
.comment("Сообщение запрета на маты.")
.define("message_adult", "Вы пытаетесь использовать ненормативную лексику в своем сообщении.");
MESSAGE_LOCAL = BUILDER
.comment("Сообщение предупреждения о том, что никого рядом нет")
.define("message_local", "Вас никто не услышал, поставьте ! перед сообщением.");
COMMON_CONFIG = BUILDER.build(); COMMON_CONFIG = BUILDER.build();
} }
@ -60,8 +50,6 @@ public class Config {
public static boolean useRegex; public static boolean useRegex;
public static double profanityThreshold; public static double profanityThreshold;
public static String profanityRegex; public static String profanityRegex;
public static String messageAdult;
public static String messageLocal;
@SubscribeEvent @SubscribeEvent
public static void onLoad(final ModConfigEvent event) { public static void onLoad(final ModConfigEvent event) {
@ -70,7 +58,5 @@ public class Config {
useRegex = USE_REGEX.get(); useRegex = USE_REGEX.get();
profanityThreshold = PROFANITY_THRESHOLD.get(); profanityThreshold = PROFANITY_THRESHOLD.get();
profanityRegex = PROFANITY_REGEX.get(); profanityRegex = PROFANITY_REGEX.get();
messageAdult = MESSAGE_ADULT.get();
messageLocal = MESSAGE_LOCAL.get();
} }
} }

View File

@ -12,15 +12,11 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
public class PlayerConfigManager { public class PlayerConfigManager {
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
private static final File CONFIG_FILE = new File("config/chatit_player_settings.json"); private static final File CONFIG_FILE = new File("config/chatit_player_settings.json");
private static final Type CONFIG_TYPE = new TypeToken<Map<UUID, Boolean>>() {}.getType(); private static final Type CONFIG_TYPE = new TypeToken<Map<UUID, Boolean>>() {}.getType();
private static final Logger LOGGER = LogUtils.getLogger();
private static Map<UUID, Boolean> playerSettings = new HashMap<>(); private static Map<UUID, Boolean> playerSettings = new HashMap<>();
@ -29,7 +25,7 @@ public class PlayerConfigManager {
try (FileReader reader = new FileReader(CONFIG_FILE)) { try (FileReader reader = new FileReader(CONFIG_FILE)) {
playerSettings = GSON.fromJson(reader, CONFIG_TYPE); playerSettings = GSON.fromJson(reader, CONFIG_TYPE);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.toString()); e.printStackTrace();
} }
} }
} }
@ -38,7 +34,7 @@ public class PlayerConfigManager {
try (FileWriter writer = new FileWriter(CONFIG_FILE)) { try (FileWriter writer = new FileWriter(CONFIG_FILE)) {
GSON.toJson(playerSettings, writer); GSON.toJson(playerSettings, writer);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.toString()); e.printStackTrace();
} }
} }

View File

@ -8,16 +8,12 @@ import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
import com.google.gson.Gson; import com.google.gson.Gson;
public class ProfanityChecker { public class ProfanityChecker {
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
private static final HttpClient CLIENT = HttpClient.newHttpClient(); private static final HttpClient CLIENT = HttpClient.newHttpClient();
private static final Logger LOGGER = LogUtils.getLogger();
private static Pattern profanityPattern = null; private static Pattern profanityPattern = null;
@ -53,7 +49,7 @@ public class ProfanityChecker {
return Double.parseDouble(responseBody); return Double.parseDouble(responseBody);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.toString()); e.printStackTrace();
if (Config.useRegex) { if (Config.useRegex) {
if (containsProfanity(message)) { if (containsProfanity(message)) {
return 1.0; return 1.0;