Skip to content

Commit

Permalink
feat(bukkit): monitor item spawn
Browse files Browse the repository at this point in the history
  • Loading branch information
HaHaWTH committed Sep 16, 2024
1 parent 522d846 commit fc2cffa
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ public final class AdvancedSensitiveWords extends JavaPlugin {
private static TaskScheduler scheduler;
private static boolean isEventMode = false;
public static Logger LOGGER;
private BukkitLibraryService libraryService;
private static final OllamaProcessor OLLAMA_PROCESSOR = new OllamaProcessor();
private static final OpenAIProcessor OPENAI_PROCESSOR = new OpenAIProcessor();
private static BukkitLibraryService libraryService;
private final OllamaProcessor OLLAMA_PROCESSOR = new OllamaProcessor();
private final OpenAIProcessor OPENAI_PROCESSOR = new OpenAIProcessor();
private VoiceChatHookService voiceChatHookService;
private CachingPermTool permCache;
public static TaskScheduler getScheduler() {
Expand All @@ -84,12 +84,6 @@ public static TaskScheduler getScheduler() {
public static AdvancedSensitiveWords getInstance() {
return instance;
}
public static OllamaProcessor getOllamaProcessor() {
return OLLAMA_PROCESSOR;
}
public static OpenAIProcessor getOpenAIProcessor() {
return OPENAI_PROCESSOR;
}
public static boolean isEventMode() {
return isEventMode;
}
Expand Down Expand Up @@ -125,7 +119,7 @@ public void onLoad() {
public void onEnable() {
LOGGER.info("Loading libraries...");
long startTime = System.currentTimeMillis();
libraryService.load();
libraryService.loadRequired();
LOGGER.info("Initializing DFA system...");
cleanStatisticCache();
scheduler = UniversalScheduler.getScheduler(this);
Expand Down Expand Up @@ -185,6 +179,9 @@ public void onEnable() {
}
if (settingsManager.getProperty(PluginSettings.ENABLE_PLAYER_ITEM_CHECK)) {
getServer().getPluginManager().registerEvents(new PlayerItemListener(), this);
if (settingsManager.getProperty(PluginSettings.ITEM_MONITOR_SPAWN)) {
getServer().getPluginManager().registerEvents(new ItemSpawnListener(), this);
}
}
if (settingsManager.getProperty(PluginSettings.CHAT_BROADCAST_CHECK)) {
if (isClassLoaded("org.bukkit.event.server.BroadcastMessageEvent")) {
Expand Down
5 changes: 1 addition & 4 deletions bukkit/src/main/java/io/wdsj/asw/bukkit/ai/AIProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.wdsj.asw.bukkit.util.VTUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Interface for AI processors (Maybe more in the future?)
*/
public interface AIProcessor {
ExecutorService THREAD_POOL = VTUtils.getVTExecutorServiceOrProvided(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("ASW-AIProcessor-%d").setDaemon(true).build()));
ExecutorService THREAD_POOL = VTUtils.newVirtualThreadPerTaskExecutorOrProvided(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("ASW-AIProcessor-%d").setDaemon(true).build()));
default void shutdown() {
THREAD_POOL.shutdownNow();
}

CompletableFuture<?> process(String input);
}
11 changes: 5 additions & 6 deletions bukkit/src/main/java/io/wdsj/asw/bukkit/ai/OllamaProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
import static io.wdsj.asw.bukkit.AdvancedSensitiveWords.settingsManager;

public class OllamaProcessor implements AIProcessor {
public boolean isOllamaInit = false;
private PromptBuilder promptBuilder;
private OllamaAPI api;
private String modelName;
public static boolean isOllamaInit = false;
private static PromptBuilder promptBuilder;
private static OllamaAPI api;
private static String modelName;
public OllamaProcessor() {
}

Expand Down Expand Up @@ -51,8 +51,7 @@ public void shutdown() {
isOllamaInit = false;
}

@Override
public CompletableFuture<String> process(String inputMessage) {
public static CompletableFuture<String> process(String inputMessage) {
if (!isOllamaInit) {
throw new IllegalStateException("OllamaProcessor is not initialized");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import static io.wdsj.asw.bukkit.AdvancedSensitiveWords.settingsManager;

public class OpenAIProcessor implements AIProcessor {
public boolean isOpenAiInit = false;
private OpenAiClient client;
public static boolean isOpenAiInit = false;
private static OpenAiClient client;
public OpenAIProcessor() {
}

Expand Down Expand Up @@ -44,8 +44,7 @@ public void shutdown() {
isOpenAiInit = false;
}

@Override
public CompletableFuture<ModerationResponse> process(String inputMessage) {
public static CompletableFuture<ModerationResponse> process(String inputMessage) {
if (!isOpenAiInit) {
throw new IllegalStateException("OpenAI Moderation Processor is not initialized");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public BukkitLibraryService(AdvancedSensitiveWords plugin) {
}
}

public void load() {
public void loadRequired() {
libraryManager.loadLibraries(ollama4j, openai4j, caffeine);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ public class PluginSettings implements SettingsHolder {
@Comment({"替换还是取消(replace/cancel)",
"Replace or cancel (replace/cancel)"})
public static final Property<String> ITEM_METHOD = newProperty("Item.method", "replace");
@Comment({"*是否监控物品生成, 给予额外保护",
"*Whether to monitor item spawn as an extra protection"})
public static final Property<Boolean> ITEM_MONITOR_SPAWN = newProperty("Item.monitorSpawn", false);
@Comment({"存在敏感词时是否发送消息提醒",
"Whether to send a message alert when sensitive words are found"})
public static final Property<Boolean> ITEM_SEND_MESSAGE = newProperty("Item.sendMessage", true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ public static void logViolation(String playerName, String violationReason) {
try {
logFile.createNewFile();
} catch (IOException e) {
LOGGER.severe("Failed to create violations.log file: " + e.getMessage());
LOGGER.warning("Failed to create violations.log file: " + e.getMessage());
return;
}
}
try (Writer writer = new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8)) {
writer.write(logMessage + System.lineSeparator());
} catch (IOException e) {
LOGGER.severe("Failed to write to violations.log file: " + e.getMessage());
LOGGER.warning("Failed to write to violations.log file: " + e.getMessage());
}
});
}
Expand Down
10 changes: 6 additions & 4 deletions bukkit/src/main/java/io/wdsj/asw/bukkit/util/VTUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ private VTUtils() {}
Method ofVirtual = Thread.class.getMethod("ofVirtual");
Class<?> ThreadBuilder = Class.forName("java.lang.Thread$Builder");
Method factory = ThreadBuilder.getMethod("factory");
ofVirtual.setAccessible(true);
factory.setAccessible(true);
VTThreadFactory = (ThreadFactory) factory.invoke(ofVirtual.invoke(null));
} catch (Exception e) {
VTThreadFactory = null;
Expand All @@ -37,22 +39,22 @@ private VTUtils() {}
}

@Nullable
public static ThreadFactory getVTThreadFactory() {
public static ThreadFactory newVirtualThreadFactory() {
return VTThreadFactory;
}

@Nullable
public static ExecutorService getVTExecutorService() {
public static ExecutorService newVirtualThreadPerTaskExecutor() {
return VTExecutorService;
}

@NotNull
public static ThreadFactory getVTThreadFactoryOrProvided(ThreadFactory threadFactory) {
public static ThreadFactory newVirtualThreadFactoryOrProvided(ThreadFactory threadFactory) {
return VTThreadFactory != null ? VTThreadFactory : threadFactory;
}

@NotNull
public static ExecutorService getVTExecutorServiceOrProvided(ExecutorService executorService) {
public static ExecutorService newVirtualThreadPerTaskExecutorOrProvided(ExecutorService executorService) {
return VTExecutorService != null ? VTExecutorService : executorService;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import fr.xephi.authme.api.v3.AuthMeApi
import io.wdsj.asw.bukkit.AdvancedSensitiveWords
import io.wdsj.asw.bukkit.AdvancedSensitiveWords.LOGGER
import io.wdsj.asw.bukkit.AdvancedSensitiveWords.settingsManager
import io.wdsj.asw.bukkit.ai.OllamaProcessor
import io.wdsj.asw.bukkit.ai.OpenAIProcessor
import io.wdsj.asw.bukkit.manage.notice.Notifier
import io.wdsj.asw.bukkit.manage.permission.PermissionsConstant
import io.wdsj.asw.bukkit.manage.permission.cache.CachingPermTool
Expand Down Expand Up @@ -71,9 +73,8 @@ class ChatListener : Listener {
return
} else {
if (settingsManager.getProperty(PluginSettings.ENABLE_OLLAMA_AI_MODEL_CHECK)
&& AdvancedSensitiveWords.getOllamaProcessor().isOllamaInit) {
val processor = AdvancedSensitiveWords.getOllamaProcessor()
processor.process(originalMessage)
&& OllamaProcessor.isOllamaInit) {
OllamaProcessor.process(originalMessage)
.thenAccept {
try {
val rating = it?.toInt() ?: 0
Expand Down Expand Up @@ -106,9 +107,8 @@ class ChatListener : Listener {
}
}
if (settingsManager.getProperty(PluginSettings.ENABLE_OPENAI_AI_MODEL_CHECK)
&& AdvancedSensitiveWords.getOpenAIProcessor().isOpenAiInit) {
val processor = AdvancedSensitiveWords.getOpenAIProcessor()
processor.process(originalMessage)
&& OpenAIProcessor.isOpenAiInit) {
OpenAIProcessor.process(originalMessage)
.thenAccept {
val results = it.results() ?: return@thenAccept
for (result in results) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package io.wdsj.asw.bukkit.listener

import io.wdsj.asw.bukkit.AdvancedSensitiveWords.*
import io.wdsj.asw.bukkit.setting.PluginSettings
import io.wdsj.asw.bukkit.util.LoggingUtils
import io.wdsj.asw.bukkit.util.TimingUtils
import io.wdsj.asw.bukkit.util.Utils
import org.bukkit.Location
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.ItemSpawnEvent

class ItemSpawnListener : Listener {
@EventHandler(priority = EventPriority.LOWEST)
fun onItemSpawn(event: ItemSpawnEvent) {
if (!isInitialized || !settingsManager.getProperty(PluginSettings.ITEM_MONITOR_SPAWN) || !settingsManager.getProperty(PluginSettings.ENABLE_PLAYER_ITEM_CHECK)) return
val itemEntity = event.entity
itemEntity.customName?.let {
var originalName = it
if (settingsManager.getProperty(PluginSettings.PRE_PROCESS)) originalName =
originalName.replace(
Utils.getPreProcessRegex().toRegex(), ""
)
val startTime = System.currentTimeMillis()
val censoredWordList = sensitiveWordBs.findAll(originalName)
if (censoredWordList.isNotEmpty()) {
Utils.messagesFilteredNum.getAndIncrement()
if (settingsManager.getProperty(PluginSettings.ITEM_METHOD).equals("cancel", ignoreCase = true)) {
itemEntity.customName = null
} else {
val processedName = sensitiveWordBs.replace(originalName)
itemEntity.customName = processedName
}
val locationLog = itemEntity.location.toLogString()
if (settingsManager.getProperty(PluginSettings.LOG_VIOLATION)) {
LoggingUtils.logViolation("ItemSpawn(IP: None)(ItemSpawn)($locationLog)", originalName + censoredWordList)
}
val endTime = System.currentTimeMillis()
TimingUtils.addProcessStatistic(endTime, startTime)
}
}
}
private fun Location.toLogString(): String {
return "World: ${this.world?.name ?: "Unknown"}, X: ${this.x}, Y: ${this.y}, Z: ${this.z}"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import fr.xephi.authme.api.v3.AuthMeApi
import io.wdsj.asw.bukkit.AdvancedSensitiveWords
import io.wdsj.asw.bukkit.AdvancedSensitiveWords.LOGGER
import io.wdsj.asw.bukkit.AdvancedSensitiveWords.settingsManager
import io.wdsj.asw.bukkit.ai.OllamaProcessor
import io.wdsj.asw.bukkit.ai.OpenAIProcessor
import io.wdsj.asw.bukkit.listener.FakeMessageExecutor
import io.wdsj.asw.bukkit.manage.notice.Notifier
import io.wdsj.asw.bukkit.manage.permission.PermissionsConstant
Expand Down Expand Up @@ -91,9 +93,8 @@ class ASWChatPacketListener : PacketListenerAbstract(PacketListenerPriority.LOW)
return
} else {
if (settingsManager.getProperty(PluginSettings.ENABLE_OLLAMA_AI_MODEL_CHECK)
&& AdvancedSensitiveWords.getOllamaProcessor().isOllamaInit && Utils.isNotCommand(originalMessage)) {
val processor = AdvancedSensitiveWords.getOllamaProcessor()
processor.process(originalMessage)
&& OllamaProcessor.isOllamaInit && Utils.isNotCommand(originalMessage)) {
OllamaProcessor.process(originalMessage)
.thenAccept {
try {
val rating = it?.toInt() ?: 0
Expand Down Expand Up @@ -142,9 +143,8 @@ class ASWChatPacketListener : PacketListenerAbstract(PacketListenerPriority.LOW)
}

if (settingsManager.getProperty(PluginSettings.ENABLE_OPENAI_AI_MODEL_CHECK)
&& AdvancedSensitiveWords.getOpenAIProcessor().isOpenAiInit && Utils.isNotCommand(originalMessage)) {
val processor = AdvancedSensitiveWords.getOpenAIProcessor()
processor.process(originalMessage)
&& OpenAIProcessor.isOpenAiInit && Utils.isNotCommand(originalMessage)) {
OpenAIProcessor.process(originalMessage)
.thenAccept {
val results = it.results() ?: return@thenAccept
for (result in results) {
Expand Down

0 comments on commit fc2cffa

Please sign in to comment.