diff --git a/src/main/java/Sdf1_login/Main.java b/src/main/java/Sdf1_login/Main.java index 1b7f920..6383b09 100644 --- a/src/main/java/Sdf1_login/Main.java +++ b/src/main/java/Sdf1_login/Main.java @@ -184,6 +184,10 @@ public class Main extends JavaPlugin /** 2FA(TOTP) 绑定管理(全部逻辑Java本地,PHP只展示二维码) */ private TwoFactorManager twofa; private OrderManager orderManager; + // ★ 第66批:物品堆叠数量修改管理器 + private StackConfigManager stackConfigMgr; + // ★ 第66批:玩家消息记录管理器 + private PlayerMessageManager playerMsgMgr; public OrderManager getOrderManager() { return orderManager; @@ -926,7 +930,16 @@ public class Main extends JavaPlugin achievementEffectGuard = new AchievementEffectGuard(this); getServer().getPluginManager().registerEvents(achievementEffectGuard, this); getLogger().info("[成就防作弊] 已启用:受管控成就 nether/all_potions、nether/all_effects"); - + + // ===== 第66批:物品堆叠数量修改 + 玩家消息记录 ===== + stackConfigMgr = new StackConfigManager(this); + getServer().getPluginManager().registerEvents(stackConfigMgr, this); + getLogger().info("[物品堆叠] 管理器已注册(懒加载模式,玩家操作时自动检查配置变更)"); + + playerMsgMgr = new PlayerMessageManager(this); + playerMsgMgr.init(); + getLogger().info("[消息记录] 管理器已启用,玩家发言将记录到 playermsg/msg.json"); + // 注册传送命令已在 onCommand 中通过条件分支完成 getLogger().info("§b[Sdf1_login]启动完毕\n§lS欢迎使用sdf1系列插件,如有问题,您可在\nGitHub和Gitee提交反馈"); @@ -958,6 +971,16 @@ public class Main extends JavaPlugin return snManager; } + /** 第66批:物品堆叠数量修改管理器(调试/指令用) */ + public StackConfigManager getStackConfigManager() { + return stackConfigMgr; + } + + /** 第66批:玩家消息记录管理器(调试/指令用) */ + public PlayerMessageManager getPlayerMessageManager() { + return playerMsgMgr; + } + /** 交易记录库(订单/玩家出售偏好) */ public TradeLogManager getTradeLog() { return tradeLog; @@ -4193,6 +4216,19 @@ public class Main extends JavaPlugin e.getPlayer().getName()); } + // ★ 第66批:玩家消息记录(MONITOR 优先级,在所有过滤/取消逻辑之后执行) + // 只记录未被取消的消息——即实际会被广播的消息 + @EventHandler(priority = EventPriority.MONITOR) + public void onChatRecord(AsyncPlayerChatEvent e) { + if (e.isCancelled()) return; + if (playerMsgMgr == null) return; + try { + playerMsgMgr.recordMessage(e.getPlayer(), e.getMessage()); + } catch (Throwable t) { + getLogger().warning("[消息记录] 记录失败: " + t.getMessage()); + } + } + // ===== 告示牌/编辑书/私信链接过滤 ===== // 告示牌通过 onSignChange 拦截,编辑书通过 onPlayerEditBook 拦截 // 私信通过 PlayerCommandPreprocessEvent 拦截(/tell, /msg, /w, /r) diff --git a/src/main/java/Sdf1_login/PlayerMessageManager.java b/src/main/java/Sdf1_login/PlayerMessageManager.java new file mode 100644 index 0000000..b442dd7 --- /dev/null +++ b/src/main/java/Sdf1_login/PlayerMessageManager.java @@ -0,0 +1,185 @@ +package Sdf1_login; + +import com.google.gson.*; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * 玩家消息记录管理器(第66批,2026-11-02)。 + *

+ * 玩家发言时同步将消息写入 {@code playermsg/msg.json}, + * 方便后续复盘追责,不依赖日志文件。 + *

+ * 写入格式: + *

