Skip to content

Commit

Permalink
feat: Implement File logger
Browse files Browse the repository at this point in the history
resolves #63
  • Loading branch information
4drian3d committed May 16, 2023
1 parent 3a0dbc8 commit b6fdfc9
Show file tree
Hide file tree
Showing 9 changed files with 177 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public CommandNode<CommandSource> node() {
.suggests((ctx, builder) -> {
playerManager.getPlayers()
.stream()
.limit(configurationContainer.get().getGeneralConfig().tabCompleteLimit())
.limit(configurationContainer.get().tabCompleteLimit())
.forEach((player) -> builder.suggest(
player.username(),
VelocityBrigadierMessage.tooltip(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,8 @@ public static class Syntax implements Warning, Toggleable, Executable {
@Setting(value = "warning-type")
private WarningType warningType = WarningType.MESSAGE;

private Set<String> allowedCommands = Set.of();
@Comment("Allowed syntax command executions")
private Set<String> allowedCommands = Set.of("luckperms");

@Override
public CommandsConfig getCommandsConfig() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ public final class Configuration implements Section {
Check the function of each configuration option at
https://github.com/4drian3d/ChatRegulator/wiki/Configuration""";

@Comment("Format Module")
private Format format = new Format();

@Comment("General Configurations")
private General general = new General();
@Comment("Formatter Module")
private Formatter formatter = new Formatter();

@Comment("CommandSpy configuration")
private CommandSpy commandSpy = new CommandSpy();

@Comment("Settings on the log of alert messages in console or files")
private Log log = new Log();

@Comment("""
Specify in which commands you want the violations to be detected
I recommend you to put chat commands, for example: /tell""")
Expand All @@ -41,24 +41,50 @@ public final class Configuration implements Section {
"reply"
);

public Set<String> getCommandsChecked(){
return this.commandsChecked;
@Comment("Set the maximum time in which a user's violations will be saved after the user leaves your server")
@Setting(value = "delete-users-after")
private long deleteUsersAfter = 30;

@Comment("""
Set the time unit of the delete-users-after setting
Available values: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS""")
@Setting(value = "time-unit")
private TimeUnit unit = TimeUnit.SECONDS;

@Comment("Limit the amount of users showed on autocompletion")
@Setting(value = "tab-complete-limit")
private int limitTabComplete = 40;

public long deleteUsersTime(){
return this.deleteUsersAfter;
}

public TimeUnit unit() {
return this.unit;
}

public int tabCompleteLimit(){
return this.limitTabComplete;
}

public Format getFormatConfig(){
return this.format;
public Set<String> getCommandsChecked(){
return this.commandsChecked;
}

public General getGeneralConfig(){
return this.general;
public Formatter getFormatterConfig(){
return this.formatter;
}

public CommandSpy getCommandSpyConfig(){
return this.commandSpy;
}

public Log getLog() {
return this.log;
}

@ConfigSerializable
public static class Format {
public static class Formatter {
@Comment("Enable Format Module")
private boolean enabled = false;

Expand Down Expand Up @@ -106,31 +132,45 @@ public boolean shouldAnnounce(CommandSource source, String command){
}

@ConfigSerializable
public static class General {
@Comment("Set the maximum time in which a user's violations will be saved after the user leaves your server")
@Setting(value = "delete-users-after")
private long deleteUsersAfter = 30;

@Comment("""
Set the time unit of the delete-users-after setting
Available values: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS""")
@Setting(value = "time-unit")
private TimeUnit unit = TimeUnit.SECONDS;

@Comment("Limit the amount of users showed on autocompletion")
@Setting(value = "tab-complete-limit")
private int limitTabComplete = 40;
public static class Log {
@Comment("Toggle to show in console the alert message in case of check detection")
private boolean warningLog = true;
private File file = new File();

public long deleteUsersTime(){
return this.deleteUsersAfter;
public boolean warningLog() {
return warningLog;
}

public TimeUnit unit() {
return this.unit;
public File getFile() {
return file;
}

public int tabCompleteLimit(){
return this.limitTabComplete;
@ConfigSerializable
public static class File {
@Comment("Sets whether this module will be activated")
private boolean enabled = false;
@Comment("Sets the format of the file in which the log will be written")
private String fileFormat = "'infractions'-dd-MM-yy'.txt'";
@Comment("Sets the log format")
private String logFormat = "[<time>] <message>";
@Comment("Sets the time format")
private String timeFormat = "HH:mm:ss";

public boolean isEnabled() {
return enabled;
}

public String getFileFormat() {
return fileFormat;
}

public String getLogFormat() {
return logFormat;
}

public String getTimeFormat() {
return timeFormat;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package io.github._4drian3d.chatregulator.plugin.impl;

import com.google.common.base.Suppliers;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import io.github._4drian3d.chatregulator.plugin.config.Configuration;
import io.github._4drian3d.chatregulator.plugin.config.ConfigurationContainer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.slf4j.Logger;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import static java.nio.file.StandardOpenOption.*;

@Singleton
public final class FileLogger {
private final Supplier<Path> file;
private final Logger logger;
private final ConfigurationContainer<Configuration> configurationContainer;

@Inject
public FileLogger(
ConfigurationContainer<Configuration> configurationContainer,
@DataDirectory Path path,
Logger logger
) {
this.logger = logger;
this.configurationContainer = configurationContainer;
this.file = Suppliers.memoizeWithExpiration(() -> {
Configuration.Log.File config = configurationContainer.get().getLog().getFile();
final Path directory = path.resolve("log");
createDirectory(directory);
final String filePath = DateTimeFormatter.ofPattern(config.getFileFormat()).format(LocalDateTime.now());
return directory.resolve(filePath);
},10, TimeUnit.MINUTES);
}

public void log(String string) {
if (!configurationContainer.get().getLog().getFile().isEnabled()) {
return;
}
final Path path = file.get();
try (final BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, CREATE, WRITE, APPEND)) {
final var fileConfig = configurationContainer.get().getLog().getFile();
final String message = fileConfig.getLogFormat()
.replace("time", DateTimeFormatter.ofPattern(fileConfig.getTimeFormat()).format(LocalDateTime.now()))
.replace("message", string);
writer.write(message);
writer.newLine();
} catch (IOException e) {
logger.warn("Cannot log to file", e);
}
}

private static final PlainTextComponentSerializer SERIALIZER = PlainTextComponentSerializer.plainText();

public void log(Component component) {
log(SERIALIZER.serialize(component));
}

private void createDirectory(Path directory) {
if (Files.notExists(directory)) {
try {
Files.createDirectory(directory);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import io.github._4drian3d.chatregulator.api.enums.SourceType;
import io.github._4drian3d.chatregulator.api.result.CheckResult;
import io.github._4drian3d.chatregulator.plugin.config.Checks;
import io.github._4drian3d.chatregulator.plugin.config.Configuration;
import io.github._4drian3d.chatregulator.plugin.config.ConfigurationContainer;
import io.github._4drian3d.chatregulator.plugin.config.Messages;
import io.github._4drian3d.chatregulator.plugin.placeholders.PlayerResolver;
Expand Down Expand Up @@ -40,13 +41,17 @@ public final class InfractionPlayerImpl implements InfractionPlayer {
@Inject
private Logger logger;
@Inject
private ConfigurationContainer<Checks> configurationContainer;
private ConfigurationContainer<Checks> checksContainer;
@Inject
private ConfigurationContainer<Configuration> configurationContainer;
@Inject
private ConfigurationContainer<Messages> messagesContainer;
@Inject
private IFormatter formatter;
@Inject
private RegulatorCommandSource regulatorSource;
@Inject
private FileLogger fileLogger;
private final StringChainImpl commandChain = new StringChainImpl();
private final StringChainImpl chatChain = new StringChainImpl();
private final InfractionCount infractionCount = new InfractionCount();
Expand Down Expand Up @@ -128,7 +133,7 @@ public String toString() {
}

public boolean isAllowed(InfractionType type) {
return configurationContainer.get().isEnabled(type) && !type.getBypassPermission().test(getPlayer());
return checksContainer.get().isEnabled(type) && !type.getBypassPermission().test(getPlayer());
}

private void sendWarningMessage(CheckResult result, InfractionType type) {
Expand All @@ -141,7 +146,7 @@ private void sendWarningMessage(CheckResult result, InfractionType type) {
}

final TagResolver resolver = builder.build();
final Checks.Warning configuration = configurationContainer.get().getWarning(type);
final Checks.Warning configuration = checksContainer.get().getWarning(type);

switch (configuration.getWarningType()) {
case TITLE -> {
Expand Down Expand Up @@ -192,7 +197,13 @@ private void sendAlertMessage(final InfractionType type, final CheckResult resul
}
}

proxyServer.getConsoleCommandSource().sendMessage(message);
if (configurationContainer.get().getLog().warningLog()) {
regulatorSource.sendMessage(message);
}

if (fileLogger != null) {
fileLogger.log(message);
}
}

public @NotNull TagResolver getPlaceholders() {
Expand Down Expand Up @@ -238,7 +249,7 @@ private void executeCommands(final @NotNull InfractionType type) {
return;
}

final Checks.CommandsConfig config = configurationContainer.get().getExecutable(type).getCommandsConfig();
final Checks.CommandsConfig config = checksContainer.get().getExecutable(type).getCommandsConfig();
if (config.executeCommand() && getInfractions().getCount(type) % config.violationsRequired() == 0) {
final String serverName = player.getCurrentServer().map(sv -> sv.getServerInfo().getName()).orElse("");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public final class ChatListener implements RegulatorExecutor<PlayerChatEvent> {
}

final Configuration configuration = configurationContainer.get();
if (configuration.getFormatConfig().enabled()) {
if (configuration.getFormatterConfig().enabled()) {
finalMessage = Replacer.applyFormat(finalMessage, configuration);
event.setResult(ChatResult.message(finalMessage));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public final class LeaveListener implements RegulatorExecutor<DisconnectEvent> {
playerManager.removePlayer(uuid);
}
}).delay(
configuration.getGeneralConfig().deleteUsersTime(),
configuration.getGeneralConfig().unit()
configuration.deleteUsersTime(),
configuration.unit()
).schedule();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public final class Replacer {
}

public static @NotNull String firstLetterUppercase(@NotNull final String string, Configuration config) {
if (!config.getFormatConfig().setFirstLetterUppercase()) return string;
if (!config.getFormatterConfig().setFirstLetterUppercase()) return string;
return firstLetterUppercase(string);
}

Expand All @@ -51,7 +51,7 @@ public final class Replacer {
}

public static String addFinalDot(final String string, Configuration config) {
return config.getFormatConfig().setFinalDot()
return config.getFormatterConfig().setFinalDot()
? addFinalDot(string)
: string;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ void configValues(@TempDir Path path){
Configuration config = ConfigurationContainer.load(LoggerFactory.getLogger(ConfigurationTest.class), path, Configuration.class, "config").get();

assertTrue(checks.getCommandBlacklistConfig().enabled());
assertFalse(config.getFormatConfig().enabled());
assertFalse(config.getFormatterConfig().enabled());

assertEquals(2, checks.getFloodConfig().getCommandsConfig().violationsRequired());
assertEquals(2, checks.getUnicodeConfig().getCommandsConfig().violationsRequired());
Expand Down

0 comments on commit b6fdfc9

Please sign in to comment.