Author SHA1 Message Date
auto 42736bd566 Update APRIL_FOOLS_RESET string in Config class
APRIL_FOOLS_RESET string in Config class has been updated from "reverse" to "esrever". This change updates the behavior of the April Fools feature in the chat application.
2024-03-31 14:53:36 +02:00
auto 157edbd6b6 Merge branch 'main' into april_fools 2024-03-31 13:37:42 +02:00
auto 4af85d0e79 Add option to disable chat filters in private channels
A constructor parameter and corresponding field 'disableInPrivate' have been added to the ChatFilter class. This handles disabling specific chat filters in private channels. The necessary checks have been implemented in RegexManager. The configuration for each filter is also updated in RegexConfig to incorporate this new functionality.
2024-03-31 13:37:05 +02:00
auto a7e029b0a1 Refactor April 1st date check in ChatListener
Removed the more complex date logic used to check for April 1st in the ChatListener class. This check checked if it was April 1st in any timezone. Replaced it with a simpler check using LocalDate's methods for month and day comparison. This only checks if it's April 1st in UTC. This aims to enhance code readability and simplify date handling.
2024-03-31 10:56:21 +02:00
auto ab98222f06 Refactor April 1st check in ChatListener class
A new method, `isWithinApril1st`, is introduced to simplify April 1st date check logic in the `ChatListener` class. This new method calculates the start and end of April 1st for all timezones in UTC and determines if the current time falls within this range.
2024-03-24 17:24:24 +01:00
auto ad91cda0c0 Add method to remove string at start
A new method `removeStringAtStart` has been added to the `ModifiableString` class. It replaces the starting string in a given text. Also, a condition has been modified in the `ChatListener` class to invoke this new method when the input string starts with the `APRIL_FOOLS_RESET` string. Additional unit tests were created to validate these changes.
2024-03-24 17:12:55 +01:00
auto 9270423928 Add reverse chat feature for April Fools' and corresponding tests
This commit includes a new feature that reverses the text speech of chat users on April 1st as an April Fools' prank. It also includes a reset option, configurable via a new parameter in the configuration file. Furthermore, it provides tests for the reverse string functionality, ensuring that it works correctly, even with complex strings that include tags.
2024-03-24 16:58:09 +01:00
auto 034de90062 Implement evidence for automatic ban for 'punish' filter violations
When a user who violate the 'punish' filter rules is automatically banned, there will now be a post about it in the #evidence channel.
2024-03-02 20:41:59 +01:00
auto bd8fa02f1e Add 'punish' filter and automatic banning functionality
Extended the RegexManager filterText method to include a 'punish' case that triggers an automatic ban for users who violate the filter. This commit also updates the PluginMessageListener to handle 'punish' commands, thus completing the execution of an auto-ban function.
2024-03-02 19:18:13 +01:00
17 changed files with 224 additions and 228 deletions
+7
View File
@@ -8,6 +8,9 @@ dependencies {
} }
compileOnly("org.spongepowered:configurate-yaml:4.1.2") // Configurate compileOnly("org.spongepowered:configurate-yaml:4.1.2") // Configurate
compileOnly("net.luckperms:api:5.3") // Luckperms compileOnly("net.luckperms:api:5.3") // Luckperms
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.0")
testImplementation("com.alttd:Galaxy-API:1.19.2-R0.1-SNAPSHOT")
} }
publishing { publishing {
@@ -25,3 +28,7 @@ publishing {
} }
} }
} }
tasks.test {
useJUnitPlatform()
}
@@ -543,4 +543,9 @@ public final class Config {
NICK_ALLOWED_COLOR_CODESLIST = getList("nicknames.allowed-color-codes", List.of("&0", "&1", "&2", "&3", "&4", "&5", "&6", "&7", "&8", "&9", "&a", "&b", "&c", "&d", "&e", "&f", "&r")); NICK_ALLOWED_COLOR_CODESLIST = getList("nicknames.allowed-color-codes", List.of("&0", "&1", "&2", "&3", "&4", "&5", "&6", "&7", "&8", "&9", "&a", "&b", "&c", "&d", "&e", "&f", "&r"));
NICK_CURRENT = getString("nicknames.messages.nick-current", NICK_CURRENT); NICK_CURRENT = getString("nicknames.messages.nick-current", NICK_CURRENT);
} }
public static String APRIL_FOOLS_RESET = "esrever";
private static void aprilFools() {
APRIL_FOOLS_RESET = getString("april-fools.reset", APRIL_FOOLS_RESET);
}
} }
@@ -178,13 +178,18 @@ public final class RegexConfig {
String regex = entry.getValue().node("regex").getString(); String regex = entry.getValue().node("regex").getString();
String replacement = entry.getValue().node("replacement").getString(); String replacement = entry.getValue().node("replacement").getString();
List<String> exclusions = entry.getValue().node("exclusions").getList(io.leangen.geantyref.TypeToken.get(String.class), new ArrayList<>()); List<String> exclusions = entry.getValue().node("exclusions").getList(io.leangen.geantyref.TypeToken.get(String.class), new ArrayList<>());
boolean disableInPrivate = false;
ConfigurationNode node = entry.getValue().node("disable-in-private");
if (node != null) {
disableInPrivate = node.getBoolean();
}
if (type == null || type.isEmpty() || regex == null || regex.isEmpty()) { if (type == null || type.isEmpty() || regex == null || regex.isEmpty()) {
ALogger.warn("Filter: " + name + " was set up incorrectly"); ALogger.warn("Filter: " + name + " was set up incorrectly");
} else { } else {
if (replacement == null || replacement.isEmpty()) { if (replacement == null || replacement.isEmpty()) {
replacement = name; replacement = name;
} }
ChatFilter chatFilter = new ChatFilter(name, type, regex, replacement, exclusions); ChatFilter chatFilter = new ChatFilter(name, type, regex, replacement, exclusions, disableInPrivate);
RegexManager.addFilter(chatFilter); RegexManager.addFilter(chatFilter);
} }
} catch(SerializationException ex) { } catch(SerializationException ex) {
@@ -8,10 +8,13 @@ import com.alttd.chat.objects.ModifiableString;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
import net.luckperms.api.cacheddata.CachedPermissionData; import net.luckperms.api.cacheddata.CachedPermissionData;
import net.luckperms.api.model.user.User; import net.luckperms.api.model.user.User;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class RegexManager { public class RegexManager {
@@ -43,17 +46,24 @@ public class RegexManager {
} }
public static boolean filterText(String playerName, UUID uuid, ModifiableString modifiableString, String channel) { // TODO loop all objects in the list and check if they violate based on the MATCHER public static boolean filterText(String playerName, UUID uuid, ModifiableString modifiableString, String channel) { // TODO loop all objects in the list and check if they violate based on the MATCHER
return filterText(playerName, uuid, modifiableString, true, channel); return filterText(playerName, uuid, modifiableString, true, channel, null);
} }
public static boolean filterText(String playerName, UUID uuid, ModifiableString modifiableString, boolean matcher, String channel) { public static boolean filterText(String playerName, UUID uuid, ModifiableString modifiableString, boolean matcher, String channel) {
return filterText(playerName, uuid, modifiableString, matcher, channel, null);
}
public static boolean filterText(String playerName, UUID uuid, ModifiableString modifiableString, boolean matcher, String channel, Consumer<FilterType> filterAction) {
User user = ChatAPI.get().getLuckPerms().getUserManager().getUser(uuid); User user = ChatAPI.get().getLuckPerms().getUserManager().getUser(uuid);
if (user == null) { if (user == null) {
ALogger.warn("Tried to check chat filters for a user who doesn't exist in LuckPerms"); ALogger.warn("Tried to check chat filters for a user who doesn't exist in LuckPerms");
return false; return false;
} }
CachedPermissionData permissionData = user.getCachedData().getPermissionData(); CachedPermissionData permissionData = user.getCachedData().getPermissionData();
boolean isPrivate = channel.equals("party");
for(ChatFilter chatFilter : chatFilters) { for(ChatFilter chatFilter : chatFilters) {
if (isPrivate && chatFilter.isDisabledInPrivate())
continue;
switch (chatFilter.getType()) { switch (chatFilter.getType()) {
case CHAT: case CHAT:
break; break;
@@ -74,6 +84,25 @@ public class RegexManager {
chatFilter.replaceMatcher(modifiableString); chatFilter.replaceMatcher(modifiableString);
} }
break; break;
case PUNISH:
if (permissionData.checkPermission("chat.bypass-punish").asBoolean())
break;
if (chatFilter.matches(modifiableString)) {
ALogger.info(playerName + " triggered the punish filter for " + chatFilter.getName()
+ " with: " + modifiableString.string() + ".");
if (filterAction == null){
ALogger.info("No filterAction was provided, not doing anything");
return false;
}
Player player = Bukkit.getPlayer(uuid);
if (player == null) {
ALogger.warn("Tried to punish a player who triggered the filter, but the player is offline.");
return false;
}
filterAction.accept(FilterType.PUNISH);
return false;
}
} }
} }
return true; return true;
@@ -17,14 +17,16 @@ public class ChatFilter {
private final Pattern pattern; private final Pattern pattern;
private final String replacement; private final String replacement;
private final List<String> exclusions; private final List<String> exclusions;
private final boolean disableInPrivate;
public ChatFilter(String name, String type, String regex, String replacement, List<String> exclusions) { public ChatFilter(String name, String type, String regex, String replacement, List<String> exclusions, boolean disableInPrivate) {
this.name = name; this.name = name;
this.filterType = FilterType.getType(type); this.filterType = FilterType.getType(type);
this.regex = regex; this.regex = regex;
this.pattern = Pattern.compile(getRegex(), Pattern.CASE_INSENSITIVE); this.pattern = Pattern.compile(getRegex(), Pattern.CASE_INSENSITIVE);
this.replacement = replacement; this.replacement = replacement;
this.exclusions = exclusions; this.exclusions = exclusions;
this.disableInPrivate = disableInPrivate;
} }
public String getName() { public String getName() {
@@ -47,6 +49,10 @@ public class ChatFilter {
return this.exclusions; return this.exclusions;
} }
public boolean isDisabledInPrivate() {
return disableInPrivate;
}
public boolean matches(ModifiableString filterableString) { public boolean matches(ModifiableString filterableString) {
String input = filterableString.string(); String input = filterableString.string();
Matcher matcher = pattern.matcher(input); Matcher matcher = pattern.matcher(input);
@@ -5,7 +5,8 @@ public enum FilterType {
EMOTE("emote"), EMOTE("emote"),
CHAT("chat"), CHAT("chat"),
REPLACEMATCHER("replacematcher"), REPLACEMATCHER("replacematcher"),
BLOCK("block"); BLOCK("block"),
PUNISH("punish");
private final String name; private final String name;
@@ -1,12 +1,14 @@
package com.alttd.chat.objects; package com.alttd.chat.objects;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.intellij.lang.annotations.RegExp;
import javax.annotation.RegEx; import java.util.Collections;
import java.util.regex.Pattern; import java.util.List;
import java.util.stream.Collectors;
public class ModifiableString { public class ModifiableString {
private Component text; private Component text;
@@ -30,4 +32,37 @@ public class ModifiableString {
public Component component() { public Component component() {
return text; return text;
} }
public void reverse() {
text = reverseComponent(text);
}
public Component reverseComponent(Component component) {
if (!(component instanceof TextComponent textComponent)) {
return Component.text("")
.append(Component.join(JoinConfiguration.noSeparators(), reverseChildren(component.children())));
}
String content = textComponent.content();
String reversedContent = new StringBuilder(content).reverse().toString();
List<Component> reversedChildren = reverseChildren(component.children());
return Component.text("")
.append(Component.join(JoinConfiguration.noSeparators(), reversedChildren)
.append(Component.text(reversedContent, component.style())));
}
public List<Component> reverseChildren(List<Component> children) {
return children.stream()
.map(this::reverseComponent)
.collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
}));
}
public void removeStringAtStart(String s) {
text = text.replaceText(TextReplacementConfig.builder().match("^" + s).replacement("").build());
}
} }
+86
View File
@@ -0,0 +1,86 @@
import com.alttd.chat.config.Config;
import com.alttd.chat.objects.ModifiableString;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import net.kyori.adventure.text.minimessage.MiniMessage;
public class ReverseTest {
@Test
public void testReverseString() {
String input = "Hello how are you doing today?";
String expectedOutput = new StringBuilder(input).reverse().toString();
MiniMessage miniMessage = MiniMessage.miniMessage();
ModifiableString modifiableString = new ModifiableString(miniMessage.deserialize(input));
modifiableString.reverse();
assertEquals(expectedOutput, modifiableString.string());
}
@Test
public void testRemoveKeyword() {
String input = "Hello how are you doing today?";
MiniMessage miniMessage = MiniMessage.miniMessage();
ModifiableString modifiableString = new ModifiableString(miniMessage.deserialize(Config.APRIL_FOOLS_RESET + " " + input));
modifiableString.removeStringAtStart(Config.APRIL_FOOLS_RESET + " ");
assertEquals(input, modifiableString.string());
}
@Test
public void testRemoveKeywordWithTags() {
MiniMessage miniMessage = MiniMessage.miniMessage();
String input = "<blue>" + Config.APRIL_FOOLS_RESET + " <red>Hello how are</red> you <blue>doing today</blue>?</blue>";
String expectedOutput = "Hello how are you doing today?";
Component deserialize = miniMessage.deserialize(input);
ModifiableString modifiableString = new ModifiableString(deserialize);
modifiableString.removeStringAtStart(Config.APRIL_FOOLS_RESET + " ");
assertEquals(expectedOutput, modifiableString.string());
}
@Test
public void testReverseStringWithTags() {
String input = "<red>Hello how are</red> you <blue>doing today</blue>?";
MiniMessage miniMessage = MiniMessage.miniMessage();
Component deserialize = miniMessage.deserialize(input);
ModifiableString modifiableString = new ModifiableString(deserialize);
String expectedOutput = new StringBuilder(PlainTextComponentSerializer.plainText().serialize(deserialize)).reverse().toString();
modifiableString.reverse();
assertEquals(expectedOutput, modifiableString.string());
}
@Test
public void complexTestReverseStringWithTags() {
String input = "<green><red>Hello <b>how</b> are</red> you <blue>doing today</blue><gold>?</gold></green>";
MiniMessage miniMessage = MiniMessage.miniMessage();
Component deserialize = miniMessage.deserialize(input);
ModifiableString modifiableString = new ModifiableString(deserialize);
String expectedOutput = new StringBuilder(PlainTextComponentSerializer.plainText().serialize(deserialize)).reverse().toString();
modifiableString.reverse();
assertEquals(expectedOutput, modifiableString.string());
}
@Test
public void extraComplexTestReverseStringWithTags() {
String input = "<gold>This <red>is</red> longer<green> <name> <red>Hello <b>how</b> are</red> you <test> <blue>doing <name> today</blue><gold>?</gold></green></gold>";
MiniMessage miniMessage = MiniMessage.miniMessage();
Component deserialize = miniMessage.deserialize(input, TagResolver.resolver(
Placeholder.component("name", miniMessage.deserialize("<red>Cool<blue><rainbow>_player_</rainbow>name</red>")),
Placeholder.parsed("test", "test replacement")
));
ModifiableString modifiableString = new ModifiableString(deserialize);
String expectedOutput = new StringBuilder(PlainTextComponentSerializer.plainText().serialize(deserialize)).reverse().toString();
modifiableString.reverse();
System.out.println(expectedOutput);
assertEquals(expectedOutput, modifiableString.string());
}
}
@@ -13,7 +13,6 @@ import com.alttd.chat.nicknames.Nicknames;
import com.alttd.chat.nicknames.NicknamesEvents; import com.alttd.chat.nicknames.NicknamesEvents;
import com.alttd.chat.objects.channels.Channel; import com.alttd.chat.objects.channels.Channel;
import com.alttd.chat.objects.channels.CustomChannel; import com.alttd.chat.objects.channels.CustomChannel;
import com.alttd.chat.requests.RequestHandler;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
import com.alttd.chat.util.Utility; import com.alttd.chat.util.Utility;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -30,7 +29,6 @@ public class ChatPlugin extends JavaPlugin {
private ChatAPI chatAPI; private ChatAPI chatAPI;
private ChatHandler chatHandler; private ChatHandler chatHandler;
private RequestHandler requestHandler;
private String messageChannel; private String messageChannel;
private ServerConfig serverConfig; private ServerConfig serverConfig;
@@ -42,8 +40,6 @@ public class ChatPlugin extends JavaPlugin {
chatAPI = new ChatImplementation(); chatAPI = new ChatImplementation();
chatHandler = new ChatHandler(); chatHandler = new ChatHandler();
DatabaseConnection.initialize(); DatabaseConnection.initialize();
requestHandler = new RequestHandler();
requestHandler.loadRequests();
serverConfig = new ServerConfig(Bukkit.getServerName()); serverConfig = new ServerConfig(Bukkit.getServerName());
registerListener(new PlayerListener(serverConfig), new ChatListener(), new BookListener()); registerListener(new PlayerListener(serverConfig), new ChatListener(), new BookListener());
if(serverConfig.GLOBALCHAT) { if(serverConfig.GLOBALCHAT) {
@@ -109,10 +105,6 @@ public class ChatPlugin extends JavaPlugin {
return chatHandler; return chatHandler;
} }
public RequestHandler getRequestHandler() {
return requestHandler;
}
public boolean serverGlobalChatEnabled() { public boolean serverGlobalChatEnabled() {
return serverConfig.GLOBALCHAT; return serverConfig.GLOBALCHAT;
} }
@@ -5,13 +5,12 @@ import com.alttd.chat.config.Config;
import com.alttd.chat.handler.ChatHandler; import com.alttd.chat.handler.ChatHandler;
import com.alttd.chat.managers.ChatUserManager; import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.RegexManager; import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.objects.ChatFilter; import com.alttd.chat.objects.*;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.ModifiableString;
import com.alttd.chat.objects.Toggleable;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
import com.alttd.chat.util.GalaxyUtility; import com.alttd.chat.util.GalaxyUtility;
import com.alttd.chat.util.Utility; import com.alttd.chat.util.Utility;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.papermc.paper.event.player.AsyncChatCommandDecorateEvent; import io.papermc.paper.event.player.AsyncChatCommandDecorateEvent;
import io.papermc.paper.event.player.AsyncChatDecorateEvent; import io.papermc.paper.event.player.AsyncChatDecorateEvent;
import io.papermc.paper.event.player.AsyncChatEvent; import io.papermc.paper.event.player.AsyncChatEvent;
@@ -30,6 +29,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.time.*;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -87,7 +87,18 @@ public class ChatListener implements Listener {
ModifiableString modifiableString = new ModifiableString(input); ModifiableString modifiableString = new ModifiableString(input);
// todo a better way for this // todo a better way for this
if(!RegexManager.filterText(player.getName(), player.getUniqueId(), modifiableString, "chat")) { if(!RegexManager.filterText(player.getName(), player.getUniqueId(), modifiableString, true, "chat", filterType -> {
if (!filterType.equals(FilterType.PUNISH)) {
ALogger.warn("Received another FilterType than punish when filtering chat and executing a filter action");
return;
}
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("punish");
out.writeUTF(player.getName());
out.writeUTF(player.getUniqueId().toString());
out.writeUTF(modifiableString.string());
player.sendPluginMessage(ChatPlugin.getInstance(), Config.MESSAGECHANNEL, out.toByteArray());
})) {
event.setCancelled(true); event.setCancelled(true);
GalaxyUtility.sendBlockedNotification("Language", player, GalaxyUtility.sendBlockedNotification("Language", player,
modifiableString.component(), modifiableString.component(),
@@ -97,7 +108,14 @@ public class ChatListener implements Listener {
Set<Player> playersToPing = new HashSet<>(); Set<Player> playersToPing = new HashSet<>();
pingPlayers(playersToPing, modifiableString, player); pingPlayers(playersToPing, modifiableString, player);
LocalDate now = LocalDate.now();
if (now.getMonth().equals(Month.APRIL) && now.getDayOfMonth() == 1) {
if (modifiableString.string().startsWith(Config.APRIL_FOOLS_RESET + " ")) {
modifiableString.removeStringAtStart(Config.APRIL_FOOLS_RESET + " ");
} else {
modifiableString.reverse();
}
}
input = render(player, modifiableString.component()); input = render(player, modifiableString.component());
for (Player receiver : receivers) { for (Player receiver : receivers) {
receiver.sendMessage(input); receiver.sendMessage(input);
@@ -1,23 +0,0 @@
package com.alttd.chat.requests;
import java.util.UUID;
public class NickNameRequest extends Request {
public NickNameRequest(UUID requester, String request) {
super(requester, request);
this.requestType = RequestType.NICKNAME;
}
public NickNameRequest(UUID requester, String request, boolean completed, UUID completedBy, long dateRequested, long dateCompleted) {
super(requester, request, completed, completedBy, dateRequested, dateCompleted);
this.requestType = RequestType.NICKNAME;
}
@Override
public boolean processRequest(UUID processor) {
return false;
}
}
@@ -1,24 +0,0 @@
package com.alttd.chat.requests;
import java.util.UUID;
public class PrefixRequest extends Request{
public PrefixRequest(UUID requester, String request) {
super(requester, request);
this.requestType = RequestType.PREFIX;
}
public PrefixRequest(UUID requester, String request, boolean completed, UUID completedBy, long dateRequested, long dateCompleted) {
super(requester, request, completed, completedBy, dateRequested, dateCompleted);
this.requestType = RequestType.NICKNAME;
}
@Override
public boolean processRequest(UUID processor) {
return false;
}
}
@@ -1,69 +0,0 @@
package com.alttd.chat.requests;
import org.bukkit.Bukkit;
import java.util.Date;
import java.util.UUID;
public abstract class Request {
protected UUID requester;
protected RequestType requestType;
protected String serverName;
protected String request;
protected boolean completed;
protected UUID completedBy;
protected long dateRequested;
protected long dateCompleted;
Request(UUID requester, String request) {
this.requester = requester;
this.request = request;
this.serverName = Bukkit.getServerName();
this.dateRequested = new Date().getTime();
saveRequest();
}
Request(UUID requester, String request, boolean completed, UUID completedBy, long dateRequested, long dateCompleted) {
this.requester = requester;
this.request = request;
this.completed = completed;
this.completedBy = completedBy;
this.dateRequested = dateRequested;
this.dateCompleted = dateCompleted;
}
public static Request of(UUID requester, RequestType requestType, String request) {
return switch (requestType) {
case PREFIX -> new PrefixRequest(requester, request);
case NICKNAME -> new NickNameRequest(requester, request);
};
}
public static Request load(UUID requester, RequestType requestType, String request, boolean completed, UUID completedBy, long dateRequested, long dateCompleted) {
return switch (requestType) {
case PREFIX -> new PrefixRequest(requester, request, completed, completedBy, dateRequested, dateCompleted);
case NICKNAME -> new NickNameRequest(requester, request, completed, completedBy, dateRequested, dateCompleted);
};
}
public boolean processRequest(UUID completedBy) {
completeRequest(completedBy);
return true;
}
public boolean isCompleted() {
return completed;
}
void completeRequest(UUID completedBy) {
this.completed = true;
this.completedBy = completedBy;
this.dateCompleted = new Date().getTime();
saveRequest();
}
public void saveRequest() {
// upsert into database
}
}
@@ -1,61 +0,0 @@
package com.alttd.chat.requests;
import com.alttd.chat.config.Config;
import com.alttd.chat.database.DatabaseConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class RequestHandler {
private final List<Request> requests;
public RequestHandler() {
requests = new ArrayList<>();
}
public boolean addRequest(Request request) {
return requests.add(request);
}
public boolean removeRequest(Request request) {
return requests.remove(request);
}
public List<Request> getRequests() {
return requests;
}
public void loadRequests() {
long time = new Date().getTime() - Config.NICK_WAIT_TIME;
// Load all requests that have not been completed yet
String query = "SELECT * FROM requests WHERE completed=false and (datechanged = 0 or datechanged > " + time + ")";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
UUID requester = UUID.fromString(resultSet.getString("requester"));
RequestType requestType = RequestType.valueOf(resultSet.getString("requesttype"));
String requestString = resultSet.getString("request");
boolean completed = resultSet.getBoolean("completed");
UUID completedby = UUID.fromString(resultSet.getString("completedby"));
long dateRequested = resultSet.getLong("daterequested");
long dateCompleted = resultSet.getLong("datecompleted");
Request request = Request.load(requester, requestType, requestString, completed, completedby, dateRequested, dateCompleted);
addRequest(request);
}
} catch (SQLException exception) {
exception.printStackTrace();
}
}
}
@@ -1,8 +0,0 @@
package com.alttd.chat.requests;
public enum RequestType {
NICKNAME,
PREFIX
}
@@ -1,22 +0,0 @@
package com.alttd.chat.requests;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
public class RequestsGui implements InventoryHolder {
private final Inventory inventory;
private final int inventorySize = 54;
RequestsGui() {
inventory = Bukkit.createInventory(this, inventorySize, "A title");
}
@Override
public @NotNull Inventory getInventory() {
return inventory;
}
}
@@ -4,11 +4,14 @@ import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.objects.ChatUser; import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.channels.CustomChannel; import com.alttd.chat.objects.channels.CustomChannel;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
import com.alttd.proxydiscordlink.DiscordLink;
import com.alttd.proxydiscordlink.lib.net.dv8tion.jda.api.EmbedBuilder;
import com.alttd.velocitychat.VelocityChat; import com.alttd.velocitychat.VelocityChat;
import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PluginMessageEvent; import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.proxy.ConsoleCommandSource;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.ServerConnection; import com.velocitypowered.api.proxy.ServerConnection;
@@ -16,8 +19,10 @@ import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.awt.*;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
public class PluginMessageListener { public class PluginMessageListener {
@@ -93,6 +98,20 @@ public class PluginMessageListener {
proxy.getAllServers().forEach(registeredServer -> proxy.getAllServers().forEach(registeredServer ->
registeredServer.sendPluginMessage(VelocityChat.getPlugin().getChannelIdentifier(), event.getData())); registeredServer.sendPluginMessage(VelocityChat.getPlugin().getChannelIdentifier(), event.getData()));
} }
case "punish" -> {
String playerName = in.readUTF();
ProxyServer proxy = VelocityChat.getPlugin().getProxy();
ConsoleCommandSource consoleCommandSource = proxy.getConsoleCommandSource();
proxy.getCommandManager().executeAsync(consoleCommandSource, String.format("ban %s Automatic ban, please appeal if you feel review is needed.", playerName));
ALogger.info(String.format("Auto banned %s due to violating the `punish` filter.", playerName));
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("Automatic ban through the chat filter");
embedBuilder.setAuthor(playerName, null, "https://crafatar.com/avatars/" + in.readUTF() + "?overlay");
embedBuilder.setDescription(String.format("`%s`\n\n Auto permanent ban\n\n Auto banned for violating the `punish` chat filter. This could be a false positive! Their message was\n||%s||", playerName, in.readUTF()));
embedBuilder.setColor(Color.RED);
DiscordLink.getPlugin().getBot().sendEmbedToDiscord(514922317923614728L, embedBuilder, -1);
}
default -> { default -> {
VelocityChat.getPlugin().getLogger().info("server " + event.getSource()); VelocityChat.getPlugin().getLogger().info("server " + event.getSource());
ProxyServer proxy = VelocityChat.getPlugin().getProxy(); ProxyServer proxy = VelocityChat.getPlugin().getProxy();