+ * [玩家名]:消息内容  [2026年11月2日 12点26分]
+ * 
+ * 玩家名与消息内容之间用冒号,消息内容与时间之间用 4 个空格分隔。 + */ +public class PlayerMessageManager { + + private final Main plugin; + private final File dataDir; + private final File msgFile; + + /** 消息记录列表(内存缓存,启动时加载) */ + private final List messages = new CopyOnWriteArrayList<>(); + + /** 最大记录条数(防止文件过大) */ + private static final int MAX_MESSAGES = 5000; + + public PlayerMessageManager(Main plugin) { + this.plugin = plugin; + this.dataDir = new File(plugin.getDataFolder(), "playermsg"); + this.msgFile = new File(dataDir, "msg.json"); + } + + /** 初始化:提取资源文件 + 加载已有记录 */ + public void init() { + // 提取文件到数据目录 + if (!dataDir.exists()) { + dataDir.mkdirs(); + } + if (!msgFile.isFile()) { + try (InputStream in = plugin.getResource("playermsg/msg.json")) { + if (in != null) { + Files.copy(in, msgFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } catch (Exception e) { + plugin.getLogger().warning("[消息记录] 提取配置文件失败: " + e.getMessage()); + } + } + loadMessages(); + } + + /** 从文件加载已有消息记录 */ + private void loadMessages() { + messages.clear(); + if (!msgFile.isFile()) return; + + try { + String content = Files.readString(msgFile.toPath(), StandardCharsets.UTF_8); + JsonObject obj = new Gson().fromJson(content, JsonObject.class); + if (obj == null) return; + + JsonArray msgArray = obj.getAsJsonArray("消息记录"); + if (msgArray != null) { + for (JsonElement el : msgArray) { + messages.add(el.getAsString()); + } + } + plugin.getLogger().info("[消息记录] 已加载 " + messages.size() + " 条历史记录"); + } catch (Exception e) { + plugin.getLogger().warning("[消息记录] 加载历史失败: " + e.getMessage()); + } + } + + /** + * 记录玩家消息。 + * 在 AsyncChatEvent 中调用,必须是非阻塞的(异步写文件)。 + * + * @param player 玩家 + * @param message 消息内容 + */ + public void recordMessage(Player player, String message) { + String formatted = formatMessage(player.getName(), message); + messages.add(formatted); + + // 超过上限时删除最早的 + while (messages.size() > MAX_MESSAGES) { + messages.remove(0); + } + + // 异步写文件 + saveMessageAsync(); + } + + /** + * 格式化消息为标准格式。 + * 格式:[玩家名]:消息内容 [2026年11月2日 12点26分] + * + *

示例:example 玩家发了 hello 消息: + *

+     * [example]:hello  [2026年11月2日 12点26分]
+     * 
+ * 注意:消息内容与时间之间是 4 个空格。 + */ + private String formatMessage(String playerName, String message) { + String time = new SimpleDateFormat("yyyy年M月d日 H点m分") + .format(new Date(System.currentTimeMillis())); + return "[" + playerName + "]:" + message + " [" + time + "]"; + } + + /** 异步保存消息到文件(原子写:临时文件 + move) */ + private void saveMessageAsync() { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + try { + List toSave = new ArrayList<>(messages); + + JsonArray msgArray = new JsonArray(); + for (String m : toSave) { + msgArray.add(m); + } + + JsonObject root = new JsonObject(); + root.add("消息记录", msgArray); + root.addProperty("最后更新", System.currentTimeMillis()); + + File tempFile = new File(dataDir, "msg.json.tmp"); + Files.writeString(tempFile.toPath(), + new Gson().toJson(root), + StandardCharsets.UTF_8); + Files.move(tempFile.toPath(), msgFile.toPath(), + StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.ATOMIC_MOVE); + } catch (Exception e) { + plugin.getLogger().warning("[消息记录] 保存失败: " + e.getMessage()); + } + }); + } + + /** + * 从内存中移除消息(被撤回的消息不记录)。 + * + * @param playerName 玩家名 + * @param message 消息内容 + */ + public void removeMessage(String playerName, String message) { + for (int i = messages.size() - 1; i >= 0; i--) { + String m = messages.get(i); + if (m.startsWith("[" + playerName + "]:") && m.contains(message)) { + messages.remove(i); + break; + } + } + } + + /** 获取消息记录(调试用) */ + public List getMessages() { + return new ArrayList<>(messages); + } + + /** 按玩家名搜索消息 */ + public List searchByPlayer(String playerName) { + List result = new ArrayList<>(); + for (String m : messages) { + if (m.startsWith("[" + playerName + "]:")) { + result.add(m); + } + } + return result; + } + + /** 清空所有消息记录 */ + public void clearMessages() { + messages.clear(); + saveMessageAsync(); + } +} \ No newline at end of file diff --git a/src/main/java/Sdf1_login/StackConfigManager.java b/src/main/java/Sdf1_login/StackConfigManager.java new file mode 100644 index 0000000..db62811 --- /dev/null +++ b/src/main/java/Sdf1_login/StackConfigManager.java @@ -0,0 +1,401 @@ +package Sdf1_login; + +import com.google.gson.*; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.io.File; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.zip.CRC32; + +/** + * 物品堆叠数量修改管理器(第66批,2026-11-02)。 + *

+ * 读取 {@code 物品堆叠修改/item.md} 配置,支持: + *

    + *
  • 英文物品名(apple, gold)
  • + *
  • 中文物品名(苹果, 黄金)—— 通过 OfficialTranslations 反向索引翻译
  • + *
  • 通配符 * (如 oak_* 匹配所有 oak 开头的物品)
  • + *
  • 中文通配符「所有」(如 所有羊毛 → 所有 *_wool 物品)
  • + *
+ *

+ * 懒加载策略:玩家操作堆叠时检查配置文件 CRC32 指纹, + * 有变更则增量重载并在控台播报,无变更则静默跳过。 + */ +public class StackConfigManager implements Listener { + + private final Main plugin; + private final File configFile; + + /** 当前生效的映射:Material → maxStackSize */ + private final Map stackMap = new ConcurrentHashMap<>(); + + /** 配置来源的原始键值(用于变更播报) */ + private final Map rawConfig = new ConcurrentHashMap<>(); + + /** 文件指纹(CRC32),用于懒加载比对 */ + private String lastFileHash = ""; + + /** 是否已完成首次加载 */ + private boolean loaded = false; + + public StackConfigManager(Main plugin) { + this.plugin = plugin; + this.configFile = new File(plugin.getDataFolder(), "物品堆叠修改/item.md"); + } + + // ===================== 懒加载 ===================== + + /** + * 懒加载检查:比对文件指纹,有变更则重新加载。 + * 在玩家操作堆叠时调用。 + * + * @return true = 有变更并已重载;false = 无变更或未加载 + */ + public boolean checkAndReload() { + // 首次加载:提取文件 + 加载 + if (!loaded) { + extractAndLoad(); + return true; + } + // 检查文件指纹 + String hash = computeFileHash(); + if (!hash.equals(lastFileHash)) { + reload(); + return true; + } + return false; + } + + /** 提取配置文件从 JAR 到数据目录(仅首次) */ + private void extractAndLoad() { + if (!configFile.isFile()) { + try { + File targetDir = new File(plugin.getDataFolder(), "物品堆叠修改"); + if (!targetDir.exists()) targetDir.mkdirs(); + try (InputStream in = plugin.getResource("物品堆叠修改/item.md")) { + if (in != null) { + Files.copy(in, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + plugin.getLogger().info("[物品堆叠] 已提取配置文件到数据目录"); + } + } + } catch (Exception e) { + plugin.getLogger().warning("[物品堆叠] 提取配置文件失败: " + e.getMessage()); + } + } + reload(); + loaded = true; + } + + /** 计算文件 CRC32 指纹 */ + private String computeFileHash() { + try { + if (!configFile.isFile()) return ""; + byte[] bytes = Files.readAllBytes(configFile.toPath()); + CRC32 crc = new CRC32(); + crc.update(bytes); + return String.valueOf(crc.getValue()); + } catch (Exception e) { + return ""; + } + } + + /** 重新加载配置 */ + public void reload() { + Map newMap = new ConcurrentHashMap<>(); + Map newRaw = new ConcurrentHashMap<>(); + + if (!configFile.isFile()) { + stackMap.clear(); + rawConfig.clear(); + lastFileHash = computeFileHash(); + return; + } + + try { + String content = Files.readString(configFile.toPath(), StandardCharsets.UTF_8); + JsonObject rootObj = parseConfigJson(content); + if (rootObj == null) { + lastFileHash = computeFileHash(); + return; + } + + // 配置在「配置示范」键下(嵌套对象) + JsonObject config示范 = rootObj.getAsJsonObject("配置示范"); + if (config示范 == null) { + config示范 = rootObj; + } + + for (Map.Entry entry : config示范.entrySet()) { + String key = entry.getKey(); + JsonElement val = entry.getValue(); + if (!val.isJsonPrimitive()) continue; + int stackSize = val.getAsInt(); + newRaw.put(key, stackSize); + resolveAndAdd(key, stackSize, newMap); + } + + // 检测变更并播报 + List changes = new ArrayList<>(); + for (Map.Entry e : newMap.entrySet()) { + Integer old = stackMap.get(e.getKey()); + if (old == null) { + changes.add("新增: " + e.getKey().name() + " → " + e.getValue()); + } else if (!old.equals(e.getValue())) { + changes.add("修改: " + e.getKey().name() + " " + old + " → " + e.getValue()); + } + } + for (Material m : stackMap.keySet()) { + if (!newMap.containsKey(m)) { + changes.add("移除: " + m.name()); + } + } + + stackMap.clear(); + stackMap.putAll(newMap); + rawConfig.clear(); + rawConfig.putAll(newRaw); + lastFileHash = computeFileHash(); + + if (!changes.isEmpty()) { + plugin.getLogger().info("[物品堆叠] 配置已更新,变更项 " + changes.size() + " 个:"); + for (String c : changes) { + plugin.getLogger().info(" " + c); + } + } + } catch (Exception e) { + plugin.getLogger().warning("[物品堆叠] 加载配置失败: " + e.getMessage()); + } + } + + /** 从 item.md 内容中提取 JSON 对象 */ + private JsonObject parseConfigJson(String content) { + int jsonStart = content.indexOf("```json"); + if (jsonStart < 0) jsonStart = content.indexOf("```"); + if (jsonStart < 0) return null; + + int contentStart = content.indexOf('\n', jsonStart); + if (contentStart < 0) return null; + + int jsonEnd = content.indexOf("```", contentStart); + if (jsonEnd < 0) return null; + + String jsonStr = content.substring(contentStart + 1, jsonEnd).trim(); + return new Gson().fromJson(jsonStr, JsonObject.class); + } + + // ===================== 键名解析 ===================== + + /** + * 解析配置键名并添加到映射表。 + * 支持:英文直接匹配、中文翻译、通配符 *、中文通配符「所有」。 + */ + private void resolveAndAdd(String key, int stackSize, Map out) { + // 1. 通配符 * (如 oak_* 或 *_wool) + if (key.contains("*")) { + String[] parts = key.split("\\*", -1); + String prefix = parts[0]; + String suffix = parts.length > 1 ? parts[1] : ""; + for (Material m : Material.values()) { + String name = m.name().toLowerCase(Locale.ROOT); + if (name.startsWith(prefix) && name.endsWith(suffix) + && !m.name().equals("AIR")) { + out.put(m, stackSize); + } + } + return; + } + + // 2. 中文通配符「所有」+ 名称 + if (key.startsWith("所有")) { + String zhPart = key.substring(2); // 去掉"所有" + String enPart = translateChinese(zhPart); + if (enPart != null && !enPart.isEmpty()) { + for (Material m : Material.values()) { + String name = m.name().toLowerCase(Locale.ROOT); + if (name.contains(enPart.toLowerCase(Locale.ROOT)) && !m.name().equals("AIR")) { + out.put(m, stackSize); + } + } + } else { + plugin.getLogger().warning("[物品堆叠] 无法翻译中文通配符: " + key); + } + return; + } + + // 3. 直接英文 Material 名 + Material direct = Material.matchMaterial(key); + if (direct != null) { + out.put(direct, stackSize); + return; + } + + // 4. 中文精确名 → 英文(通过 OfficialTranslations 反向索引) + Map> rev = OfficialTranslations.reverseMap(); + if (!rev.isEmpty()) { + List names = rev.get(key); + if (names != null) { + for (String en : names) { + Material m = Material.matchMaterial(en); + if (m != null) out.put(m, stackSize); + } + return; + } + } + + plugin.getLogger().warning("[物品堆叠] 无法解析配置键: " + key); + } + + /** 中文→英文翻译(利用 OfficialTranslations 反向索引) */ + private String translateChinese(String zh) { + Map> rev = OfficialTranslations.reverseMap(); + if (rev.isEmpty()) return null; + + List names = rev.get(zh); + if (names != null && !names.isEmpty()) { + return names.get(0); + } + + // 模糊匹配:找包含 zh 的中文键 + for (Map.Entry> entry : rev.entrySet()) { + if (entry.getKey().contains(zh) && !entry.getValue().isEmpty()) { + return entry.getValue().get(0); + } + } + return null; + } + + // ===================== 应用堆叠数量 ===================== + + /** 获取物品的自定义堆叠上限,未配置返回 -1 */ + public int getMaxStackSize(Material m) { + if (m == null) return -1; + Integer v = stackMap.get(m); + return v != null ? v : -1; + } + + /** + * 对 ItemStack 应用自定义堆叠上限。 + * 仅在配置了堆叠数量时才修改,避免副作用。 + * + * @return true = 已修改;false = 未配置或无需修改 + */ + public boolean applyStackSize(ItemStack item) { + if (item == null || item.getType() == Material.AIR) return false; + int max = getMaxStackSize(item.getType()); + if (max > 0 && item.getMaxStackSize() != max) { + ItemMeta meta = item.getItemMeta(); + if (meta != null) { + meta.setMaxStackSize(max); + item.setItemMeta(meta); + } + return true; + } + return false; + } + + // ===================== 事件监听 ===================== + + /** + * 玩家点击物品栏时触发懒加载 + 应用堆叠数量。 + * LOWEST 优先级确保先于其它处理器执行。 + */ + @EventHandler(priority = EventPriority.LOWEST) + public void onInventoryClick(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) return; + + checkAndReload(); + + if (e.getClickedInventory().getHolder() instanceof Player) { + applyStackSize(e.getCurrentItem()); + } + applyStackSize(e.getCursor()); + } + + /** 玩家拖拽物品时应用堆叠数量 */ + @EventHandler(priority = EventPriority.LOWEST) + public void onInventoryDrag(InventoryDragEvent e) { + if (!(e.getWhoClicked() instanceof Player)) return; + checkAndReload(); + // Paper 26.x 移除了 getNewContents(),改用 getNewItems() + java.util.Map newItems = null; + try { + newItems = e.getNewItems(); + } catch (Throwable t) { + try { + Object v = e.getClass().getMethod("getNewContents").invoke(e); + if (v instanceof java.util.Map) { + @SuppressWarnings("unchecked") + java.util.Map m = (java.util.Map) v; + newItems = m; + } + } catch (Throwable ignored) {} + } + if (newItems == null) return; + for (ItemStack item : newItems.values()) { + applyStackSize(item); + } + } + + /** 玩家拾取地上物品时应用堆叠数量 */ + @EventHandler(priority = EventPriority.LOWEST) + public void onItemPickup(EntityPickupItemEvent e) { + if (!(e.getEntity() instanceof Player)) return; + checkAndReload(); + applyStackSize(e.getItem().getItemStack()); + } + + /** 玩家合成物品时应用堆叠数量 */ + @EventHandler(priority = EventPriority.LOWEST) + public void onCraftItem(CraftItemEvent e) { + if (!(e.getWhoClicked() instanceof Player)) return; + checkAndReload(); + // Paper 26.x: getResult() 返回 Event.Result,旧版直接返回 ItemStack + Object resultObj; + try { + resultObj = e.getResult(); + } catch (Throwable t) { + return; + } + if (resultObj == null) return; + ItemStack crafted = null; + if (resultObj instanceof ItemStack) { + crafted = (ItemStack) resultObj; + } else { + // Event.Result → 取 .get() + try { + Object val = resultObj.getClass().getMethod("get").invoke(resultObj); + if (val instanceof ItemStack) { + crafted = (ItemStack) val; + } + } catch (Throwable ignored) {} + } + applyStackSize(crafted); + } + + // ===================== 调试 ===================== + + /** 获取当前配置映射(调试用) */ + public Map getStackMap() { + return Collections.unmodifiableMap(stackMap); + } + + /** 是否已加载 */ + public boolean isLoaded() { + return loaded; + } +} diff --git a/src/main/resources/playermsg/msg.json b/src/main/resources/playermsg/msg.json new file mode 100644 index 0000000..6a12b92 --- /dev/null +++ b/src/main/resources/playermsg/msg.json @@ -0,0 +1,5 @@ +{ + "玩家消息记录复盘": "方便时候追责目标玩家的发言、和行为", + "规范格式": "[user]:[msg] [time]", + "example": "[example] 4个空格 [2026年11月2日 12点26分]" +} \ No newline at end of file diff --git a/src/main/resources/物品堆叠修改/item.md b/src/main/resources/物品堆叠修改/item.md new file mode 100644 index 0000000..15e7a70 --- /dev/null +++ b/src/main/resources/物品堆叠修改/item.md @@ -0,0 +1,19 @@ +## ----配置区域开始---- + +```json +{ + "物品堆叠映射":"", + "食用方法":"键值对,键=品名,值=数量", + "配置示范":{ + "apple":128, + "gold":32, + "*_wool":100, + "所有橡木":90 + } +} +``` +## ----配置区域结束---- + +### 物品堆叠食用说明 + +- 在上方json围栏块内,按键值对修改。支持使用中文。通配符支持:`*`和中文词组`所有`。比如`oak_*`表示所有以oak开头的,比如橡木、橡木告示牌、橡木台阶等。`所有羊毛`表示所有以_wool结尾的羊毛。 \ No newline at end of file