Import ItxiaohuiServerAdvancements 1.2.0 source

This commit is contained in:
xhgit committed 2026-11-13 22:30:40 +08:00
1 parent f8f9c9abce
commit 6a9a20b2d7
45 files changed
+7446 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
/gradlew text eol=lf
+30
View File
@@ -0,0 +1,30 @@
.gradle/
build/
test-server/
test-client/node_modules/
.idea/
*.iml
*.log
# Local test and production deployment material, not part of the public source.
/audit-results/
/deployment/
/test-client/
/src/probe/
/AUTOMATION_REPORT.md
/DEPLOYMENT_REPORT.md
/FEATURE_REPORT.md
/FIX_REPORT.md
/FULL_AUDIT_REPORT.md
/TEST_REPORT.md
# Local credentials and data.
.env
.env.*
*.pem
*.key
*.jks
*.p12
*.db
*.db-wal
*.db-shm
+170
View File
@@ -0,0 +1,170 @@
# 自动优先成就目录(1.2.0)
默认开启 **129 个自动普通成就 + 1 个根进度**:原有 17 个自动成就,加上趣味目录中的 112 个自动成就。另保留 22 个默认关闭的可选人工项目;不启用它们也不影响自动路线。
本次将原趣味目录中的 34 项人工条件改成可测量规则,并新增 60 个自动成就。部分名称保留、目标描述调整:例如铁路按放置铁轨计数,住宅按建材清单计数,不冒充审美、连通性或公共贡献鉴定。
## 不需要 AI 或管理员日常审核
- 原版统计:任意颜色床的合成、航行、骑乘、游泳、交易、附魔、钓鱼等,读取玩家原版累计统计,可能包含安装前历史。
- 原版进度:图腾、远距离狙击、恶魂火球反弹等,核对真正完成的原版 Advancement。
- 真实事件:进食、从烹饪设备取出食物、驯服、成功钓获和方块放置;记录新版安装后的成功事件,取消事件不计。
- 背包收藏:检查随身物品栏(含装备和副手),按不同物品种类与数量判断,不统计箱子里或背包内部容器中的物品。
- 生物群系和结构:约每 10 秒在玩家当前位置采样;结构按天然生成结构的包围盒及小幅邻接余量判断,并按世界、类型和结构位置去重。不是搜索全世界,也不代表完整探索所有房间。
- 这版插件没有 AI 接口、API Key、调用费或把聊天/截图送交 AI 的流程。建筑审美、原创性和社交贡献不交给模型直接决定发奖。
## 升级、编辑与可选项目
首次启动先备份 advancements.yml,安装标记升级为 bundled-fun-catalog-version: 2。1.1.0 中与原模板完全相同的 74 项会升级,额外补入 60 项。管理员修改过的同名定义、禁用状态以及主动删除的旧条目保留,不强制覆盖。因此有自定义配置的服务器,实际启用数量可能与默认不同。
只编辑运行目录的 advancements.yml。JAR 内 fun-advancements.yml 是新版模板,fun-advancements-v1.yml 只用于识别未修改的旧模板。修改后正常停服重启,不使用 Bukkit /reload。数据库和玩家原版进度不用清空,原有奖励防重记录继续有效。
默认关闭的 22 项适合已有活动运营的服务器,可手工设置 enabled: true 后正常重启,再使用 /isa give <在线玩家> <ID> 授予;自动路线没有依赖这些人工节点。自定义地标也可以改用现有 reach_location 条件并填写真实坐标。
新目录奖励仅 10–100 经验点、禁止重复领取,不发货币或强力装备。拾取和放置统计允许重复拿放,不是不可刷的经济凭证。
## 112 个自动项目
| 名称 | ID | 自动目标 |
|---|---|---|
| 先富带动后富 | `fun_diamond_64` | 累计从地面拾取 64 个钻石 |
| 小区保安 | `fun_neighborhood_guard` | 击杀 30 只僵尸、20 只骷髅和 10 只苦力怕 |
| 这不是流水线 | `fun_bread_factory` | 累计合成 1024 个面包 |
| 禁止随地大小牧 | `fun_responsible_rancher` | 成功繁殖动物 50 次 |
| 差一点就附魔了 | `fun_level_30` | 历史达到 30 级经验 |
| 这里居然还有人住 | `fun_remote_village` | 进入一处天然生成的村庄范围(不要求偏远) |
| 服务器考古学家 | `fun_server_archaeologist` | 探索三处不同的天然遗迹:神殿或海底废墟;按结构位置去重 |
| 高处不胜寒 | `fun_lonely_peak` | 历史到达 Y≥200 的高处;不限定服主自建山顶 |
| 腿是自己的,路是服主的 | `fun_walk_10km` | 累计移动 10000 格;不计单次至少 100 格的跳变 |
| 下界出差申请已批准 | `fun_nether_business` | 首次进入下界,解锁探索分支 |
| 不是终点,是新起点 | `fun_new_beginning` | 进入末地并亲手击杀末影龙 |
| 什么都懂一点 | `fun_jack_of_trades` | 完成钻石收集、面包合成、社区防卫和长途探索四项成就 |
| 服里的老熟人 | `fun_old_friend` | 完成综合入门、繁殖、经验等级、首次合成床;不再依赖人工考古审核 |
| 今晚终于有床了 | `fun_first_bed` | 亲手合成第一张床,任意颜色均可 |
| 拒绝吃生的 | `fun_cooked_food` | 从熔炉、烟熏炉等取出累计 64 份已烹饪食物 |
| 背包里有个动物园 | `fun_pocket_zoo` | 同时持有清单中五种动物相关物品:蛋、羽毛、骨头、线、皮革、墨囊、蜂蜜、鳕鱼 |
| 吃点好的 | `fun_varied_diet` | 安装新版后实际吃下十种不同食物 |
| 保命的钱不能省 | `fun_totem_saved` | 达成原版进度:使用不死图腾逃过一劫 |
| 出门在外靠自己 | `fun_self_made_iron` | 背包或身穿同时攒齐铁头盔、胸甲、护腿和靴子;不限制物资来源 |
| 今天不想走路 | `fun_boat_3km` | 原版统计累计乘船航行 3000 格(300000 厘米) |
| 沙漠里也有惊喜 | `fun_desert_temple` | 进入一座天然沙漠神殿的结构范围 |
| 小心脚下 | `fun_jungle_temple` | 进入一座天然丛林神庙的结构范围 |
| 船长已经下班 | `fun_three_shipwrecks` | 进入三艘位置不同的天然沉船范围 |
| X 标记的地方 | `fun_buried_treasure` | 到达一处天然埋藏宝藏位置;不验证是否使用藏宝图 |
| 海底不包呼吸 | `fun_ocean_monument` | 进入一座天然海底神殿的结构范围 |
| 安静,现在很危险 | `fun_ancient_city` | 进入一座天然远古城市的结构范围;不要求往返 |
| 这房子比我家大 | `fun_woodland_mansion` | 进入一座天然林地府邸的结构范围 |
| 冰箱门忘关了 | `fun_ice_spikes` | 被环境采样记录到达冰刺平原 |
| 蘑菇比树还像树 | `fun_mushroom_fields` | 被环境采样记录到达蘑菇岛 |
| 一粒种子的野心 | `fun_wheat_1000` | 累计从地面收集 1000 个小麦;收获后拾取也计入 |
| 土豆不是货币 | `fun_potato_512` | 累计从地面收集 512 个马铃薯 |
| 西瓜批发市场 | `fun_melon_1024` | 累计从地面收集 1024 片西瓜 |
| 蜂蜜自由 | `fun_honey_64` | 同时在随身物品栏持有 64 瓶蜂蜜,不限制获取方式 |
| 羊毛色卡 | `fun_rainbow_wool` | 同时在随身物品栏持有全部 16 色羊毛 |
| 猫说这里归它了 | `fun_three_cats` | 安装新版后亲自驯服三只猫 |
| 出门带保镖 | `fun_five_wolves` | 安装新版后亲自驯服五只狼 |
| 鱼没钓到,家当不少 | `fun_fishing_variety` | 安装新版后通过成功钓获获得五种不同物品 |
| 从火柴盒开始 | `fun_first_home` | 完成开荒建材清单:合成床,放置 64 块木板、1 扇木门和 4 支火把;不鉴定房屋外形 |
| 窗户不是装饰 | `fun_windows_20` | 安装新版后累计放置 20 个玻璃方块或玻璃板,不要求属于住宅 |
| 铁路不是摆设 | `fun_railway_500` | 安装新版后累计放置 500 个铁轨类方块;不验证线路连通 |
| 整理,是一种修行 | `fun_organized_storage` | 亲手合成 16 个箱子及 8 块告示牌,准备分类仓储;不评价整理效果 |
| 唱片不负责打怪 | `fun_six_records` | 同时持有内置唱片清单中六张不同唱片 |
| 花里胡哨才是家 | `fun_flower_garden` | 安装新版后实际种下十种清单内不同的花;不要求位于同一花园 |
| 蜘蛛不是室友 | `fun_spiders_50` | 累计亲手击杀 50 只蜘蛛 |
| 今晚不做梦 | `fun_phantoms_10` | 累计亲手击杀 10 只幻翼 |
| 隔壁的弓箭更准 | `fun_sniper_skeleton` | 达成原版狙击手进度:从至少 50 格外射杀骷髅 |
| 盾牌不是锅盖 | `fun_shield_10` | 原版盾牌格挡伤害统计达到 100(原版十分之一伤害点计量) |
| 让它自己冷静一下 | `fun_return_to_sender` | 达成原版见鬼去吧进度:反弹恶魂火球并击杀它 |
| 烈焰人事部 | `fun_blaze_rods_32` | 累计从地面拾取 32 根烈焰棒 |
| 海底清洁工 | `fun_elder_guardian` | 亲手击败一只远古守卫者 |
| 三个头也得排队 | `fun_wither_boss` | 亲手击败一只凋灵 |
| 箭有自己的想法 | `fun_piercing_arrow` | 达成原版一箭双雕进度:用穿透弩一箭击杀两只幻翼 |
| 膝盖还好吗 | `auto_jumps` | 累计跳跃 1000 次 |
| 风一样的方块人 | `auto_sprint` | 累计疾跑 10 公里 |
| 悄悄地进村 | `auto_crouch` | 累计潜行移动 500 格 |
| 泳池已经装不下你 | `auto_swim` | 累计游泳 1000 格 |
| 下一站没有终点 | `auto_minecart` | 累计乘矿车移动 3000 格 |
| 这匹马有编制 | `auto_horse` | 累计骑马移动 2000 格 |
| 今天也不走正门 | `auto_elytra` | 累计鞘翅飞行 10 公里 |
| 楼梯对你没有吸引力 | `auto_climb` | 累计攀爬 500 格 |
| 岩浆专线乘客 | `auto_strider` | 累计骑炽足兽移动 1000 格 |
| 愿者上钩一百次 | `auto_fish100` | 原版成功钓鱼统计达到 100 |
| 村民看见你就上班 | `auto_trade50` | 与村民成功交易 50 次 |
| 附魔台的常客 | `auto_enchant10` | 完成 10 次物品附魔 |
| 全村都知道你来了 | `auto_bells` | 敲钟 100 次 |
| 音乐可能不是你的错 | `auto_notes` | 演奏音符盒 100 次 |
| 点歌台营业中 | `auto_records` | 播放唱片 10 次 |
| 床才是终极装备 | `auto_sleep` | 原版入睡统计达到 10 次 |
| 铁砧正在申请工伤 | `auto_anvil` | 与铁砧交互 20 次 |
| 阳台承包商 | `auto_potted` | 向花盆种入植物 16 次 |
| 本村荣誉保安 | `auto_raid` | 原版袭击胜利统计达到 1 |
| 炼药室的新员工 | `auto_brewing` | 与酿造台交互 10 次;不冒充酿出药水次数 |
| 下界也有房地产 | `auto_fortress` | 进入原版进度认可的下界要塞 |
| 古代人的零花钱 | `auto_debris` | 获得远古残骸并达成对应原版进度 |
| 黑曜石也会哭 | `auto_crying` | 获得哭泣的黑曜石并达成对应原版进度 |
| 村民今天有折扣 | `auto_hero` | 达成原版村庄英雄进度 |
| 它好像认得你 | `auto_tame` | 达成原版驯服动物进度 |
| 明天的饭有着落了 | `auto_seed` | 达成原版种下种子的进度 |
| 这把锄头有点贵 | `auto_hoe` | 达成原版下界合金锄进度 |
| 快递员正式上岗 | `auto_wings` | 达成原版获得鞘翅进度 |
| 电梯维修中 | `auto_levitate` | 达成原版在末地漂浮挑战进度 |
| 看清楚再打 | `auto_spyglass` | 用望远镜观察末影龙并达成对应原版进度 |
| 木匠的色卡 | `auto_wood_palette` | 同时携带八种不同木板 |
| 口袋里有半座矿山 | `auto_miner_pockets` | 同时持有铁铜金粗矿、红石、青金石、煤、钻石、绿宝石和石英 |
| 书里真的有力量 | `auto_enchanted_book` | 随身持有一本附魔书 |
| 骑乘业务扩张中 | `auto_saddles` | 随身持有三个鞍 |
| 叮叮当当一整组 | `auto_amethyst` | 随身持有 64 个紫水晶碎片 |
| 地底寄来的回声 | `auto_echo` | 随身持有 8 个回响碎片 |
| 海螺里的声音 | `auto_nautilus` | 随身持有 8 个鹦鹉螺壳 |
| 海王的备用餐具 | `auto_trident` | 随身持有三叉戟 |
| 移动仓库开张 | `auto_shulkers` | 随身持有 16 个潜影壳 |
| 盔甲也要穿搭 | `auto_trims` | 同时持有哨兵、沙丘、监守和尖塔四种锻造模板 |
| 红土不用滤镜 | `auto_badlands` | 环境采样记录到达 badlands 生物群系 |
| 樱花开到你面前 | `auto_cherry_grove` | 环境采样记录到达 cherry_grove 生物群系 |
| 声音请调到最小 | `auto_deep_dark` | 环境采样记录到达 deep_dark 生物群系 |
| 树根比路还多 | `auto_mangrove_swamp` | 环境采样记录到达 mangrove_swamp 生物群系 |
| 地底居然有花园 | `auto_lush_caves` | 环境采样记录到达 lush_caves 生物群系 |
| 天花板有点尖 | `auto_dripstone_caves` | 环境采样记录到达 dripstone_caves 生物群系 |
| 雪山慢递 | `auto_snowy_slopes` | 环境采样记录到达 snowy_slopes 生物群系 |
| 蓝色森林不卖奶茶 | `auto_warped_forest` | 环境采样记录到达 warped_forest 生物群系 |
| 红色森林不卖草莓 | `auto_crimson_forest` | 环境采样记录到达 crimson_forest 生物群系 |
| 鞋底快熟了 | `auto_basalt_deltas` | 环境采样记录到达 basalt_deltas 生物群系 |
| 干饭也算正经事 | `auto_eat64` | 安装新版后实际吃下 64 份食物 |
| 菜单已经翻到第二页 | `auto_eat20` | 安装新版后实际吃下 20 种不同食物 |
| 食堂今天我值班 | `auto_cook256` | 安装新版后从烹饪设备取出 256 份食物 |
| 火候各有讲究 | `auto_cook5` | 安装新版后取出五种不同的烹饪食物 |
| 鱼塘股东 | `auto_fish256` | 安装新版后成功钓获累计 256 个物品 |
| 水底杂货铺 | `auto_fish10` | 安装新版后成功钓获十种不同物品 |
| 朋友圈开始长毛 | `auto_tame10` | 安装新版后亲自成功驯服十只动物 |
| 一块一块垒起来 | `auto_place1000` | 安装新版后实际放置 1000 个方块;拆后重放也计数 |
| 采光优先 | `auto_glass100` | 安装新版后实际放置 100 块透明玻璃 |
| 花店终于进齐货 | `auto_flowers16` | 安装新版后实际种下清单中 16 种不同的花 |
## 22 个可选人工项目(默认关闭)
| 名称 | ID | 可选验收目标 |
|---|---|---|
| 地图边缘的咖啡馆 | `fun_distant_cafe` | 找到服主设置在远方的小屋或咖啡馆 |
| 自由落体体验券 | `fun_water_landing` | 从挑战高台落入指定水池并存活;由服主设置安全场地 |
| 这水有点烫 | `fun_lava_escape` | 进入岩浆后成功脱险,提供过程证据 |
| 我的床有自己的想法 | `fun_forgot_bed` | 设置重生点后远行,发现忘带床并记录这次冒险 |
| 此处禁止施工 | `fun_secret_room` | 找到服主藏在地图里的秘密房间;无需破坏建筑 |
| 南瓜董事长 | `fun_pumpkin_farm` | 建成至少有 100 个南瓜的农场 |
| 给动物一点体面 | `fun_humane_ranch` | 建成有照明、遮雨与分区的牧场 |
| 夜里终于看得见了 | `fun_public_lighting` | 完成一段公共道路的照明;先取得道路管理者同意 |
| 桥归桥,路归路 | `fun_river_bridge` | 建造一座安全、可通行的跨河桥 |
| 地下也要有生活 | `fun_underground_home` | 建造含卧室、仓库和种植区的地下基地 |
| 请勿拆除,具有历史价值 | `fun_preserved_hut` | 保留自己的第一间小屋,并设置纪念牌 |
| 装备差,胆子大 | `fun_light_gear_challenge` | 不穿钻石及以上护甲,完成服主指定挑战副本 |
| 新人接待处 | `fun_welcome_newcomer` | 自愿帮助一位新人完成安家,经对方确认 |
| 借你一把镐 | `fun_lend_a_pickaxe` | 向新人赠送一套实用工具,经对方确认;不索要回报 |
| 这条路大家都能走 | `fun_public_road` | 参与修建一条公共道路,获得负责人确认 |
| 免费,但不是垃圾桶 | `fun_community_donation` | 向公共物资站捐赠一组指定实用物资 |
| 我家大门常打开 | `fun_open_house` | 举办一次自愿参加的玩家参观活动 |
| 合影请看这里 | `fun_group_photo` | 与五名其他玩家在指定地标合影;尊重参与意愿 |
| 差一点就是冠军 | `fun_event_participant` | 完整参加一次服务器活动,不要求获胜 |
| 建筑工地有我一份 | `fun_community_builder` | 参与一次公共建筑项目,经负责人确认 |
| 今天由我来讲故事 | `fun_original_story` | 为服务器图书馆写一本原创游戏故事 |
| 多年以后还能找到这里 | `fun_time_capsule` | 在纪念馆留下自己的书、署名和加入日期 |
构建、测试和使用限制见 [README](README.md)。
+176 -1
View File
@@ -1,3 +1,178 @@
# ItxiaohuiServerAdvancements
ItxiaohuiServerAdvancements 是一款面向 Paper 1.21.8 的 Minecraft 服务端成就插件。通过原版进度界面展示独立的服务器成就树,默认启用 129 个自动成就,涵盖探索、战斗、种田、烹饪、驯养与收藏。无需客户端模组、AI 接口或管理员逐项审核。
ItxiaohuiServerAdvancements 是一款面向 Paper 1.21.8 的 Minecraft 服务端成就插件。通过原版进度界面展示独立的服务器成就树,默认启用 129 个自动成就,涵盖探索、战斗、种田、烹饪、驯养与收藏。无需客户端模组、AI 接口或管理员逐项审核。
当前版本为 **1.2.0**,构建需要 Java 21。默认包含 **129 个自动普通成就 + 根进度**,另保留 22 个默认关闭的可选人工项目。见[完整目录与管理说明](FUN_ACHIEVEMENTS.md)。
## 安装
1. 使用 Java 21 启动 Paper 1.21.8。
2. 将 `build/libs/ItxiaohuiServerAdvancements.jar` 放入服务端 `plugins/`。
3. 正常启动服务端。插件会自动创建:
- `plugins/ItxiaohuiServerAdvancements/config.yml`
- `plugins/ItxiaohuiServerAdvancements/advancements.yml`
- `plugins/ItxiaohuiServerAdvancements/messages.yml`
- `plugins/ItxiaohuiServerAdvancements/data/advancements.db`
4. 玩家加入后约 1 秒自动获得无弹窗、无广播、无奖励的根进度;按 `L` 打开原版进度界面。
1.2.0 首次启动会先备份原 `advancements.yml`,安装/升级自动优先目录:与旧模板完全一致的定义自动更新,自定义条目、管理员禁用状态和已删除旧项保留。后续启动不会反复安装,不清库。少量主观或服务器专属项目默认关闭,不影响自动路线。模板不生成世界建筑,也不虚构地点坐标。
不要使用 Bukkit `/reload`。修改 Advancement 的 ID、父级、图标、标题、描述、显示选项或增删节点后,请用 `stop` 正常关闭服务器再启动。Paper 1.21.8 的动态移除接口不会在当前进程中立即清除注册表,因此插件故意拒绝危险的热替换。
## 构建
```powershell
.\gradlew.bat clean test shadowJar
```
产物固定为 `build/libs/ItxiaohuiServerAdvancements.jar`。SQLite JDBC 3.50.3.0 已打包并通过隔离类加载器加载,避免选中 Paper 内置的其他版本;JNI 包名保持原样。不需要另装数据库或驱动。
Linux/macOS 可执行 `./gradlew clean test shadowJar`。
## 配置
全局选项位于 `config.yml`。`root` 控制独立页签的根节点,根 ID 不能作为普通成就删除;`statistics.flush-interval-seconds` 控制内存统计批量写入周期。全局配置或节点定义修改后需要正常重启,消息文件可用 `/isa reload` 重载。
普通成就位于 `advancements.yml`:
```yaml
achievements:
first_diamond:
name: "钻石收藏家"
description: "累计从地面拾取 64 个钻石"
icon: "minecraft:diamond"
frame: goal # task / goal / challenge
parent: root
display: { x: 2, y: 0 } # 排序提示;原版客户端负责最终坐标
hidden: false
show-toast: true
announce-chat: false
enabled: true
conditions:
- { type: collect_item, item: "minecraft:diamond", amount: 64 }
rewards:
experience: 100
allow-reclaim: false
items:
- { item: "minecraft:emerald", amount: 3 }
commands:
- "say {player} 完成了钻石收藏家"
```
一个成就的多个条件采用 AND 关系。配置加载时会检查非法 ID、图标、材料、未知条件、缺失父级、依赖缺失和父级循环。单个坏定义会被隔离并写入明确日志;`/isa validate` 可提前检查。
### 条件类型与统计口径
| 类型 | 必要参数 | 统计口径 |
|---|---|---|
| `first_join` | 无 | Bukkit 判定的首次加入 |
| `online_time` | `amount`, `unit` | 登录会话累计;单位为 seconds/minutes/hours |
| `mine_block` | `block`, `amount` | 未取消的方块破坏事件 |
| `collect_item` | `item`, `amount` | 从世界物品实体拾取的数量;不含交易、容器转移、管理员命令等来源 |
| `obtain_item` | `item`, `amount` | 插件能确认的新获得数量:当前包括地面拾取和玩家合成产出;不含交易、容器转移或命令来源 |
| `kill_mob` | `entity`, `amount` | 玩家作为直接 Bukkit killer 的击杀;`entity: "*"` 表示任意实体 |
| `visit_dimension` | `dimension` | 加入时所在维度或切换后进入的维度 |
| `move_distance` | `amount` | 同一世界内实际移动距离;单次大于等于 100 格的跳变不计,避免传送灌水 |
| `reach_location` | `world`, `x`, `y`, `z`, `radius`, 可选 `id` | 进入指定球形区域 |
| `craft_item` | `item`, `amount` | 原版 CRAFT_ITEM 成功统计的增量;包括普通和 Shift 合成,不统计无产出点击 |
| `breed_mob` | `entity`, `amount` | 玩家作为繁殖者的成功繁殖;支持 `*` |
| `experience_level` | `amount` | 历史达到的最高经验等级 |
| `complete_achievement` | `achievement` | 指定服务器成就的原版完成状态 |
| `manual` | 无 | 只能由管理员授予 |
| `player_statistic` | `statistic`, `amount`,按统计类型可需 `materials` 或 `entity` | 读取原版累计统计;距离单位为厘米,可能包含安装前历史 |
| `vanilla_advancement` | `advancement` | 指定 minecraft 原版进度已完成 |
| `inventory_set` | `items`, `amount`,可选 `each` | 随身物品中至少指定数量的不同种类,每种满足数量要求 |
| `visit_biome` | `biome` | 周期采样记录到达该生物群系 |
| `visit_structure` | `structures`, `amount` | 周期记录进入不同的天然结构位置,重复进入同一处不累加 |
| `altitude` | `amount` | 环境采样记录历史到达的最高正 Y 坐标 |
| `event_count` | `event`, `amount`,可选 `subjects` | 新版安装后的进食、取出烹饪食物、驯服、成功钓获或放置方块数量 |
| `event_distinct` | 同上 | 对上述事件记录的不同对象种类计数,不把重复吃同一种食物当新品种 |
统计值是历史累计值,不会因物品被丢弃、存箱或成就被撤销而清零。节点 `x/y` 不是原版 Advancement JSON 字段;插件将其用于稳定排序,最终位置由原版客户端按父子树自动布局。
### 奖励
- `experience`:经验点(不是经验等级)。
- `items`:原版物品 ID 与数量;背包放不下时掉落在玩家位置。
- `commands`:由控制台执行,支持受控占位符 `{player}` 和 `{uuid}`。
- `allow-reclaim`:撤销后再次完成是否允许再次发奖,默认 `false`。
- `completion-message`:可选的个人完成消息。
后台队列先将奖励预约为 `RESERVED`,再持久化 `PENDING` 执行意图,之后才在主线程授予原版进度、发经验/物品和执行命令。成功落库为 `CLAIMED`;部分失败为 `FAILED`。
`RESERVED` 表示尚未执行,可以安全恢复;`PENDING` 与 `FAILED` 都不自动重放,即使 `allow-reclaim=true` 也一样。管理员应先备份数据库,查询 `reward_claims` 中的 `status`、`attempts`、`detail` 与日志,核查实际经验/物品/命令是否已执行,再人工补发欠缺部分。不要直接删除未决记录后重跑整份奖励。数据库事务不能与外部游戏命令形成绝对原子事务。
若数据库预约失败,玩家的原版节点不会提前完成,可以在数据库恢复后重试。管理命令异步返回实际完成结果。
## 命令与权限
主命令为 `/isa`,别名 `/itxiaohuiadvancements`。
| 命令 | 用途 |
|---|---|
| `/isa help` | 帮助 |
| `/isa list` / `/isa info <id>` | 查看定义 |
| `/isa editor` | 打开管理容器 GUI |
| `/isa give <在线玩家> <id>` | 手动完成并发奖 |
| `/isa revoke <在线玩家> <id>` | 撤销原版完成状态,不清统计 |
| `/isa progress <在线玩家>` | 查看完成数和内存统计 |
| `/isa create <id>` | 创建一个默认禁用的 YAML 骨架 |
| `/isa delete <id> confirm` | 检查子节点后删除定义;不清历史数据 |
| `/isa validate` | 校验磁盘配置 |
| `/isa reload` | 重载消息并校验;定义有变化时要求正常重启 |
| `/isa backup` | 刷盘、WAL checkpoint 并备份数据库 |
权限:
- `itxiaohui.serveradvancements.admin`:默认 OP,包含全部子权限。
- `itxiaohui.serveradvancements.give`
- `itxiaohui.serveradvancements.revoke`
- `itxiaohui.serveradvancements.view`
管理 GUI 的点击事件会再次执行服务端权限检查。复杂条件和奖励仍以 YAML 为准,GUI 提供浏览、详情、启停、给自己授予/撤销、重载和操作提示。
## SQLite 备份与恢复
数据库启用 WAL、FULL 同步、外键、busy timeout 和结构版本迁移。运行时 JDBC 操作统一走后台单线程队列。高频统计使用版本快照批量 UPSERT,读取失败时不以空缓存覆盖历史数据;未保存的重登缓存会被保留。离线且已保存的缓存会被淘汰。
退出、备份和正常停服会主动刷盘。进程在最近一次批量保存后被强杀,仍可能丢失尚在内存中的统计;周期可调低到 5 秒,但不能宣称任何崩溃都不丢数据。
备份:执行 `/isa backup`,后台先刷盘,再使用 SQLite `VACUUM INTO` 制作包含已提交 WAL 页的一致快照。每次创建独立目录,包含 `advancements.db` 以及三份 YAML;连续同秒请求不会覆盖或冲突。刷盘失败不会报备份成功。
恢复:
1. 使用 `stop` 正常关闭服务端。
2. 额外复制保存当前 `data/advancements.db` 及同目录的 `-wal`/`-shm`(若存在)。
3. 将选定备份复制为 `data/advancements.db`。
4. 确保没有遗留的旧 `advancements.db-wal`、`advancements.db-shm` 与新主库混用。
5. 启动服务端并检查完整性与插件日志。
不要在服务器运行时直接覆盖数据库。
## 架构
- `advancement`:不稳定动态注册 API 的唯一隔离层、原版进度授予/撤销。
- `config` / `model`:YAML 解析、校验、成就模型。
- `condition` / `listener`:行为统计和 AND 条件求值。
- `statistics` / `database`:内存缓存、异步批量持久化、迁移、奖励状态和审计。
- `reward`:防重复奖励执行。
- `command` / `gui`:权限受控的管理入口。
## 已知限制
1. `UnsafeValues.loadAdvancement/removeAdvancement` 在 Paper 1.21.8 已标记为不稳定/弃用;相关代码已集中隔离。定义更新采用正常重启流程。
2. 原版客户端决定节点坐标与未解锁深层节点的可见范围,插件不能通过标准 Advancement JSON 强制绝对 `x/y`。
3. `collect_item` 只统计地面拾取;不会虚假宣称覆盖交易、箱子、漏斗或命令来源。
4. 当前管理命令修改原版玩家进度只支持在线玩家;离线玩家统计仍保存在 SQLite,玩家下次进入后继续累计。
5. `/isa revoke` 不清累计统计;若玩家条件仍满足,后续求值会再次完成该成就。默认奖励防重仍会阻止重复发奖。
6. 条件依赖和父级关系一起做迭代环检测,树深度上限为 256;每个节点最多 64 条条件,物品奖励单项 1–4096 个、经验奖励 0–1000000,避免误配置耗尽资源。
从 1.0.0 升级:备份数据目录,使用 `stop` 正常关闭后替换 JAR 并启动;无需清空 SQLite 或玩家原版进度文件。旧的 PENDING/FAILED 记录会继续保留,按上面的核查流程处理,不会自动重复发放。
## 测试
使用 `./gradlew test securityAudit`(Windows 使用 `.\gradlew.bat test securityAudit`)运行单元和审计测试,报告位于 `build/reports/tests/`。
## 许可证
本项目按 [GNU GPL v3](LICENSE) 发布。随 JAR 分发的 SQLite JDBC 仍按其原有许可证发布,许可证声明位于 JAR 内的 `META-INF/maven/org.xerial/sqlite-jdbc/`。
+91
View File
@@ -0,0 +1,91 @@
plugins {
id 'java'
id 'jacoco'
id 'com.gradleup.shadow' version '8.3.6'
}
group = 'top.itxiaohui.serveradvancements'
version = '1.2.0'
repositories {
mavenCentral()
maven { url = 'https://repo.papermc.io/repository/maven-public/' }
}
dependencies {
compileOnly 'io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT'
implementation 'org.xerial:sqlite-jdbc:3.50.3.0'
testImplementation platform('org.junit:junit-bom:5.13.4')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation 'io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT'
testImplementation 'org.mockito:mockito-core:5.18.0'
}
sourceSets {
audit {
java.srcDir 'src/audit/java'
compileClasspath += sourceSets.main.output + configurations.testCompileClasspath + configurations.testRuntimeClasspath
runtimeClasspath += output + compileClasspath
}
probe {
java.srcDir 'src/probe/java'
resources.setSrcDirs(['src/probe/resources'])
compileClasspath += sourceSets.main.output + configurations.compileClasspath
}
}
tasks.register('securityAudit', Test) {
description = 'Security, robustness, persistence and abuse audit; failures identify unmet invariants.'
testClassesDirs = sourceSets.audit.output.classesDirs
classpath = sourceSets.audit.runtimeClasspath
useJUnitPlatform()
maxHeapSize = '1g'
testLogging { events 'passed', 'failed', 'skipped'; exceptionFormat 'short'; showStandardStreams = true }
finalizedBy 'auditCoverage'
}
jacoco { toolVersion = '0.8.13' }
tasks.register('auditCoverage', JacocoReport) {
executionData layout.buildDirectory.file('jacoco/securityAudit.exec')
sourceSets sourceSets.main
reports { xml.required = true; html.required = true }
}
tasks.register('probeJar', Jar) {
description = 'Isolated-server test probe only; never install on production.'
archiveFileName = 'ISA-AuditProbe.jar'
destinationDirectory = layout.buildDirectory.dir('audit-tools')
from sourceSets.probe.output
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(21)
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.release = 21
}
tasks.processResources {
inputs.property('pluginVersion', project.version)
filteringCharset = 'UTF-8'
filesMatching('plugin.yml') {
expand(version: project.version)
}
}
tasks.test {
useJUnitPlatform()
}
tasks.shadowJar {
archiveFileName = 'ItxiaohuiServerAdvancements.jar'
// JNI exports reference org.sqlite classes by their original names.
// The runtime loads this bundled driver in a dedicated child-first classloader.
}
tasks.jar { enabled = false }
tasks.build { dependsOn tasks.shadowJar }
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=false
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+8
View File
@@ -0,0 +1,8 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven { url = 'https://repo.papermc.io/repository/maven-public/' }
}
}
rootProject.name = 'ItxiaohuiServerAdvancements'
@@ -0,0 +1,30 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.model.*;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import static org.mockito.Mockito.*;
final class AuditSupport {
static JavaPlugin plugin(Path directory) {
JavaPlugin plugin = mock(JavaPlugin.class);
when(plugin.getDataFolder()).thenReturn(directory.toFile());
YamlConfiguration config = new YamlConfiguration();
config.set("database.busy-timeout-millis", 100);
when(plugin.getConfig()).thenReturn(config);
when(plugin.getLogger()).thenReturn(Logger.getLogger("ISA-Audit"));
return plugin;
}
static AchievementDefinition achievement(String id, ConditionDefinition... conditions) {
return new AchievementDefinition(id, id, "audit", "minecraft:stone", AdvancementFrame.TASK,
"root", 0, 0, List.of(conditions), false, false, false, true,
new RewardDefinition(0, List.of(), List.of(), false, ""));
}
static ConditionDefinition condition(ConditionType type, Map<String, Object> parameters) {
return new ConditionDefinition(type, parameters);
}
}
@@ -0,0 +1,150 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.*;
import org.bukkit.advancement.Advancement;
import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import top.itxiaohui.serveradvancements.condition.AutomaticConditions;
import top.itxiaohui.serveradvancements.condition.ConditionEngine;
import top.itxiaohui.serveradvancements.model.*;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.nio.file.Path;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class AutomaticConditionsAuditTest {
@TempDir Path directory;
final Player player = mock(Player.class);
final UUID id = UUID.randomUUID();
final StatisticsService statistics = mock(StatisticsService.class);
private ConditionDefinition condition(ConditionType type, Map<String,Object> parameters) {
when(player.getUniqueId()).thenReturn(id);
return new ConditionDefinition(type, parameters);
}
@Test void nativeDistanceKeepsCentimetres() {
when(player.getStatistic(Statistic.BOAT_ONE_CM)).thenReturn(300000);
assertEquals(300000, AutomaticConditions.current(player, condition(ConditionType.PLAYER_STATISTIC,
Map.of("statistic","BOAT_ONE_CM","amount",300000)), statistics));
}
@Test void nativeCraftGroupsSumDifferentBedColours() {
when(player.getStatistic(Statistic.CRAFT_ITEM, Material.RED_BED)).thenReturn(1);
when(player.getStatistic(Statistic.CRAFT_ITEM, Material.WHITE_BED)).thenReturn(2);
var c = condition(ConditionType.PLAYER_STATISTIC, Map.of("statistic","CRAFT_ITEM","materials",List.of("minecraft:red_bed","minecraft:white_bed")));
assertEquals(3, AutomaticConditions.current(player,c,statistics));
}
private ItemStack stack(Material material, int amount) {
ItemStack item=mock(ItemStack.class);
Material type=mock(Material.class);
when(type.isAir()).thenReturn(false);
when(type.getKey()).thenReturn(NamespacedKey.minecraft(material.name().toLowerCase(Locale.ROOT)));
when(item.getType()).thenReturn(type);when(item.getAmount()).thenReturn(amount);return item;
}
@Test void inventoryCountsKindsNotStacksAndRequiresPerKindQuantity() {
var inventory=mock(PlayerInventory.class);when(player.getInventory()).thenReturn(inventory);
ItemStack[] contents={stack(Material.DIAMOND,32),stack(Material.DIAMOND,32),stack(Material.EMERALD,1),null};
when(inventory.getContents()).thenReturn(contents);
var c=condition(ConditionType.INVENTORY_SET,Map.of("items",List.of("minecraft:diamond","minecraft:emerald"),"each",64,"amount",1));
assertEquals(1,AutomaticConditions.current(player,c,statistics));
}
@Test void inventoryWithoutRequiredItemsDoesNotComplete() {
var inventory=mock(PlayerInventory.class);when(player.getInventory()).thenReturn(inventory);
ItemStack[] contents={stack(Material.STONE,64)};
when(inventory.getContents()).thenReturn(contents);
var c=condition(ConditionType.INVENTORY_SET,Map.of("items",List.of("minecraft:diamond")));
assertEquals(0,AutomaticConditions.current(player,c,statistics));
}
@Test void distinctFoodCountsDoNotIncreaseForRepeatedSameFood() {
var c=condition(ConditionType.EVENT_DISTINCT,Map.of("event","eat_food","amount",10));
when(statistics.snapshot(id)).thenReturn(Map.of("event:eat_food:minecraft:apple",100D,"event:eat_food:minecraft:bread",1D,"event:cook_food:minecraft:cooked_beef",30D));
assertEquals(2,AutomaticConditions.current(player,c,statistics));
}
@Test void eventSubjectFilterDoesNotTreatOtherBlocksAsFlowers() {
var c=condition(ConditionType.EVENT_DISTINCT,Map.of("event","place_block","subjects",List.of("minecraft:poppy","minecraft:dandelion")));
when(statistics.snapshot(id)).thenReturn(Map.of("event:place_block:minecraft:stone",100D,"event:place_block:minecraft:poppy",10D));
assertEquals(1,AutomaticConditions.current(player,c,statistics));
}
@Test void eventCountSumsOnlySelectedAnimals() {
var c=condition(ConditionType.EVENT_COUNT,Map.of("event","tame_animal","subjects",List.of("minecraft:cat")));
when(statistics.snapshot(id)).thenReturn(Map.of("event:tame_animal:minecraft:cat",3D,"event:tame_animal:minecraft:wolf",10D));
assertEquals(3,AutomaticConditions.current(player,c,statistics));
}
@Test void structuresAreUniqueAndFilteredByStructureType() {
var c=condition(ConditionType.VISIT_STRUCTURE,Map.of("structures",List.of("minecraft:shipwreck","minecraft:shipwreck_beached")));
when(statistics.snapshot(id)).thenReturn(Map.of("structure:minecraft:shipwreck:world:0,0,0",1D,"structure:minecraft:shipwreck:world:100,0,0",1D,"structure:minecraft:mansion:world:0,0,0",1D));
assertEquals(2,AutomaticConditions.current(player,c,statistics));
}
@Test void nativeAdvancementMustActuallyBeDone() {
var c=condition(ConditionType.VANILLA_ADVANCEMENT,Map.of("advancement","minecraft:adventure/totem_of_undying"));
Advancement advancement=mock(Advancement.class);AdvancementProgress progress=mock(AdvancementProgress.class);
when(player.getAdvancementProgress(advancement)).thenReturn(progress);
try(var bukkit=mockStatic(Bukkit.class)) {
bukkit.when(()->Bukkit.getAdvancement(NamespacedKey.minecraft("adventure/totem_of_undying"))).thenReturn(advancement);
assertEquals(0,AutomaticConditions.current(player,c,statistics));
when(progress.isDone()).thenReturn(true);assertEquals(1,AutomaticConditions.current(player,c,statistics));
}
}
@Test void missingNativeAdvancementDoesNotComplete() {
var c=condition(ConditionType.VANILLA_ADVANCEMENT,Map.of("advancement","minecraft:adventure/missing"));
try(var bukkit=mockStatic(Bukkit.class)) { assertEquals(0,AutomaticConditions.current(player,c,statistics)); }
}
@Test void customNamespaceCannotCreateCircularNativeDependencies() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.VANILLA_ADVANCEMENT,
Map.of("advancement","itxiaohui_server_advancements:auto_loop"))).isEmpty());
}
@Test void unknownStatisticIsRejected() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","NOT_REAL"))).isEmpty());
}
@Test void typedStatisticRequiresMaterialList() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","CRAFT_ITEM"))).isEmpty());
}
@Test void untypedStatisticCannotSilentlyIgnoreMaterialList() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","JUMP","materials",List.of("minecraft:stone")))).isEmpty());
}
@Test void malformedSubjectListCannotBecomeUnfilteredCounter() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.EVENT_COUNT,Map.of("event","place_block","subjects","minecraft:poppy"))).isEmpty());
}
@Test void unknownServerEventIsRejected() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.EVENT_COUNT,Map.of("event","not_real"))).isEmpty());
}
@Test void invalidStructureNamespaceIsRejected() {
assertFalse(AutomaticConditions.validate(condition(ConditionType.VISIT_STRUCTURE,Map.of("structures",List.of("oops:not_real")))).isEmpty());
}
@Test void actionRecorderIgnoresUnknownOrNonPositiveInputs() {
var engine=new ConditionEngine(AuditSupport.plugin(directory),null,statistics,null,null);
engine.event(player,"not_real","minecraft:stone",1);
engine.event(player,"place_block","minecraft:stone",0);
engine.event(player,"place_block","minecraft:stone",-1);
verifyNoInteractions(statistics);
}
@Test void altitudeAndBiomeUsePersistedObservations() {
var c=condition(ConditionType.VISIT_BIOME,Map.of("biome","minecraft:cherry_grove"));
when(statistics.get(id,"visit_biome:minecraft:cherry_grove")).thenReturn(1D);
assertEquals(1,AutomaticConditions.current(player,c,statistics));
}
}
@@ -0,0 +1,150 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import top.itxiaohui.serveradvancements.config.BundledCatalogInstaller;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import top.itxiaohui.serveradvancements.config.StrictYaml;
import top.itxiaohui.serveradvancements.model.ConditionType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class BundledCatalogAuditTest {
@TempDir Path directory;
private YamlConfiguration resource(String name) throws Exception {
try (var input = getClass().getClassLoader().getResourceAsStream(name)) {
assertNotNull(input, name);
return StrictYaml.parse(new String(input.readAllBytes(), StandardCharsets.UTF_8), true);
}
}
@Test void automaticFirstCatalogLoadsAlongside17OriginalAchievements() throws Exception {
Path target = directory.resolve("advancements.yml");
StrictYaml.save(resource("advancements.yml"), target);
byte[] original = Files.readAllBytes(target);
var result = BundledCatalogInstaller.install(target, resource("fun-advancements.yml"));
assertEquals(134, result.added());
assertArrayEquals(original, Files.readAllBytes(result.backup()));
var plugin = AuditSupport.plugin(directory);
plugin.getConfig().set("root.id", "custom_root");
Material item = mock(Material.class);
when(item.isItem()).thenReturn(true);
when(item.isBlock()).thenReturn(true);
try (var materials = mockStatic(Material.class)) {
materials.when(() -> Material.matchMaterial(anyString())).thenReturn(item);
var loaded = new ConfigurationManager(plugin).load();
assertTrue(loaded.validation().valid(), loaded.validation().errors().toString());
assertEquals(151, loaded.definitions().size());
var fun = loaded.definitions().values().stream().filter(d -> d.id().startsWith("fun_") || d.id().startsWith("auto_")).toList();
assertEquals(134, fun.size());
long manual = fun.stream().filter(d -> d.conditions().stream().anyMatch(c -> c.type() == ConditionType.MANUAL)).count();
assertEquals(22, manual);
assertEquals(112, fun.size() - manual);
assertTrue(fun.stream().filter(d -> d.conditions().stream().anyMatch(c -> c.type() == ConditionType.MANUAL))
.allMatch(d -> !d.enabled() && d.description().contains("默认关闭")));
assertEquals(129, loaded.definitions().values().stream().filter(d -> d.enabled()).count());
assertTrue(fun.stream().allMatch(d -> !d.rewards().allowReclaim() && d.rewards().items().isEmpty()
&& d.rewards().commands().isEmpty() && d.rewards().experience() <= 100));
assertEquals(fun.size(), fun.stream().map(d -> d.name()).distinct().count());
}
}
@Test void existingSameIdAndCustomNodesRemainUnchanged() throws Exception {
var current = StrictYaml.parse("""
achievements:
fun_diamond_64:
name: 自定义钻石目标
enabled: false
conditions: [{type: manual}]
my_custom:
name: 管理员自己的成就
conditions: [{type: manual}]
""", true);
Path target = directory.resolve("advancements.yml");
StrictYaml.save(current, target);
assertEquals(133, BundledCatalogInstaller.install(target, resource("fun-advancements.yml")).added());
var saved = StrictYaml.read(target, true).getConfigurationSection("achievements");
assertEquals("自定义钻石目标", saved.getConfigurationSection("fun_diamond_64").getString("name"));
assertFalse(saved.getConfigurationSection("fun_diamond_64").getBoolean("enabled"));
assertEquals("管理员自己的成就", saved.getConfigurationSection("my_custom").getString("name"));
}
@Test void subsequentStartupDoesNotRewriteOrReinstallDeletedNodes() throws Exception {
Path target = directory.resolve("advancements.yml");
var catalog = resource("fun-advancements.yml");
BundledCatalogInstaller.install(target, catalog);
var current = StrictYaml.read(target, true);
current.getConfigurationSection("achievements").set("fun_diamond_64", null);
StrictYaml.save(current, target);
byte[] before = Files.readAllBytes(target);
var second = BundledCatalogInstaller.install(target, catalog);
assertEquals(0, second.added());
assertNull(second.backup());
assertArrayEquals(before, Files.readAllBytes(target));
}
@Test void duplicateYamlDoesNotGetOverwritten() throws Exception {
Path target = directory.resolve("advancements.yml");
String invalid = "achievements:\n duplicate: {}\n duplicate: {}\n";
Files.writeString(target, invalid);
assertThrows(IOException.class, () -> BundledCatalogInstaller.install(target, resource("fun-advancements.yml")));
assertEquals(invalid, Files.readString(target));
}
@Test void nonSectionAchievementsDoesNotGetOverwritten() throws Exception {
Path target = directory.resolve("advancements.yml");
String invalid = "achievements: do-not-overwrite\n";
Files.writeString(target, invalid);
assertThrows(IOException.class, () -> BundledCatalogInstaller.install(target, resource("fun-advancements.yml")));
assertEquals(invalid, Files.readString(target));
}
@Test void packagedCatalogIsInstalledThroughPluginResource() throws Exception {
var plugin = AuditSupport.plugin(directory);
when(plugin.getResource("fun-advancements.yml")).thenAnswer(invocation ->
getClass().getClassLoader().getResourceAsStream("fun-advancements.yml"));
assertEquals(134, BundledCatalogInstaller.install(plugin).added());
assertEquals(0, BundledCatalogInstaller.install(plugin).added());
}
@Test void missingPackagedCatalogFailsWithoutCreatingConfiguration() {
assertThrows(IOException.class, () -> BundledCatalogInstaller.install(AuditSupport.plugin(directory)));
assertFalse(Files.exists(directory.resolve("advancements.yml")));
}
@Test void version1UpgradeReplacesOnlyUnmodifiedTemplatesAndPreservesDeletedNodes() throws Exception {
Path target = directory.resolve("advancements.yml");
var previous = resource("fun-advancements-v1.yml");
BundledCatalogInstaller.install(target, previous);
var current = StrictYaml.read(target, true);
var achievements = current.getConfigurationSection("achievements");
achievements.getConfigurationSection("fun_three_cats").set("description", "服主自定义条件说明");
achievements.getConfigurationSection("fun_five_wolves").set("enabled", false);
achievements.set("fun_ice_spikes", null);
StrictYaml.save(current, target);
byte[] before = Files.readAllBytes(target);
var result = BundledCatalogInstaller.install(target, resource("fun-advancements.yml"));
assertEquals(60, result.added());
assertEquals(71, result.updated());
assertArrayEquals(before, Files.readAllBytes(result.backup()));
var saved = StrictYaml.read(target, true);
assertEquals(2, saved.getInt("bundled-fun-catalog-version"));
var nodes = saved.getConfigurationSection("achievements");
assertEquals("服主自定义条件说明", nodes.getConfigurationSection("fun_three_cats").getString("description"));
assertFalse(nodes.getConfigurationSection("fun_five_wolves").getBoolean("enabled"));
assertFalse(nodes.contains("fun_ice_spikes"));
assertEquals("player_statistic", nodes.getConfigurationSection("fun_first_bed").getMapList("conditions").getFirst().get("type"));
assertFalse(nodes.getConfigurationSection("fun_group_photo").getBoolean("enabled"));
assertEquals(0, BundledCatalogInstaller.install(target, resource("fun-advancements.yml")).updated());
}
}
@@ -0,0 +1,112 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.Material;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.MockedStatic;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import java.nio.file.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ConfigurationAuditTest {
@TempDir Path directory;
ConfigurationManager configuration;
MockedStatic<Material> materials;
@BeforeEach void setup() {
configuration=new ConfigurationManager(AuditSupport.plugin(directory));
Material item=mock(Material.class); when(item.isItem()).thenReturn(true);when(item.isBlock()).thenReturn(true);
materials=mockStatic(Material.class);
for(String key:List.of("minecraft:stone","minecraft:diamond","minecraft:emerald"))
materials.when(()->Material.matchMaterial(key)).thenReturn(item);
}
@AfterEach void cleanup() { materials.close(); }
ConfigurationManager.LoadResult yaml(String content) throws Exception {
Files.writeString(directory.resolve("advancements.yml"),content);
return configuration.load();
}
String node(String id,String parent,String condition) {
return " "+id+":\n name: test\n icon: minecraft:stone\n parent: "+parent+"\n conditions:\n - "+condition+"\n";
}
@Test void invalidIconRejected() throws Exception {
var result=yaml("achievements:\n"+node("safe","root","{type: manual}").replace("minecraft:stone","minecraft:not_real"));
assertFalse(result.validation().valid()); assertTrue(result.definitions().isEmpty());
}
@Test void unknownConditionRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("safe","root","{type: typo}")).validation().valid());
}
@Test void missingParentDetected() throws Exception {
assertFalse(yaml("achievements:\n"+node("safe","missing","{type: manual}")).validation().valid());
}
@Test void parentCycleDetected() throws Exception {
assertFalse(yaml("achievements:\n"+node("a","b","{type: manual}")+node("b","a","{type: manual}")).validation().valid());
}
@Test void completionDependencyCycleMustBeDetected() throws Exception {
assertFalse(yaml("achievements:\n"+node("a","root","{type: complete_achievement, achievement: b}")+node("b","root","{type: complete_achievement, achievement: a}")).validation().valid());
}
@Test void duplicateYamlIdMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("same","root","{type: manual}")+node("same","root","{type: first_join}")).validation().valid());
}
@Test void reservedRootCannotBeOrdinaryAchievement() throws Exception {
assertFalse(yaml("achievements:\n"+node("root","root","{type: first_join}")).validation().valid());
}
@Test void disabledParentMustNotSilentlyStrandEnabledChild() throws Exception {
assertFalse(yaml("achievements:\n"+node("parent","root","{type: manual}")+" enabled: false\n"+node("child","parent","{type: manual}")).validation().valid());
}
@Test void nanTargetMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("nan","root","{type: collect_item, item: 'minecraft:diamond', amount: .nan}")).validation().valid());
}
@Test void infinityTargetMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("inf","root","{type: online_time, amount: .inf}")).validation().valid());
}
@Test void unknownOnlineUnitMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("time","root","{type: online_time, amount: 10, unit: years_typo}")).validation().valid());
}
@Test void invalidEntityMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("mob","root","{type: kill_mob, entity: 'minecraft:not_real', amount: 1}")).validation().valid());
}
@Test void malformedNumericTargetMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("bad","root","{type: online_time, amount: banana}")).validation().valid());
}
@Test void regionWithoutCoordinatesMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("region","root","{type: reach_location}")).validation().valid());
}
@Test void negativeRewardMustBeRejected() throws Exception {
assertFalse(yaml("achievements:\n"+node("xp","root","{type: manual}")+" rewards: {experience: -100}\n").validation().valid());
}
@Test void dottedIdsMustRoundTripThroughCreateAndLoad() throws Exception {
assertTrue(configuration.createSkeleton("branch.one"));
assertTrue(configuration.load().definitions().containsKey("branch.one"),"YAML path separator must not split a legal resource ID");
}
@Test void rootIdChangeMustBeValidatedAndProtected() throws Exception {
var plugin=AuditSupport.plugin(directory);plugin.getConfig().set("root.id","custom_root");
var manager=new ConfigurationManager(plugin);
assertFalse(manager.createSkeleton("custom_root"),"Configured root must be reserved, not only the literal root");
}
@Test void invalidGraphNodesMustBeExcludedAtStartup() throws Exception {
var result=yaml("achievements:\n"+node("a","b","{type: manual}")+node("b","a","{type: manual}")+node("good","root","{type: manual}"));
configuration.applyValidSubset(result);
assertEquals(Set.of("good"),configuration.definitions().keySet());
}
@Test void validSiblingSurvivesLocallyInvalidNode() throws Exception {
var result=yaml("achievements:\n"+node("bad","root","{type: typo}")+node("good","root","{type: manual}"));
configuration.applyValidSubset(result); assertEquals(Set.of("good"),configuration.definitions().keySet());
}
@Test void bulkValidDefinitionsParseWithoutCrash() throws Exception {
StringBuilder input=new StringBuilder("achievements:\n");
for(int i=0;i<1000;i++) input.append(node("node_"+i,"root","{type: manual}"));
long started=System.nanoTime(); var result=yaml(input.toString());
assertTrue(result.validation().valid());assertEquals(1000,result.definitions().size());
System.out.printf(Locale.ROOT,"CONFIG_1000_NODES_MS=%.2f%n",(System.nanoTime()-started)/1e6);
}
@Test void deletingParentWithChildIsBlocked() throws Exception {
var result=yaml("achievements:\n"+node("a","root","{type: manual}")+node("b","a","{type: manual}"));
configuration.apply(result); assertFalse(configuration.delete("a").success());
}
@Test void deepTree10000MustNotOverflowStack() throws Exception {
StringBuilder input=new StringBuilder("achievements:\n");
for(int i=9999;i>=0;i--)input.append(node("n"+i,i==0?"root":"n"+(i-1),"{type: manual}"));
assertDoesNotThrow(()->yaml(input.toString()));
}
}
@@ -0,0 +1,149 @@
package top.itxiaohui.serveradvancements.audit;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class DatabaseAuditTest {
@TempDir Path directory;
DatabaseManager database;
@BeforeEach void open() throws Exception { database = new DatabaseManager(AuditSupport.plugin(directory)); database.open(); }
@AfterEach void close() throws Exception { database.close(); }
@Test void sqlInjectionRemainsData() throws Exception {
UUID player = UUID.randomUUID();
String key = "x'); DROP TABLE player_statistics; --";
database.saveStatistics(Map.of(player, Map.of(key, 123D)));
assertEquals(123D, database.loadStatistics(player).get(key));
database.audit("actor'", "INJECTION", "target", "'); DROP TABLE reward_claims; --");
assertEquals(DatabaseManager.RewardStatus.NONE, database.rewardStatus(player, key));
}
@Test void oneRewardReservationUnder64ConcurrentCalls() throws Exception {
ExecutorService workers = Executors.newFixedThreadPool(8);
UUID player = UUID.randomUUID();
AtomicInteger reserved = new AtomicInteger();
try {
List<Callable<Void>> tasks = new ArrayList<>();
for (int i=0;i<64;i++) tasks.add(() -> { if(database.beginReward(player,"one", false)) reserved.incrementAndGet(); return null; });
for(Future<Void> task:workers.invokeAll(tasks)) task.get();
} finally { workers.shutdownNow(); }
assertEquals(1, reserved.get());
}
@Test void claimedRewardSurvivesReopen() throws Exception {
UUID player = UUID.randomUUID();
assertTrue(database.beginReward(player,"one",false));
database.finishReward(player,"one",true,"ok");
database.close(); database.open();
assertFalse(database.beginReward(player,"one",false));
assertEquals(DatabaseManager.RewardStatus.CLAIMED,database.rewardStatus(player,"one"));
}
@Test void pendingRewardMustBlockEvenWhenReclaimEnabled() throws Exception {
UUID player = UUID.randomUUID();
assertTrue(database.beginReward(player,"crash",true));
database.close(); database.open();
assertFalse(database.beginReward(player,"crash",true), "Unresolved PENDING must not be replayed, including allow-reclaim=true");
}
@Test void partiallyFailedRewardMustNotAutomaticallyReplayWholeReward() throws Exception {
UUID player = UUID.randomUUID();
assertTrue(database.beginReward(player,"partial",false));
database.finishReward(player,"partial",false,"XP delivered, command failed");
assertFalse(database.beginReward(player,"partial",false), "FAILED may have already delivered XP/items and requires manual reconciliation");
}
@Test void writerLockFailsWithoutOverwritingPersistedStatistics() throws Exception {
UUID player = UUID.randomUUID();
database.saveStatistics(Map.of(player,Map.of("stone",5D)));
try(Connection external=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath()); Statement lock=external.createStatement()) {
lock.execute("BEGIN IMMEDIATE");
long started=System.nanoTime();
assertThrows(SQLException.class,()->database.saveStatistics(Map.of(player,Map.of("stone",99D))));
double millis=(System.nanoTime()-started)/1e6;
System.out.printf(Locale.ROOT,"SQLITE_LOCK_FAILURE_MS=%.2f%n",millis);
lock.execute("ROLLBACK");
}
assertEquals(5D,database.loadStatistics(player).get("stone"));
}
@Test void backupContainsCommittedDataAndPassesIntegrityCheck() throws Exception {
UUID player=UUID.randomUUID();
database.saveStatistics(Map.of(player,Map.of("stat",42D)));
Path backup=database.backup();
try(Connection copy=DriverManager.getConnection("jdbc:sqlite:"+backup); Statement sql=copy.createStatement()) {
try(ResultSet result=sql.executeQuery("PRAGMA integrity_check")) { assertEquals("ok",result.getString(1)); }
try(ResultSet result=sql.executeQuery("SELECT value FROM player_statistics")) { assertEquals(42D,result.getDouble(1)); }
}
}
@Test void sameSecondBackupRequestsMustNotCollide() throws Exception {
// Repeated immediate calls are intentional: administrators can double-click or automate backups.
for(int i=0;i<3;i++) assertTrue(Files.exists(database.backup()));
}
@Test void corruptedDatabaseStopsInitialization() throws Exception {
Path corrupt=directory.resolve("corrupt/data"); Files.createDirectories(corrupt);
Files.writeString(corrupt.resolve("advancements.db"),"THIS IS NOT SQLITE");
DatabaseManager broken=new DatabaseManager(AuditSupport.plugin(directory.resolve("corrupt")));
assertThrows(SQLException.class,broken::open);
try {
assertDoesNotThrow(broken::close,"Initialization failure must still release the JDBC file handle");
} finally {
var field=DatabaseManager.class.getDeclaredField("connection");field.setAccessible(true);
Connection leaked=(Connection)field.get(broken);if(leaked!=null&&!leaked.isClosed())leaked.close();
}
}
@Test void futureSchemaRejectedWithoutDeletingExistingData() throws Exception {
database.close();
try(Connection raw=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath());Statement sql=raw.createStatement()) {
sql.executeUpdate("UPDATE schema_version SET version=99");
}
assertThrows(SQLException.class,database::open);
}
@Test void batch100000CountersBenchmark() throws Exception {
Map<UUID,Map<String,Double>> batch=new HashMap<>();
for(int player=0;player<1000;player++) {
Map<String,Double> stats=new HashMap<>();
for(int key=0;key<100;key++) stats.put("key:"+key,(double)key);
batch.put(UUID.randomUUID(),stats);
}
long started=System.nanoTime();database.saveStatistics(batch);
double millis=(System.nanoTime()-started)/1e6;
try(Connection raw=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath());Statement sql=raw.createStatement();ResultSet result=sql.executeQuery("SELECT count(*) FROM player_statistics")) {
assertEquals(100_000,result.getInt(1));
}
System.out.printf(Locale.ROOT,"SQLITE_BATCH rows=100000 elapsed_ms=%.2f rows_per_second=%.0f%n",millis,100_000_000D/millis);
}
@Test void unexecutedReservationCanResumeButPendingCannot() throws Exception {
UUID id=UUID.randomUUID();
assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false));
assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false));
assertTrue(database.startReward(id,"resume"));
assertEquals(DatabaseManager.Reservation.REVIEW_REQUIRED,database.reserveReward(id,"resume",true));
database.releaseUnexecutedReward(id,"resume");
assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false));
}
@Test void reclaimOnlyStartsNewAttemptAfterConfirmedClaim() throws Exception {
UUID id=UUID.randomUUID();database.reserveReward(id,"reclaim",false);database.startReward(id,"reclaim");database.finishReward(id,"reclaim",true,"ok");
assertEquals(DatabaseManager.Reservation.NO_REWARD,database.reserveReward(id,"reclaim",false));
assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"reclaim",true));
}
@Test void databaseQueueRunsOnWorkerAndReturnsWithoutBlockingCaller() throws Exception {
CountDownLatch entered=new CountDownLatch(1),release=new CountDownLatch(1);Thread caller=Thread.currentThread();
try {
var future=database.submit(()->{assertNotSame(caller,Thread.currentThread());entered.countDown();assertTrue(release.await(5,TimeUnit.SECONDS));return 7;});
assertTrue(entered.await(5,TimeUnit.SECONDS));assertFalse(future.isDone());
release.countDown();assertEquals(7,future.get(5,TimeUnit.SECONDS));
} finally {release.countDown();}
}
}
@@ -0,0 +1,165 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.MockedStatic;
import top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements;
import top.itxiaohui.serveradvancements.advancement.AdvancementManager;
import top.itxiaohui.serveradvancements.command.IsaCommand;
import top.itxiaohui.serveradvancements.condition.ConditionEngine;
import top.itxiaohui.serveradvancements.config.*;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import top.itxiaohui.serveradvancements.gui.AdminGui;
import top.itxiaohui.serveradvancements.listener.PlayerActivityListener;
import top.itxiaohui.serveradvancements.model.*;
import top.itxiaohui.serveradvancements.reward.RewardService;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.lang.reflect.*;
import java.nio.file.Path;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class LogicSecurityAuditTest {
@TempDir Path directory;
@ParameterizedTest @ValueSource(strings={"give","revoke","progress","editor","reload","create","delete","validate","backup"})
void unprivilegedCommandsMustNeverReachPrivilegedServices(String subcommand) {
ItxiaohuiServerAdvancements plugin=mock(ItxiaohuiServerAdvancements.class);
ConfigurationManager configuration=mock(ConfigurationManager.class);
MessageService messages=mock(MessageService.class);
CommandSender sender=mock(CommandSender.class);
new IsaCommand(plugin,configuration,messages).onCommand(sender,mock(Command.class),"isa",new String[]{subcommand,"victim","first_log","confirm"});
verify(messages).send(sender,"no-permission");verifyNoInteractions(plugin,configuration);
}
@Test void adminTabCompletionMustBePermissionFiltered() {
ItxiaohuiServerAdvancements plugin=mock(ItxiaohuiServerAdvancements.class);
var results=new IsaCommand(plugin,mock(ConfigurationManager.class),mock(MessageService.class))
.onTabComplete(mock(CommandSender.class),mock(Command.class),"isa",new String[]{""});
assertFalse(results.contains("backup"),"Unprivileged completion exposes admin commands (information disclosure only)");
}
@Test void guiRechecksPermissionAfterMenuWasOpened() throws Exception {
JavaPlugin plugin=AuditSupport.plugin(directory);
ConfigurationManager configuration=mock(ConfigurationManager.class);
AdvancementManager advancements=mock(AdvancementManager.class);
ConditionEngine conditions=mock(ConditionEngine.class);
Class<?> holderClass=Class.forName(AdminGui.class.getName()+"$Holder");
Constructor<?> constructor=holderClass.getDeclaredConstructor(int.class);constructor.setAccessible(true);
InventoryHolder holder=(InventoryHolder)constructor.newInstance(0);
Inventory inventory=mock(Inventory.class);when(inventory.getHolder(false)).thenReturn(holder);
InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(inventory);
Player player=mock(Player.class);when(click.getWhoClicked()).thenReturn(player);when(click.getRawSlot()).thenReturn(0);
new AdminGui(plugin,configuration,advancements,conditions).onClick(click);
verify(click).setCancelled(true);verify(player).closeInventory();verifyNoInteractions(configuration,advancements,conditions);
}
@Test void arbitraryInventoryCannotInvokeAdminActions() {
ConfigurationManager configuration=mock(ConfigurationManager.class);
AdvancementManager advancements=mock(AdvancementManager.class);
ConditionEngine conditions=mock(ConditionEngine.class);
Inventory inventory=mock(Inventory.class);when(inventory.getHolder(false)).thenReturn(mock(InventoryHolder.class));
InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(inventory);
new AdminGui(AuditSupport.plugin(directory),configuration,advancements,conditions).onClick(click);
verifyNoInteractions(configuration,advancements,conditions);
}
@Test void noOpCraftCannotIncreaseCraftOrObtainCounters() {
ConditionEngine conditions=mock(ConditionEngine.class);
CraftItemEvent craft=mock(CraftItemEvent.class);Player player=mock(Player.class);
ItemStack stack=mock(ItemStack.class);when(stack.getAmount()).thenReturn(4);when(stack.getType()).thenReturn(Material.DIAMOND);
when(craft.getWhoClicked()).thenReturn(player);when(craft.getCurrentItem()).thenReturn(stack);when(craft.getAction()).thenReturn(InventoryAction.NOTHING);
new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class)).onCraft(craft);
verifyNoInteractions(conditions);
}
@Test void andConditionsRequireEveryCounter() {
JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class);
StatisticsService stats=mock(StatisticsService.class);AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class);
Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);
when(stats.isReady(id)).thenReturn(true);
var definition=AuditSupport.achievement("both",AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",10)),
AuditSupport.condition(ConditionType.KILL_MOB,Map.of("entity","minecraft:zombie","amount",2)));
when(config.definitions()).thenReturn(Map.of("both",definition));when(stats.get(id,"mine_block:minecraft:stone")).thenReturn(10D);
new ConditionEngine(plugin,config,stats,advancements,rewards).evaluate(player);
verify(advancements,never()).award(any(),anyString());verify(rewards,never()).complete(any(),any(),any(),any());
}
@Test void nanTargetCannotAutoCompleteWithoutAnyProgress() {
JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class);
StatisticsService stats=mock(StatisticsService.class);AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class);
Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);when(stats.isReady(id)).thenReturn(true);
var definition=AuditSupport.achievement("nan",AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",Double.NaN)));
when(config.definitions()).thenReturn(Map.of("nan",definition));
new ConditionEngine(plugin,config,stats,advancements,rewards).evaluate(player);
verify(advancements,never()).award(any(),anyString());
}
@Test void partialRewardFailureMustNotDuplicateExperience() throws Exception {
JavaPlugin plugin=AuditSupport.plugin(directory);DatabaseManager database=new DatabaseManager(plugin);database.open();
try(MockedStatic<Bukkit> bukkit=mockStatic(Bukkit.class)) {
ConsoleCommandSender console=mock(ConsoleCommandSender.class);bukkit.when(Bukkit::getConsoleSender).thenReturn(console);
Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.getName()).thenReturn("AuditPlayer");when(player.isOnline()).thenReturn(true);
var reward=new RewardDefinition(100,List.of(),List.of("missing_command"),false,"");
var definition=new AchievementDefinition("partial","partial","","minecraft:stone",AdvancementFrame.TASK,"root",0,0,List.of(),false,false,false,true,reward);
java.util.concurrent.BlockingQueue<Runnable> main=new java.util.concurrent.LinkedBlockingQueue<>();
RewardService rewards=new RewardService(plugin,database,mock(MessageService.class),main::add);
var first=rewards.grant(player,definition);
Runnable action=main.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(action);action.run();
assertEquals(RewardService.Outcome.REVIEW_REQUIRED,first.get(5,java.util.concurrent.TimeUnit.SECONDS));
assertEquals(RewardService.Outcome.REVIEW_REQUIRED,rewards.grant(player,definition).get(5,java.util.concurrent.TimeUnit.SECONDS));
verify(player,times(1)).giveExp(100);
} finally { database.close(); }
}
@Test void rewardCommandRejectsNewlineAndSanitizesPlayerPlaceholder() throws Exception {
RewardService service=new RewardService(AuditSupport.plugin(directory),mock(DatabaseManager.class),mock(MessageService.class));
Method render=RewardService.class.getDeclaredMethod("renderCommand",String.class,Player.class);render.setAccessible(true);
Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.getName()).thenReturn("name\nstop; @a");
assertEquals("give namestopa minecraft:stone",render.invoke(service,"/give {player} minecraft:stone",player));
InvocationTargetException thrown=assertThrows(InvocationTargetException.class,()->render.invoke(service,"say hi\nstop",player));
assertInstanceOf(IllegalArgumentException.class,thrown.getCause());
}
@Test void subBlockWalkingDistanceMustBeCounted() {
Player player=mock(Player.class);World world=mock(World.class);ConditionEngine conditions=mock(ConditionEngine.class);
var listener=new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class));
listener.onMove(new org.bukkit.event.player.PlayerMoveEvent(player,new Location(world,0.1,64,0.1),new Location(world,0.9,64,0.1)));
verify(conditions).record(eq(player),eq(ConditionType.MOVE_DISTANCE),eq(""),eq(0.8));
}
@Test void successfulNativeCraftStatisticCountsExactDelta() {
ConditionEngine conditions=mock(ConditionEngine.class);Player player=mock(Player.class);
var listener=new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class));
var event=new org.bukkit.event.player.PlayerStatisticIncrementEvent(player,Statistic.CRAFT_ITEM,20,24,Material.OAK_PLANKS);
listener.onStatistic(event);
verify(conditions).record(player,ConditionType.CRAFT_ITEM,"minecraft:oak_planks",4);
verify(conditions).record(player,ConditionType.OBTAIN_ITEM,"minecraft:oak_planks",4);
}
@Test void reachedRegionRemainsSatisfiedAfterPlayerLeaves() {
JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class);
StatisticsService stats=new StatisticsService(plugin,mock(DatabaseManager.class));
AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class);
Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);stats.load(id);
World world=mock(World.class);when(world.getName()).thenReturn("world");when(world.getKey()).thenReturn(NamespacedKey.minecraft("overworld"));
when(player.getLocation()).thenReturn(new Location(world,0,64,0));
var region=AuditSupport.condition(ConditionType.REACH_LOCATION,Map.of("world","world","x",0,"y",64,"z",0,"radius",2));
var mine=AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",10));
var definition=AuditSupport.achievement("region",region,mine);when(config.definitions()).thenReturn(Map.of("region",definition));
var engine=new ConditionEngine(plugin,config,stats,advancements,rewards);engine.evaluate(player);
assertEquals(1D,stats.get(id,region.statisticKey()));verify(rewards,never()).complete(any(),any(),any(),any());
when(player.getLocation()).thenReturn(new Location(world,100,64,100));stats.increment(id,"mine_block:minecraft:stone",10);engine.evaluate(player);
verify(rewards).complete(eq(player),eq(definition),any(),any());
}
@Test void reservationFailureNeverAwardsNativeProgressOrRewards() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);
var pending=new java.util.concurrent.CompletableFuture<DatabaseManager.Reservation>();
when(database.submit(any())).thenAnswer(invocation->pending);
Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.isOnline()).thenReturn(true);
var awarded=new java.util.concurrent.atomic.AtomicBoolean();
RewardService service=new RewardService(AuditSupport.plugin(directory),database,mock(MessageService.class),Runnable::run);
var request=service.complete(player,AuditSupport.achievement("locked"),()->{awarded.set(true);return true;},()->{});
assertFalse(awarded.get());assertFalse(request.isDone());
pending.completeExceptionally(new java.sql.SQLException("database locked"));
assertEquals(RewardService.Outcome.RETRY_LATER,request.get(1,java.util.concurrent.TimeUnit.SECONDS));
assertFalse(awarded.get());verify(player,never()).giveExp(anyInt());
}
}
@@ -0,0 +1,93 @@
package top.itxiaohui.serveradvancements.audit;
import org.bukkit.entity.Player;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class StatisticsAuditTest {
@TempDir Path directory;
void flush(StatisticsService service) throws Exception {
Method flush=StatisticsService.class.getDeclaredMethod("flushAsyncBody");flush.setAccessible(true);flush.invoke(service);
}
@Test void fastRejoinMustPreserveDirtyInMemoryCounters() {
DatabaseManager database=mock(DatabaseManager.class);
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);
UUID id=UUID.randomUUID(); stats.load(id);stats.increment(id,"diamond",64);stats.load(id);
assertEquals(64D,stats.get(id,"diamond"),"Rejoin must not overwrite dirty cache with a stale DB snapshot");
}
@Test void readFailureMustNotCreateWritableZeroBaseline() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);when(database.loadStatistics(any())).thenThrow(new SQLException("database locked"));
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);
UUID id=UUID.randomUUID(); stats.load(id);stats.increment(id,"diamond",1);flush(stats);
verify(database,never()).saveStatistics(anyMap());
}
@Test void failedBatchRemainsDirtyAndIsRetried() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);
doThrow(new SQLException("disk full")).doNothing().when(database).saveStatistics(anyMap());
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);
stats.increment(UUID.randomUUID(),"stone",10);flush(stats);flush(stats);
verify(database,times(2)).saveStatistics(anyMap());
}
@Test void cacheAcceptsConcurrent80000IncrementsWithoutLostCount() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);
UUID id=UUID.randomUUID(); ExecutorService workers=Executors.newFixedThreadPool(8);
try {
List<Callable<Void>> tasks=new ArrayList<>();
for(int w=0;w<8;w++) tasks.add(()->{for(int i=0;i<10000;i++)stats.increment(id,"stone",1);return null;});
for(var task:workers.invokeAll(tasks))task.get();
} finally { workers.shutdownNow(); }
assertEquals(80_000D,stats.get(id,"stone"));flush(stats);
verify(database).saveStatistics(Map.of(id,Map.of("stone",80000D)));
}
@Test void nonFiniteCountersMustNotEnterPersistence() {
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),mock(DatabaseManager.class));
UUID id=UUID.randomUUID();stats.increment(id,"poison",Double.NaN);
assertTrue(Double.isFinite(stats.get(id,"poison")),"NaN poisons comparisons and SQLite NULL handling");
}
@Test void duplicateSessionStartMustNotDiscardElapsedTimeOrStats() throws Exception {
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),mock(DatabaseManager.class));
Player player=mock(Player.class); UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);
stats.beginSession(player);stats.increment(id,"mine",25);stats.beginSession(player);
assertEquals(25D,stats.get(id,"mine"));
}
@Test void incrementRacingWithFlushMustRemainDirty() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);UUID id=UUID.randomUUID();
CountDownLatch enteredSave=new CountDownLatch(1),allowSave=new CountDownLatch(1);
stats.load(id);stats.increment(id,"stone",1);
doAnswer(invocation->{enteredSave.countDown();assertTrue(allowSave.await(5,TimeUnit.SECONDS));return null;}).when(database).saveStatistics(anyMap());
ExecutorService worker=Executors.newSingleThreadExecutor();
try {
Future<?> saving=worker.submit(()->{try{flush(stats);}catch(Exception e){throw new RuntimeException(e);}});
assertTrue(enteredSave.await(5,TimeUnit.SECONDS));stats.increment(id,"stone",1);
allowSave.countDown();saving.get();flush(stats);
verify(database).saveStatistics(Map.of(id,Map.of("stone",2D)));
} finally { allowSave.countDown();worker.shutdownNow(); }
}
@Test void recoveringReadMergesQueuedIncrementOntoHistoricalBaseline() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);UUID id=UUID.randomUUID();
when(database.loadStatistics(id)).thenThrow(new SQLException("temporarily unavailable")).thenReturn(Map.of("stone",100D));
StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);
stats.load(id);stats.increment(id,"stone",3);assertFalse(stats.isReady(id));flush(stats);
verify(database).saveStatistics(Map.of(id,Map.of("stone",103D)));
}
@Test void onlinePlayerCacheRemainsWhenOnlineTimeIsDisabled() throws Exception {
DatabaseManager database=mock(DatabaseManager.class);
when(database.submit(any())).thenAnswer(invocation->{java.util.concurrent.Callable<?> action=invocation.getArgument(0);return CompletableFuture.completedFuture(action.call());});
var plugin=AuditSupport.plugin(directory);plugin.getConfig().set("statistics.online-time-enabled",false);
StatisticsService stats=new StatisticsService(plugin,database);Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);
stats.beginSession(player).get();stats.increment(id,"stone",5);flush(stats);
assertTrue(stats.isReady(id));assertEquals(5D,stats.get(id,"stone"));
stats.endSession(id);flush(stats);assertEquals(0,stats.cachedPlayerCount());
}
}
@@ -0,0 +1,151 @@
package top.itxiaohui.serveradvancements;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.advancement.AdvancementManager;
import top.itxiaohui.serveradvancements.command.IsaCommand;
import top.itxiaohui.serveradvancements.condition.ConditionEngine;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import top.itxiaohui.serveradvancements.config.MessageService;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import top.itxiaohui.serveradvancements.gui.AdminGui;
import top.itxiaohui.serveradvancements.listener.PlayerActivityListener;
import top.itxiaohui.serveradvancements.reward.RewardService;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.io.File;
import java.sql.SQLException;
import java.util.Map;
import top.itxiaohui.serveradvancements.config.StrictYaml;
import top.itxiaohui.serveradvancements.config.BundledCatalogInstaller;
import org.bukkit.configuration.ConfigurationSection;
public final class ItxiaohuiServerAdvancements extends JavaPlugin {
private DatabaseManager database;
private StatisticsService statistics;
private ConfigurationManager configuration;
private MessageService messages;
private AdvancementManager advancementManager;
private RewardService rewardService;
private ConditionEngine conditionEngine;
private AdminGui adminGui;
@Override public void onEnable() {
saveDefaultConfig();
saveBundled("advancements.yml");
saveBundled("messages.yml");
try {
StrictYaml.read(new File(getDataFolder(), "config.yml").toPath(), false);
String icon = getConfig().getString("root.icon", "minecraft:nether_star");
var material = org.bukkit.Material.matchMaterial(icon);
if (material == null || !material.isItem() || org.bukkit.NamespacedKey.fromString(getConfig().getString("root.background", "minecraft:textures/block/deepslate_tiles.png")) == null)
throw new IllegalArgumentException("根进度图标或背景非法");
} catch (Exception error) { getLogger().severe("全局配置非法: " + error.getMessage()); getServer().getPluginManager().disablePlugin(this); return; }
String rootId = getConfig().getString("root.id", "root");
if (!ConfigurationManager.validId(rootId)) { getLogger().severe("root.id 非法,插件已停止;请修复后正常重启"); getServer().getPluginManager().disablePlugin(this); return; }
try {
var catalog = BundledCatalogInstaller.install(this);
if (catalog.backup() != null) getLogger().info("趣味成就补入 " + catalog.added() + " 项,升级未修改模板 " + catalog.updated() + " 项,原配置备份: " + catalog.backup());
} catch (Exception error) {
getLogger().severe("趣味成就安装失败,为保护配置插件将停用: " + error.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
try {
database = new DatabaseManager(this);
database.open();
} catch (Exception | LinkageError exception) {
getLogger().severe("SQLite 初始化失败,为保护数据插件将停用: " + exception.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
messages = new MessageService(this);
configuration = new ConfigurationManager(this);
ConfigurationManager.LoadResult initial = configuration.load();
configuration.applyValidSubset(initial);
logValidation(initial);
advancementManager = new AdvancementManager(this);
AdvancementManager.RegistrationResult registered = advancementManager.registerAll(configuration.definitions());
registered.errors().forEach(error -> getLogger().severe("Advancement 注册错误: " + error));
statistics = new StatisticsService(this, database);
statistics.start();
rewardService = new RewardService(this, database, messages);
conditionEngine = new ConditionEngine(this, configuration, statistics, advancementManager, rewardService);
adminGui = new AdminGui(this, configuration, advancementManager, conditionEngine);
getServer().getPluginManager().registerEvents(new PlayerActivityListener(this, statistics, conditionEngine, advancementManager), this);
getServer().getPluginManager().registerEvents(adminGui, this);
IsaCommand command = new IsaCommand(this, configuration, messages);
PluginCommand isa = getCommand("isa");
if (isa == null) throw new IllegalStateException("plugin.yml 未注册 isa 命令");
isa.setExecutor(command);
isa.setTabCompleter(command);
Bukkit.getScheduler().runTaskTimer(this, () -> {
statistics.updateOnlineSessions();
for (Player player : Bukkit.getOnlinePlayers()) {
conditionEngine.observeEnvironment(player);
conditionEngine.evaluate(player);
}
}, 200L, 200L);
getLogger().info("已启用:注册 " + registered.count() + " 个原版进度(含根进度),SQLite=" + database.databasePath());
}
private void saveBundled(String name) {
File file = new File(getDataFolder(), name);
if (!file.exists()) saveResource(name, false);
}
public boolean reloadDefinitions(CommandSender sender) {
try {
var global = StrictYaml.read(new File(getDataFolder(), "config.yml").toPath(), false);
Map<String, Object> current = new java.util.HashMap<>(getConfig().getValues(true));
Map<String, Object> next = new java.util.HashMap<>(global.getValues(true));
current.values().removeIf(value -> value instanceof ConfigurationSection);
next.values().removeIf(value -> value instanceof ConfigurationSection);
if (!current.equals(next)) { messages.send(sender, "reload-restart-required"); return false; }
} catch (Exception error) { getLogger().severe("config.yml 校验失败: " + error.getMessage()); messages.send(sender, "reload-failed"); return false; }
messages.reload();
ConfigurationManager.LoadResult candidate = configuration.load();
if (!candidate.validation().valid()) {
logValidation(candidate);
messages.send(sender, "reload-failed");
return false;
}
if (!candidate.definitions().equals(configuration.definitions())) {
messages.send(sender, "reload-restart-required");
return false;
}
configuration.apply(candidate);
messages.send(sender, "reloaded", Map.of("count", configuration.definitions().size()));
return true;
}
private void logValidation(ConfigurationManager.LoadResult result) {
result.validation().errors().forEach(error -> getLogger().severe(error));
result.validation().warnings().stream().distinct().forEach(warning -> getLogger().warning(warning));
if (!result.validation().valid()) getLogger().warning("无效成就已隔离;其余解析成功的定义将继续运行。请执行 /isa validate 查看。 ");
}
@Override public void onDisable() {
if (rewardService != null) rewardService.close();
try { if (statistics != null) statistics.close(); }
catch (Exception error) { getLogger().severe("关闭时统计刷盘失败,请保留数据目录: " + error.getMessage()); }
finally {
if (advancementManager != null) advancementManager.unregisterAll();
if (database != null) {
try { database.close(); }
catch (SQLException exception) { getLogger().severe("关闭 SQLite 失败: " + exception.getMessage()); }
}
}
}
public DatabaseManager database() { return database; }
public StatisticsService statistics() { return statistics; }
public AdvancementManager advancementManager() { return advancementManager; }
public ConditionEngine conditionEngine() { return conditionEngine; }
public AdminGui adminGui() { return adminGui; }
}
@@ -0,0 +1,193 @@
package top.itxiaohui.serveradvancements.advancement;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.advancement.Advancement;
import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.model.AchievementDefinition;
import java.util.*;
import java.util.logging.Level;
@SuppressWarnings("deprecation")
public final class AdvancementManager {
public static final String NAMESPACE = "itxiaohui_server_advancements";
private static final String CRITERION = "completed";
private final JavaPlugin plugin;
private final Set<NamespacedKey> registered = new LinkedHashSet<>();
private String rootId;
public AdvancementManager(JavaPlugin plugin) { this.plugin = plugin; }
public RegistrationResult registerAll(Map<String, AchievementDefinition> definitions) {
Map<UUID, Set<String>> completed = captureOnlineProgress();
unregisterAll();
rootId = plugin.getConfig().getString("root.id", "root");
List<String> errors = new ArrayList<>();
tryLoad(key(rootId), rootJson(), errors);
for (AchievementDefinition definition : sorted(definitions)) {
if (!definition.enabled()) continue;
tryLoad(key(definition.id()), advancementJson(definition), errors);
}
Bukkit.getServer().updateResources();
Bukkit.getScheduler().runTaskLater(plugin, () -> {
for (Player player : Bukkit.getOnlinePlayers()) {
ensureRoot(player);
for (String id : completed.getOrDefault(player.getUniqueId(), Set.of())) award(player, id);
}
}, 2L);
return new RegistrationResult(registered.size(), List.copyOf(errors));
}
private void tryLoad(NamespacedKey key, String json, List<String> errors) {
try {
Advancement existing = Bukkit.getAdvancement(key);
if (existing != null) {
registered.add(key);
plugin.getLogger().warning("检测到启动前已存在的进度 " + key + ";沿用当前定义。若刚修改配置,请正常停止并再次启动服务器。");
return;
}
Advancement loaded = Bukkit.getUnsafe().loadAdvancement(key, json);
if (loaded == null) errors.add(key + ": Paper 返回 null");
else registered.add(key);
} catch (RuntimeException exception) {
errors.add(key + ": " + exception.getMessage());
plugin.getLogger().log(Level.SEVERE, "注册原版进度失败: " + key, exception);
}
}
private List<AchievementDefinition> sorted(Map<String, AchievementDefinition> definitions) {
List<AchievementDefinition> result = new ArrayList<>();
Set<String> added = new HashSet<>();
while (result.size() < definitions.size()) {
boolean progressed = false;
List<AchievementDefinition> candidates = definitions.values().stream()
.filter(AchievementDefinition::enabled)
.filter(d -> !added.contains(d.id()))
.filter(d -> d.parent().equals("root") || added.contains(d.parent()))
.sorted(Comparator.comparingDouble(AchievementDefinition::x)
.thenComparingDouble(AchievementDefinition::y).thenComparing(AchievementDefinition::id))
.toList();
for (AchievementDefinition candidate : candidates) {
result.add(candidate);
added.add(candidate.id());
progressed = true;
}
if (!progressed) break;
}
return result;
}
private String rootJson() {
JsonObject root = baseJson();
JsonObject display = new JsonObject();
display.add("icon", icon(plugin.getConfig().getString("root.icon", "minecraft:nether_star")));
display.addProperty("title", plugin.getConfig().getString("root.title", "服务器成就树"));
display.addProperty("description", plugin.getConfig().getString("root.description", "记录服务器冒险"));
display.addProperty("background", plugin.getConfig().getString("root.background", "minecraft:textures/block/deepslate_tiles.png"));
display.addProperty("frame", "task");
display.addProperty("show_toast", false);
display.addProperty("announce_to_chat", false);
display.addProperty("hidden", false);
root.add("display", display);
return root.toString();
}
private String advancementJson(AchievementDefinition definition) {
JsonObject root = baseJson();
root.addProperty("parent", NAMESPACE + ":" + (definition.parent().equals("root") ? rootId : definition.parent()));
JsonObject display = new JsonObject();
display.add("icon", icon(definition.icon()));
display.addProperty("title", definition.name());
display.addProperty("description", definition.description());
display.addProperty("frame", definition.frame().name().toLowerCase(Locale.ROOT));
display.addProperty("show_toast", definition.showToast());
display.addProperty("announce_to_chat", definition.announceChat());
display.addProperty("hidden", definition.hidden());
root.add("display", display);
return root.toString();
}
private JsonObject baseJson() {
JsonObject root = new JsonObject();
JsonObject criteria = new JsonObject();
JsonObject impossible = new JsonObject();
impossible.addProperty("trigger", "minecraft:impossible");
criteria.add(CRITERION, impossible);
root.add("criteria", criteria);
JsonArray group = new JsonArray();
group.add(CRITERION);
JsonArray requirements = new JsonArray();
requirements.add(group);
root.add("requirements", requirements);
return root;
}
private JsonObject icon(String materialName) {
Material material = Material.matchMaterial(materialName);
JsonObject icon = new JsonObject();
icon.addProperty("id", material == null ? "minecraft:stone" : material.getKey().toString());
return icon;
}
private Map<UUID, Set<String>> captureOnlineProgress() {
Map<UUID, Set<String>> result = new HashMap<>();
for (Player player : Bukkit.getOnlinePlayers()) {
Set<String> ids = new HashSet<>();
for (NamespacedKey key : registered) {
Advancement advancement = Bukkit.getAdvancement(key);
if (advancement != null && player.getAdvancementProgress(advancement).isDone()) ids.add(key.getKey());
}
result.put(player.getUniqueId(), ids);
}
return result;
}
public void unregisterAll() {
List<NamespacedKey> reverse = new ArrayList<>(registered);
Collections.reverse(reverse);
for (NamespacedKey key : reverse) {
try { Bukkit.getUnsafe().removeAdvancement(key); }
catch (RuntimeException exception) { plugin.getLogger().warning("移除进度失败 " + key + ": " + exception.getMessage()); }
}
registered.clear();
}
public void ensureRoot(Player player) {
if (!plugin.getConfig().getBoolean("root.auto-grant", true)) return;
award(player, rootId == null ? plugin.getConfig().getString("root.id", "root") : rootId);
}
public boolean award(Player player, String id) {
Advancement advancement = Bukkit.getAdvancement(key(id));
if (advancement == null) return false;
AdvancementProgress progress = player.getAdvancementProgress(advancement);
boolean changed = false;
for (String criterion : progress.getRemainingCriteria()) changed |= progress.awardCriteria(criterion);
return changed;
}
public boolean revoke(Player player, String id) {
if (id.equals(rootId)) return false;
Advancement advancement = Bukkit.getAdvancement(key(id));
if (advancement == null) return false;
AdvancementProgress progress = player.getAdvancementProgress(advancement);
boolean changed = false;
for (String criterion : progress.getAwardedCriteria()) changed |= progress.revokeCriteria(criterion);
return changed;
}
public boolean isDone(Player player, String id) {
Advancement advancement = Bukkit.getAdvancement(key(id));
return advancement != null && player.getAdvancementProgress(advancement).isDone();
}
public NamespacedKey key(String id) { return new NamespacedKey(NAMESPACE, id); }
public int registeredCount() { return registered.size(); }
public record RegistrationResult(int count, List<String> errors) { public boolean success() { return errors.isEmpty(); } }
}
@@ -0,0 +1,242 @@
package top.itxiaohui.serveradvancements.command;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import top.itxiaohui.serveradvancements.config.MessageService;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import top.itxiaohui.serveradvancements.gui.AdminGui;
import top.itxiaohui.serveradvancements.model.AchievementDefinition;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public final class IsaCommand implements TabExecutor {
private static final String ADMIN = "itxiaohui.serveradvancements.admin";
private final ItxiaohuiServerAdvancements plugin;
private final ConfigurationManager configuration;
private final MessageService messages;
public IsaCommand(ItxiaohuiServerAdvancements plugin, ConfigurationManager configuration, MessageService messages) {
this.plugin = plugin;
this.configuration = configuration;
this.messages = messages;
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("help")) { help(sender); return true; }
String sub = args[0].toLowerCase(Locale.ROOT);
try {
return switch (sub) {
case "list" -> list(sender);
case "info" -> info(sender, args);
case "editor" -> editor(sender);
case "give" -> give(sender, args);
case "revoke" -> revoke(sender, args);
case "progress" -> progress(sender, args);
case "reload" -> reload(sender);
case "create" -> create(sender, args);
case "delete" -> delete(sender, args);
case "validate" -> validate(sender);
case "backup" -> backup(sender);
default -> { help(sender); yield true; }
};
} catch (Exception exception) {
sender.sendMessage(Component.text("操作失败: " + exception.getMessage(), NamedTextColor.RED));
plugin.getLogger().severe("命令 /isa " + String.join(" ", args) + " 失败: " + exception);
return true;
}
}
private void help(CommandSender sender) {
sender.sendMessage(Component.text("服务器成就树命令", NamedTextColor.GOLD));
sender.sendMessage(Component.text("/isa list | info <id> | progress <玩家>", NamedTextColor.YELLOW));
if (sender.hasPermission(ADMIN)) {
sender.sendMessage(Component.text("/isa editor | give/revoke <玩家> <id>", NamedTextColor.YELLOW));
sender.sendMessage(Component.text("/isa create/delete <id> | reload | validate | backup", NamedTextColor.YELLOW));
}
}
private boolean list(CommandSender sender) {
sender.sendMessage(Component.text("已配置成就(" + configuration.definitions().size() + ")", NamedTextColor.GOLD));
configuration.definitions().values().forEach(definition -> sender.sendMessage(Component.text(
"- " + definition.id() + ":" + definition.name() + (definition.enabled() ? "" : " [禁用]"),
definition.enabled() ? NamedTextColor.YELLOW : NamedTextColor.GRAY)));
return true;
}
private boolean info(CommandSender sender, String[] args) {
if (args.length < 2) return usage(sender, "/isa info <id>");
AchievementDefinition definition = configuration.get(args[1]);
if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[1])); return true; }
sender.sendMessage(Component.text(definition.name() + " (" + definition.id() + ")", NamedTextColor.GOLD));
sender.sendMessage(Component.text(definition.description(), NamedTextColor.GRAY));
sender.sendMessage(Component.text("父级=" + definition.parent() + " 类型=" + definition.frame().name().toLowerCase() +
" 条件=" + definition.conditions().size() + " 启用=" + definition.enabled(), NamedTextColor.YELLOW));
return true;
}
private boolean editor(CommandSender sender) {
if (!require(sender, ADMIN)) return true;
if (!(sender instanceof Player player)) { messages.send(sender, "player-only"); return true; }
plugin.adminGui().open(player, 0);
return true;
}
private boolean give(CommandSender sender, String[] args) {
if (!require(sender, "itxiaohui.serveradvancements.give")) return true;
if (args.length < 3) return usage(sender, "/isa give <在线玩家> <id>");
Player target = findOnline(args[1]);
if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; }
AchievementDefinition definition = configuration.get(args[2]);
if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[2])); return true; }
plugin.advancementManager().ensureRoot(target);
plugin.conditionEngine().completeAsync(target, definition).whenComplete((outcome, error) -> {
if (!plugin.isEnabled()) return;
Bukkit.getScheduler().runTask(plugin, () -> {
if (error != null) { sender.sendMessage(Component.text("授予失败,可稍后重试: " + error.getMessage(), NamedTextColor.RED)); return; }
switch (outcome) {
case COMPLETED, RESTORED_WITHOUT_REWARD -> messages.send(sender, "granted", Map.of("player", target.getName(), "id", definition.id()));
case ALREADY_COMPLETE, IN_FLIGHT -> messages.send(sender, "already-completed", Map.of("player", target.getName(), "id", definition.id()));
case REVIEW_REQUIRED -> sender.sendMessage(Component.text("奖励存在 PENDING/FAILED 记录,需要管理员核查,未重复发奖。", NamedTextColor.RED));
case RETRY_LATER -> sender.sendMessage(Component.text("玩家数据尚未就绪、成就禁用或数据库暂不可用,未授予,可稍后重试。", NamedTextColor.YELLOW));
}
});
});
plugin.database().auditAsync(sender.getName(), "GIVE_REQUEST", target.getUniqueId().toString(), definition.id());
return true;
}
private boolean revoke(CommandSender sender, String[] args) {
if (!require(sender, "itxiaohui.serveradvancements.revoke")) return true;
if (args.length < 3) return usage(sender, "/isa revoke <在线玩家> <id>");
Player target = findOnline(args[1]);
if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; }
AchievementDefinition definition = configuration.get(args[2]);
if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[2])); return true; }
plugin.advancementManager().revoke(target, definition.id());
plugin.database().auditAsync(sender.getName(), "REVOKE", target.getUniqueId().toString(), definition.id());
messages.send(sender, "revoked", Map.of("player", target.getName(), "id", definition.id()));
return true;
}
private boolean progress(CommandSender sender, String[] args) {
if (!require(sender, "itxiaohui.serveradvancements.view")) return true;
if (args.length < 2) return usage(sender, "/isa progress <在线玩家>");
Player target = findOnline(args[1]);
if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; }
long done = configuration.definitions().keySet().stream().filter(id -> plugin.advancementManager().isDone(target, id)).count();
sender.sendMessage(Component.text(target.getName() + ":完成 " + done + "/" + configuration.definitions().size(), NamedTextColor.GOLD));
Map<String, Double> stats = plugin.statistics().snapshot(target.getUniqueId());
stats.entrySet().stream().sorted(Map.Entry.comparingByKey()).limit(30).forEach(entry ->
sender.sendMessage(Component.text("- " + entry.getKey() + " = " + String.format(Locale.ROOT, "%.2f", entry.getValue()), NamedTextColor.GRAY)));
return true;
}
private boolean reload(CommandSender sender) {
if (!require(sender, ADMIN)) return true;
plugin.reloadDefinitions(sender);
plugin.database().auditAsync(sender.getName(), "RELOAD", null, null);
return true;
}
private boolean create(CommandSender sender, String[] args) throws IOException {
if (!require(sender, ADMIN)) return true;
if (args.length < 2) return usage(sender, "/isa create <id>");
if (!configuration.createSkeleton(args[1])) {
sender.sendMessage(Component.text("ID 非法、已存在或使用了保留 ID root。", NamedTextColor.RED));
return true;
}
plugin.database().auditAsync(sender.getName(), "CREATE", args[1], null);
messages.send(sender, "created", Map.of("id", args[1]));
return true;
}
private boolean delete(CommandSender sender, String[] args) throws IOException {
if (!require(sender, ADMIN)) return true;
if (args.length < 2) return usage(sender, "/isa delete <id> confirm");
if (args.length < 3 || !args[2].equalsIgnoreCase("confirm")) {
messages.send(sender, "delete-confirm", Map.of("id", args[1])); return true;
}
ConfigurationManager.DeleteResult result = configuration.delete(args[1]);
if (!result.success()) sender.sendMessage(Component.text("无法删除: " + result.reason(), NamedTextColor.RED));
else {
plugin.database().auditAsync(sender.getName(), "DELETE", args[1], "配置已删除,原版玩家进度未批量清理");
messages.send(sender, "deleted", Map.of("id", args[1]));
}
return true;
}
private boolean validate(CommandSender sender) {
if (!require(sender, ADMIN)) return true;
ConfigurationManager.LoadResult result = configuration.load();
result.validation().errors().forEach(error -> sender.sendMessage(Component.text("错误: " + error, NamedTextColor.RED)));
result.validation().warnings().forEach(warning -> sender.sendMessage(Component.text("警告: " + warning, NamedTextColor.YELLOW)));
if (result.validation().valid()) messages.send(sender, "validation-ok", Map.of("count", result.definitions().size()));
return true;
}
private boolean backup(CommandSender sender) throws Exception {
if (!require(sender, ADMIN)) return true;
plugin.statistics().updateOnlineSessions();
plugin.statistics().flushAllAsync().thenCompose(ignored -> plugin.database().submit(() -> plugin.database().backup()))
.whenComplete((path, error) -> {
if (!plugin.isEnabled()) return;
Bukkit.getScheduler().runTask(plugin, () -> {
if (error != null) sender.sendMessage(Component.text("备份失败: " + error.getMessage(), NamedTextColor.RED));
else messages.send(sender, "backup-created", Map.of("path", path.toAbsolutePath()));
});
});
return true;
}
private Player findOnline(String input) {
try { return Bukkit.getPlayer(UUID.fromString(input)); }
catch (IllegalArgumentException ignored) { return Bukkit.getPlayerExact(input); }
}
private boolean require(CommandSender sender, String permission) {
if (sender.hasPermission(permission)) return true;
messages.send(sender, "no-permission");
return false;
}
private boolean usage(CommandSender sender, String usage) {
sender.sendMessage(Component.text("用法: " + usage, NamedTextColor.RED));
return true;
}
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (args.length == 0) return List.of();
if (args.length == 1) return filter(List.of("help", "list", "info", "editor", "give", "revoke", "progress", "reload", "create", "delete", "validate", "backup").stream().filter(sub -> allowed(sender, sub)).toList(), args[0]);
if (!allowed(sender, args[0].toLowerCase(Locale.ROOT))) return List.of();
if (args.length == 2 && Set.of("give", "revoke", "progress").contains(args[0].toLowerCase()))
return filter(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(), args[1]);
if ((args.length == 2 && Set.of("info", "delete").contains(args[0].toLowerCase())) ||
(args.length == 3 && Set.of("give", "revoke").contains(args[0].toLowerCase())))
return filter(new ArrayList<>(configuration.definitions().keySet()), args[args.length - 1]);
if (args.length == 3 && args[0].equalsIgnoreCase("delete")) return filter(List.of("confirm"), args[2]);
return List.of();
}
private boolean allowed(CommandSender sender, String sub) {
return switch (sub) {
case "help", "list", "info" -> true;
case "give", "revoke" -> sender.hasPermission("itxiaohui.serveradvancements." + sub);
case "progress" -> sender.hasPermission("itxiaohui.serveradvancements.view");
default -> sender.hasPermission(ADMIN);
};
}
private List<String> filter(List<String> values, String prefix) {
String lower = prefix.toLowerCase(Locale.ROOT);
return values.stream().filter(value -> value.toLowerCase(Locale.ROOT).startsWith(lower)).sorted().toList();
}
}
@@ -0,0 +1,133 @@
package top.itxiaohui.serveradvancements.condition;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Statistic;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import top.itxiaohui.serveradvancements.model.ConditionDefinition;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.util.*;
/** Read-only native state and persisted server observations. No AI/network calls. */
public final class AutomaticConditions {
public static final Set<String> EVENTS = Set.of("eat_food", "cook_food", "tame_animal", "fish_item", "place_block");
private AutomaticConditions() { }
public static List<String> strings(ConditionDefinition condition, String key) {
Object value = condition.parameters().get(key);
if (!(value instanceof List<?> list)) return List.of();
return list.stream().map(String::valueOf).toList();
}
public static List<String> validate(ConditionDefinition c) {
List<String> errors = new ArrayList<>();
for (String key : List.of("materials", "items", "structures", "subjects")) {
Object value = c.parameters().get(key);
if (value != null && (!(value instanceof List<?> list) || list.stream().anyMatch(item -> !(item instanceof String))))
errors.add(key + " 必须是字符串列表");
}
switch (c.type()) {
case PLAYER_STATISTIC -> {
try {
Statistic statistic = Statistic.valueOf(c.string("statistic", ""));
var materials = strings(c, "materials");
switch (statistic.getType()) {
case UNTYPED -> { if (!materials.isEmpty() || c.parameters().containsKey("entity")) errors.add("无类型统计不能指定物品或生物"); }
case ITEM, BLOCK -> {
validateMaterials(materials, errors, statistic.isBlock());
if (c.parameters().containsKey("entity")) errors.add("物品统计不能指定 entity");
}
case ENTITY -> {
EntityType type = entity(c.string("entity", ""));
if (type == null || !type.isAlive() || !materials.isEmpty()) errors.add("原版统计生物无效");
}
}
} catch (IllegalArgumentException error) { errors.add("原版统计名称无效"); }
}
case VANILLA_ADVANCEMENT -> {
NamespacedKey key = NamespacedKey.fromString(c.string("advancement", ""));
if (key == null || !key.getNamespace().equals("minecraft") || !key.getKey().contains("/")) errors.add("只允许 minecraft 原版进度键");
}
case INVENTORY_SET -> {
var items = strings(c, "items");
validateMaterials(items, errors, false);
if (c.target() != Math.rint(c.target()) || c.target() > items.size()) errors.add("收藏种类数超过物品列表或非整数");
double each = c.number("each", 1);
if (!Double.isFinite(each) || each < 1 || each > 4096 || each != Math.rint(each)) errors.add("收藏单种数量必须是 1–4096 整数");
}
case VISIT_BIOME -> { if (!validMinecraftKey(c.string("biome", ""))) errors.add("生物群系键无效"); }
case VISIT_STRUCTURE -> {
var structures = strings(c, "structures");
if (structures.isEmpty() || structures.size() > 32 || structures.stream().anyMatch(s -> !validMinecraftKey(s))) errors.add("结构列表无效");
}
case EVENT_COUNT, EVENT_DISTINCT -> {
if (!EVENTS.contains(c.string("event", ""))) errors.add("自动事件名称无效");
var subjects = strings(c, "subjects");
if (subjects.size() > 64 || subjects.stream().anyMatch(s -> !validMinecraftKey(s))) errors.add("事件对象列表无效");
if (!subjects.isEmpty() && c.type() == top.itxiaohui.serveradvancements.model.ConditionType.EVENT_DISTINCT && c.target() > new HashSet<>(subjects).size()) errors.add("不同种类目标大于对象列表");
}
default -> { }
}
return errors;
}
private static boolean validMinecraftKey(String value) {
NamespacedKey key = NamespacedKey.fromString(value);
return key != null && key.getNamespace().equals("minecraft");
}
private static EntityType entity(String key) {
return Arrays.stream(EntityType.values()).filter(type -> type.isAlive() && type.getKey().toString().equals(key)).findFirst().orElse(null);
}
private static void validateMaterials(List<String> values, List<String> errors, boolean block) {
if (values.isEmpty() || values.size() > 64 || new HashSet<>(values).size() != values.size()) errors.add("物品列表必须有 1–64 个不同对象");
for (String value : values) {
Material material = Material.matchMaterial(value);
if (!validMinecraftKey(value) || material == null || (block ? !material.isBlock() : !material.isItem())) errors.add("物品/方块无效: " + value);
}
}
public static double current(Player player, ConditionDefinition c, StatisticsService statistics) {
return switch (c.type()) {
case PLAYER_STATISTIC -> nativeStatistic(player, c);
case VANILLA_ADVANCEMENT -> {
var advancement = Bukkit.getAdvancement(NamespacedKey.fromString(c.string("advancement", "")));
yield advancement != null && player.getAdvancementProgress(advancement).isDone() ? 1 : 0;
}
case INVENTORY_SET -> {
Map<String, Integer> counts = new HashMap<>();
for (ItemStack item : player.getInventory().getContents()) if (item != null && !item.getType().isAir())
counts.merge(item.getType().getKey().toString(), item.getAmount(), Integer::sum);
yield strings(c, "items").stream().filter(item -> counts.getOrDefault(item, 0) >= c.number("each", 1)).count();
}
case VISIT_STRUCTURE -> {
var structures = strings(c, "structures");
yield statistics.snapshot(player.getUniqueId()).entrySet().stream()
.filter(e -> e.getValue() > 0 && structures.stream().anyMatch(s -> e.getKey().startsWith("structure:" + s + ":"))).count();
}
case EVENT_COUNT, EVENT_DISTINCT -> {
String prefix = "event:" + c.string("event", "") + ":";
var subjects = strings(c, "subjects");
var entries = statistics.snapshot(player.getUniqueId()).entrySet().stream()
.filter(e -> e.getKey().startsWith(prefix) && (subjects.isEmpty() || subjects.contains(e.getKey().substring(prefix.length()))));
yield c.type() == top.itxiaohui.serveradvancements.model.ConditionType.EVENT_DISTINCT
? entries.filter(e -> e.getValue() > 0).count() : entries.mapToDouble(Map.Entry::getValue).sum();
}
default -> statistics.get(player.getUniqueId(), c.statisticKey());
};
}
private static double nativeStatistic(Player player, ConditionDefinition c) {
Statistic statistic = Statistic.valueOf(c.string("statistic", ""));
return switch (statistic.getType()) {
case UNTYPED -> player.getStatistic(statistic);
case ITEM, BLOCK -> strings(c, "materials").stream().mapToDouble(m -> player.getStatistic(statistic, Material.matchMaterial(m))).sum();
case ENTITY -> player.getStatistic(statistic, entity(c.string("entity", "")));
};
}
}
@@ -0,0 +1,168 @@
package top.itxiaohui.serveradvancements.condition;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.advancement.AdvancementManager;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import top.itxiaohui.serveradvancements.model.*;
import top.itxiaohui.serveradvancements.reward.RewardService;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public final class ConditionEngine {
private final JavaPlugin plugin;
private final ConfigurationManager configuration;
private final StatisticsService statistics;
private final AdvancementManager advancements;
private final RewardService rewards;
private long indexedRevision = Long.MIN_VALUE;
private final Map<String, List<AchievementDefinition>> byStatistic = new HashMap<>();
private final List<AchievementDefinition> regions = new ArrayList<>();
public ConditionEngine(JavaPlugin plugin, ConfigurationManager configuration, StatisticsService statistics,
AdvancementManager advancements, RewardService rewards) {
this.plugin = plugin;
this.configuration = configuration;
this.statistics = statistics;
this.advancements = advancements;
this.rewards = rewards;
}
public void record(Player player, ConditionType type, String discriminator, double amount) {
if (type == ConditionType.KILL_MOB || type == ConditionType.BREED_MOB) {
statistics.increment(player.getUniqueId(), key(type, "*"), amount);
}
statistics.increment(player.getUniqueId(), key(type, discriminator), amount);
evaluateAffected(player, key(type, discriminator), type == ConditionType.KILL_MOB || type == ConditionType.BREED_MOB ? key(type, "*") : "");
}
public void mark(Player player, ConditionType type, String discriminator) {
statistics.setMax(player.getUniqueId(), key(type, discriminator), 1);
evaluateAffected(player, key(type, discriminator), "");
}
public void setLevel(Player player, int level) {
statistics.setMax(player.getUniqueId(), "experience_level", level);
evaluateAffected(player, "experience_level", "");
}
public void event(Player player, String event, String subject, int amount) {
if (amount <= 0 || !AutomaticConditions.EVENTS.contains(event)) return;
statistics.increment(player.getUniqueId(), "event:" + event + ":" + subject, amount);
evaluateAffected(player, "event:" + event, "");
}
/** Called by the low-frequency main-thread sampler, not on every movement packet. */
public void observeEnvironment(Player player) {
if (!statistics.isReady(player.getUniqueId())) return;
Location location = player.getLocation();
statistics.setMax(player.getUniqueId(), "altitude", Math.max(0, location.getY()));
statistics.setMax(player.getUniqueId(), "visit_biome:" + location.getBlock().getBiome().getKey(), 1);
var world = location.getWorld();
int x = location.getBlockX() >> 4, z = location.getBlockZ() >> 4;
if (!world.isChunkLoaded(x, z)) return;
for (var structure : world.getStructures(x, z)) {
var bounds = structure.getBoundingBox();
if (!bounds.clone().expand(1, 2, 1).contains(location.toVector())) continue;
String identity = structure.getStructure().getKey() + ":" + world.getUID() + ":"
+ (int) bounds.getMinX() + "," + (int) bounds.getMinY() + "," + (int) bounds.getMinZ();
statistics.setMax(player.getUniqueId(), "structure:" + identity, 1);
}
}
public void evaluate(Player player) {
if (!statistics.isReady(player.getUniqueId())) return;
for (AchievementDefinition definition : configuration.definitions().values()) evaluateOne(player, definition);
}
private void evaluateOne(Player player, AchievementDefinition definition) {
if (definition.enabled() && !advancements.isDone(player, definition.id()) && !rewards.isInFlight(player.getUniqueId(), definition.id()) && satisfied(player, definition)) complete(player, definition);
}
private void evaluateAffected(Player player, String key, String wildcard) {
if (!statistics.isReady(player.getUniqueId())) return;
if (indexedRevision != configuration.revision()) {
byStatistic.clear(); regions.clear();
for (AchievementDefinition definition : configuration.definitions().values()) {
for (ConditionDefinition condition : definition.conditions()) {
byStatistic.computeIfAbsent(condition.statisticKey(), ignored -> new ArrayList<>()).add(definition);
if (condition.type() == ConditionType.REACH_LOCATION && !regions.contains(definition)) regions.add(definition);
}
}
indexedRevision = configuration.revision();
}
Set<AchievementDefinition> affected = new LinkedHashSet<>(byStatistic.getOrDefault(key, List.of()));
affected.addAll(byStatistic.getOrDefault(wildcard, List.of()));
if (key.equals("move_distance")) affected.addAll(regions);
for (AchievementDefinition definition : affected) evaluateOne(player, definition);
}
public boolean complete(Player player, AchievementDefinition definition) {
if (!definition.enabled() || !statistics.isReady(player.getUniqueId()) || advancements.isDone(player, definition.id()) || rewards.isInFlight(player.getUniqueId(), definition.id())) return false;
completeAsync(player, definition);
return true;
}
public CompletableFuture<RewardService.Outcome> completeAsync(Player player, AchievementDefinition definition) {
if (!definition.enabled() || !statistics.isReady(player.getUniqueId())) return CompletableFuture.completedFuture(RewardService.Outcome.RETRY_LATER);
if (advancements.isDone(player, definition.id())) return CompletableFuture.completedFuture(RewardService.Outcome.ALREADY_COMPLETE);
return rewards.complete(player, definition, () -> advancements.award(player, definition.id()),
() -> {
statistics.setMax(player.getUniqueId(), "achievement:" + definition.id(), 1);
if (plugin.isEnabled()) plugin.getServer().getScheduler().runTask(plugin, () -> { if (player.isOnline()) evaluate(player); });
});
}
private boolean satisfied(Player player, AchievementDefinition definition) {
for (ConditionDefinition condition : definition.conditions()) {
if (!Double.isFinite(condition.target()) || condition.target() <= 0) return false;
if (condition.type() == ConditionType.MANUAL) return false;
if (condition.type() == ConditionType.REACH_LOCATION) {
if (statistics.get(player.getUniqueId(), condition.statisticKey()) < 1) {
if (!reached(player.getLocation(), condition)) return false;
statistics.setMax(player.getUniqueId(), condition.statisticKey(), 1);
}
} else if (condition.type() == ConditionType.COMPLETE_ACHIEVEMENT) {
if (!advancements.isDone(player, condition.string("achievement", ""))) return false;
} else if (AutomaticConditions.current(player, condition, statistics) < condition.target()) return false;
}
return true;
}
private boolean reached(Location location, ConditionDefinition condition) {
if (!location.getWorld().getKey().toString().equalsIgnoreCase(condition.string("world", location.getWorld().getKey().toString()))
&& !location.getWorld().getName().equalsIgnoreCase(condition.string("world", location.getWorld().getName()))) return false;
double x = condition.number("x", location.getX());
double y = condition.number("y", location.getY());
double z = condition.number("z", location.getZ());
double radius = condition.number("radius", 5);
double dx = location.getX() - x, dy = location.getY() - y, dz = location.getZ() - z;
return dx * dx + dy * dy + dz * dz <= radius * radius;
}
private String key(ConditionType type, String discriminator) {
return switch (type) {
case FIRST_JOIN -> "first_join";
case ONLINE_TIME -> "online_time_ms";
case MINE_BLOCK -> "mine_block:" + discriminator;
case COLLECT_ITEM -> "collect_item:" + discriminator;
case OBTAIN_ITEM -> "obtain_item:" + discriminator;
case KILL_MOB -> "kill_mob:" + discriminator;
case VISIT_DIMENSION -> "visit_dimension:" + discriminator;
case MOVE_DISTANCE -> "move_distance";
case REACH_LOCATION -> "reach_location:" + discriminator;
case CRAFT_ITEM -> "craft_item:" + discriminator;
case BREED_MOB -> "breed_mob:" + discriminator;
case EXPERIENCE_LEVEL -> "experience_level";
case COMPLETE_ACHIEVEMENT -> "achievement:" + discriminator;
case MANUAL -> "manual";
case VISIT_BIOME -> "visit_biome:" + discriminator;
case ALTITUDE -> "altitude";
case EVENT_COUNT, EVENT_DISTINCT -> "event:" + discriminator;
case PLAYER_STATISTIC, VANILLA_ADVANCEMENT, INVENTORY_SET, VISIT_STRUCTURE -> throw new IllegalArgumentException("该条件使用原版状态或环境采样,不接受直接累计: " + type);
};
}
}
@@ -0,0 +1,94 @@
package top.itxiaohui.serveradvancements.config;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
/** One-time, additive catalog upgrade. Never replaces an administrator's existing ID. */
public final class BundledCatalogInstaller {
private static final String MARKER = "bundled-fun-catalog-version";
private BundledCatalogInstaller() { }
public static Result install(JavaPlugin plugin) throws IOException {
try (var resource = plugin.getResource("fun-advancements.yml")) {
if (resource == null) throw new IOException("JAR 缺少 fun-advancements.yml");
var catalog = StrictYaml.parse(new String(resource.readAllBytes(), StandardCharsets.UTF_8), true);
return install(plugin.getDataFolder().toPath().resolve("advancements.yml"), catalog);
}
}
public static Result install(Path target, YamlConfiguration catalog) throws IOException {
YamlConfiguration previous = new YamlConfiguration();
if (catalog.getInt("catalog-version", 0) > 1) {
try (var resource = BundledCatalogInstaller.class.getClassLoader().getResourceAsStream("fun-advancements-v1.yml")) {
if (resource == null) throw new IOException("缺少旧版目录,拒绝不安全升级");
previous = StrictYaml.parse(new String(resource.readAllBytes(), StandardCharsets.UTF_8), true);
}
}
return install(target, catalog, previous);
}
public static Result install(Path target, YamlConfiguration catalog, YamlConfiguration previous) throws IOException {
int version = catalog.getInt("catalog-version", 0);
ConfigurationSection additions = catalog.getConfigurationSection("achievements");
if (version < 1 || additions == null) throw new IOException("内置趣味成就目录无效");
YamlConfiguration current = StrictYaml.read(target, true);
int installed = current.getInt(MARKER, 0);
if (installed >= version) return new Result(0, 0, null);
if (current.contains("achievements") && !current.isConfigurationSection("achievements"))
throw new IOException("现有 achievements 不是配置节,拒绝覆盖");
ConfigurationSection destination = current.getConfigurationSection("achievements");
if (destination == null) destination = current.createSection("achievements");
int added = 0, updated = 0;
ConfigurationSection oldEntries = previous.getConfigurationSection("achievements");
for (String id : additions.getKeys(false)) {
ConfigurationSection node = additions.getConfigurationSection(id);
if (!ConfigurationManager.validId(id) || node == null) throw new IOException("内置成就无效: " + id);
if (!destination.contains(id)) {
// A previously installed ID removed by the administrator stays removed.
if (installed > 0 && oldEntries != null && oldEntries.contains(id)) continue;
copy(node, destination.createSection(id));
added++;
} else if (installed == 1 && oldEntries != null && oldEntries.isConfigurationSection(id)
&& destination.isConfigurationSection(id)
&& leaves(destination.getConfigurationSection(id)).equals(leaves(oldEntries.getConfigurationSection(id)))) {
destination.set(id, null);
copy(node, destination.createSection(id));
updated++;
}
}
current.set(MARKER, version);
Path backup = null;
if (Files.exists(target)) {
backup = target.resolveSibling("advancements-before-fun-" + UUID.randomUUID() + ".yml.bak");
Files.copy(target, backup);
}
StrictYaml.save(current, target);
return new Result(added, updated, backup);
}
private static Map<String, Object> leaves(ConfigurationSection section) {
Map<String, Object> values = new HashMap<>(section.getValues(true));
values.values().removeIf(value -> value instanceof ConfigurationSection);
return values;
}
private static void copy(ConfigurationSection source, ConfigurationSection destination) {
for (String key : source.getKeys(false)) {
ConfigurationSection child = source.getConfigurationSection(key);
if (child == null) destination.set(key, source.get(key));
else copy(child, destination.createSection(key));
}
}
public record Result(int added, int updated, Path backup) { }
}
@@ -0,0 +1,241 @@
package top.itxiaohui.serveradvancements.config;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.model.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import org.bukkit.entity.EntityType;
public final class ConfigurationManager {
private static final Pattern ID_PATTERN = Pattern.compile("[a-z0-9._/-]+");
private final JavaPlugin plugin;
private LinkedHashMap<String, AchievementDefinition> definitions = new LinkedHashMap<>();
private ValidationResult lastValidation = new ValidationResult(List.of(), List.of());
private long revision;
public ConfigurationManager(JavaPlugin plugin) { this.plugin = plugin; }
public LoadResult load() {
File file = new File(plugin.getDataFolder(), "advancements.yml");
LinkedHashMap<String, AchievementDefinition> loaded = new LinkedHashMap<>();
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
YamlConfiguration yaml;
try { yaml = StrictYaml.read(file.toPath(), true); }
catch (IOException error) { return new LoadResult(loaded, new ValidationResult(List.of(error.getMessage()), List.of())); }
ConfigurationSection root = yaml.getConfigurationSection("achievements");
if (root == null) {
errors.add("advancements.yml: 缺少 achievements 节点");
return new LoadResult(loaded, new ValidationResult(errors, warnings));
}
for (String id : root.getKeys(false)) {
ConfigurationSection section = root.getConfigurationSection(id);
if (section == null) continue;
try {
AchievementDefinition definition = parse(id, section);
List<String> localErrors = validateOne(definition);
if (localErrors.isEmpty()) loaded.put(id, definition);
else localErrors.forEach(error -> errors.add("advancements.yml 成就 " + id + ": " + error));
} catch (RuntimeException exception) {
errors.add("advancements.yml 成就 " + id + ": " + exception.getMessage());
}
}
validateGraph(loaded, errors);
if (loaded.values().stream().anyMatch(definition -> definition.x() != 0 || definition.y() != 0))
warnings.add("display.x/y 仅作为定义排序提示;原版客户端自动计算节点坐标");
ValidationResult result = new ValidationResult(List.copyOf(errors), List.copyOf(warnings));
return new LoadResult(loaded, result);
}
public boolean apply(LoadResult result) {
lastValidation = result.validation();
if (!result.validation().valid()) return false;
definitions = result.definitions();
revision++;
return true;
}
public void applyValidSubset(LoadResult result) {
lastValidation = result.validation();
definitions = result.definitions();
revision++;
}
private AchievementDefinition parse(String id, ConfigurationSection section) {
List<ConditionDefinition> conditions = new ArrayList<>();
for (Map<?, ?> raw : section.getMapList("conditions")) {
Map<String, Object> values = new LinkedHashMap<>();
raw.forEach((key, value) -> values.put(String.valueOf(key), value));
String type = String.valueOf(values.remove("type"));
conditions.add(new ConditionDefinition(ConditionType.parse(type), values));
}
ConfigurationSection reward = section.getConfigurationSection("rewards");
List<RewardDefinition.RewardItem> items = new ArrayList<>();
if (reward != null) {
for (Map<?, ?> raw : reward.getMapList("items")) {
items.add(new RewardDefinition.RewardItem(String.valueOf(raw.get("item")), strictInt(raw.get("amount"), 1)));
}
}
RewardDefinition rewards = new RewardDefinition(
reward == null ? 0 : strictInt(reward.get("experience"), 0),
List.copyOf(items), reward == null ? List.of() : List.copyOf(reward.getStringList("commands")),
reward != null && reward.getBoolean("allow-reclaim", plugin.getConfig().getBoolean("defaults.allow-reward-reclaim", false)),
reward == null ? "" : reward.getString("completion-message", ""));
ConfigurationSection display = section.getConfigurationSection("display");
return new AchievementDefinition(id, section.getString("name", id), section.getString("description", ""),
section.getString("icon", "minecraft:stone"), AdvancementFrame.parse(section.getString("frame", "task")),
section.getString("parent", "root").equals(rootId()) ? "root" : section.getString("parent", "root"), display == null ? 0 : display.getDouble("x"),
display == null ? 0 : display.getDouble("y"), List.copyOf(conditions),
section.getBoolean("hidden", false),
section.getBoolean("show-toast", plugin.getConfig().getBoolean("defaults.show-toast", true)),
section.getBoolean("announce-chat", plugin.getConfig().getBoolean("defaults.announce-chat", false)),
section.getBoolean("enabled", true), rewards);
}
private int strictInt(Object value, int fallback) {
if (value == null) return fallback;
if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue()) || number.doubleValue() != number.intValue())
throw new IllegalArgumentException("整数配置非法: " + value);
return number.intValue();
}
public String rootId() { return plugin.getConfig().getString("root.id", "root"); }
public long revision() { return revision; }
public static boolean validId(String id) {
return id != null && id.length() <= 128 && ID_PATTERN.matcher(id).matches()
&& Arrays.stream(id.split("/", -1)).noneMatch(part -> part.isEmpty() || part.equals(".") || part.equals(".."));
}
private List<String> validateOne(AchievementDefinition definition) {
List<String> errors = new ArrayList<>();
if (!validId(definition.id()) || definition.id().equals("root") || definition.id().equals(rootId()))
errors.add("ID 非法,只允许小写字母、数字、._/-");
Material icon = Material.matchMaterial(definition.icon());
if (NamespacedKey.fromString(definition.icon()) == null || icon == null || !icon.isItem()) errors.add("图标不是有效物品: " + definition.icon());
if (definition.conditions().isEmpty()) errors.add("至少需要一个条件");
if (definition.conditions().size() > 64 || definition.name().length() > 256 || definition.description().length() > 2048
|| !Double.isFinite(definition.x()) || !Double.isFinite(definition.y())) errors.add("条件数量、显示文字长度或坐标非法");
for (ConditionDefinition condition : definition.conditions()) {
errors.addAll(top.itxiaohui.serveradvancements.condition.AutomaticConditions.validate(condition));
if (!Double.isFinite(condition.target()) || condition.target() <= 0) errors.add("条件 " + condition.type() + " 的目标必须为正有限数且单位有效");
String materialKey = switch (condition.type()) {
case MINE_BLOCK -> condition.string("block", "");
case COLLECT_ITEM, OBTAIN_ITEM, CRAFT_ITEM -> condition.string("item", "");
default -> null;
};
if (materialKey != null) {
Material material = Material.matchMaterial(materialKey);
if (NamespacedKey.fromString(materialKey) == null || material == null
|| (condition.type() == ConditionType.MINE_BLOCK ? !material.isBlock() : !material.isItem()))
errors.add("条件 " + condition.type() + " 的物品/方块无效: " + materialKey);
}
if (condition.type() == ConditionType.KILL_MOB || condition.type() == ConditionType.BREED_MOB) {
String entity = condition.string("entity", "");
if (!entity.equals("*")) {
if (Arrays.stream(EntityType.values()).noneMatch(type -> type.isAlive() && type.getKey().toString().equals(entity))) errors.add("生物 ID 无效: " + entity);
}
}
if (condition.type() == ConditionType.VISIT_DIMENSION && NamespacedKey.fromString(condition.string("dimension", "")) == null) errors.add("维度 ID 无效");
if (condition.type() == ConditionType.REACH_LOCATION) {
if (condition.string("world", "").isBlank()) errors.add("区域必须指定 world");
for (String axis : List.of("x", "y", "z")) if (!condition.parameters().containsKey(axis) || !Double.isFinite(condition.number(axis, Double.NaN))) errors.add("区域必须指定有限坐标 " + axis);
if (!Double.isFinite(condition.number("radius", 5)) || condition.number("radius", 5) < 0) errors.add("区域半径非法");
}
}
if (definition.rewards().experience() < 0 || definition.rewards().experience() > 1_000_000) errors.add("经验奖励必须为 0 到 1000000");
if (definition.rewards().items().size() > 64 || definition.rewards().commands().size() > 64) errors.add("奖励条目过多");
for (String command : definition.rewards().commands()) if (command.isBlank() || command.length() > 1024 || command.contains("\n") || command.contains("\r")) errors.add("奖励命令为空、超长或包含换行");
for (RewardDefinition.RewardItem item : definition.rewards().items()) {
Material material = Material.matchMaterial(item.material());
if (material == null || !material.isItem() || item.amount() < 1 || item.amount() > 4096)
errors.add("奖励物品无效: " + item.material() + " x" + item.amount());
}
return errors;
}
private void validateGraph(Map<String, AchievementDefinition> map, List<String> errors) {
Map<String, Set<String>> dependencies = new HashMap<>();
Map<String, List<String>> consumers = new HashMap<>();
Set<String> invalid = new HashSet<>(); Map<String, Integer> indegree = new HashMap<>();
for (AchievementDefinition definition : map.values()) {
Set<String> required = new HashSet<>();
if (!definition.parent().equals("root")) required.add(definition.parent());
for (ConditionDefinition c : definition.conditions()) if (c.type() == ConditionType.COMPLETE_ACHIEVEMENT) required.add(c.string("achievement", ""));
dependencies.put(definition.id(), required); indegree.put(definition.id(), required.size());
for (String dependency : required) {
consumers.computeIfAbsent(dependency, ignored -> new ArrayList<>()).add(definition.id());
AchievementDefinition parent = map.get(dependency);
if (parent == null || definition.enabled() && !parent.enabled()) invalid.add(definition.id());
}
}
Deque<String> ready = new ArrayDeque<>(); indegree.forEach((id, count) -> { if (count == 0) ready.add(id); });
Set<String> visited = new HashSet<>(); Map<String, Integer> depth = new HashMap<>();
while (!ready.isEmpty()) {
String id = ready.remove(); visited.add(id);
int level = map.get(id).parent().equals("root") ? 1 : depth.getOrDefault(map.get(id).parent(), 0) + 1;
depth.put(id, level); if (level > 256) invalid.add(id);
for (String consumer : consumers.getOrDefault(id, List.of())) if (indegree.compute(consumer, (key, count) -> count - 1) == 0) ready.add(consumer);
}
for (String id : map.keySet()) if (!visited.contains(id)) invalid.add(id);
ready.addAll(invalid);
while (!ready.isEmpty()) for (String consumer : consumers.getOrDefault(ready.remove(), List.of())) if (invalid.add(consumer)) ready.add(consumer);
for (String id : invalid) { errors.add("成就 " + id + ": 依赖缺失、禁用、循环或树深度超过 256,已隔离"); map.remove(id); }
}
public Map<String, AchievementDefinition> definitions() { return Collections.unmodifiableMap(definitions); }
public AchievementDefinition get(String id) { return definitions.get(id); }
public ValidationResult lastValidation() { return lastValidation; }
public boolean createSkeleton(String id) throws IOException {
if (!validId(id) || id.equals("root") || id.equals(rootId())) return false;
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements"); if (root == null) root = yaml.createSection("achievements");
if (root.contains(id)) return false;
ConfigurationSection node = root.createSection(id);
node.set("name", id); node.set("description", "请编辑成就描述"); node.set("icon", "minecraft:stone"); node.set("frame", "task"); node.set("parent", "root");
node.set("enabled", false); node.set("conditions", List.of(Map.of("type", "manual")));
ConfigurationSection display = node.createSection("display"); display.set("x", 1); display.set("y", 0);
ConfigurationSection reward = node.createSection("rewards"); reward.set("experience", 0); reward.set("items", List.of()); reward.set("commands", List.of());
StrictYaml.save(yaml, file.toPath());
return true;
}
public DeleteResult delete(String id) throws IOException {
if (id.equals("root") || id.equals(rootId()) || !validId(id)) return new DeleteResult(false, "根进度不可删除或 ID 非法");
for (AchievementDefinition definition : definitions.values()) {
if (definition.parent().equals(id)) return new DeleteResult(false, "仍有子成就: " + definition.id());
}
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements");
if (root == null || !root.contains(id)) return new DeleteResult(false, "成就不存在");
for (String other : root.getKeys(false)) {
ConfigurationSection node = root.getConfigurationSection(other); if (node == null) continue;
if (node.getString("parent", "root").equals(id)) return new DeleteResult(false, "磁盘配置仍有子成就: " + other);
for (Map<?, ?> c : node.getMapList("conditions")) if ("complete_achievement".equals(c.get("type")) && id.equals(c.get("achievement"))) return new DeleteResult(false, "仍被条件引用: " + other);
}
root.set(id, null); StrictYaml.save(yaml, file.toPath());
return new DeleteResult(true, "");
}
public boolean setEnabled(String id, boolean enabled) throws IOException {
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements");
ConfigurationSection node = root == null ? null : root.getConfigurationSection(id);
if (node == null) return false;
node.set("enabled", enabled); StrictYaml.save(yaml, file.toPath());
return true;
}
public record LoadResult(LinkedHashMap<String, AchievementDefinition> definitions, ValidationResult validation) {}
public record DeleteResult(boolean success, String reason) {}
}
@@ -0,0 +1,54 @@
package top.itxiaohui.serveradvancements.config;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public final class MessageService {
private final JavaPlugin plugin;
private YamlConfiguration messages;
private final LegacyComponentSerializer legacy = LegacyComponentSerializer.legacyAmpersand();
public MessageService(JavaPlugin plugin) {
this.plugin = plugin;
reload();
}
public void reload() {
File file = new File(plugin.getDataFolder(), "messages.yml");
messages = YamlConfiguration.loadConfiguration(file);
InputStream bundled = plugin.getResource("messages.yml");
if (bundled != null) {
try (InputStreamReader reader = new InputStreamReader(bundled, StandardCharsets.UTF_8)) {
messages.setDefaults(YamlConfiguration.loadConfiguration(reader));
} catch (java.io.IOException exception) {
plugin.getLogger().warning("读取内置消息默认值失败: " + exception.getMessage());
}
}
}
public Component component(String key, Map<String, ?> replacements) {
String value = messages.getString(key, key);
for (Map.Entry<String, ?> entry : replacements.entrySet()) {
value = value.replace("{" + entry.getKey() + "}", String.valueOf(entry.getValue()));
}
String prefix = messages.getString("prefix", "");
return legacy.deserialize(prefix + value);
}
public Component component(String key) { return component(key, Map.of()); }
public void send(CommandSender sender, String key) { sender.sendMessage(component(key)); }
public void send(CommandSender sender, String key, Map<String, ?> values) {
sender.sendMessage(component(key, values));
}
}
@@ -0,0 +1,38 @@
package top.itxiaohui.serveradvancements.config;
import org.bukkit.configuration.file.YamlConfiguration;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public final class StrictYaml {
private StrictYaml() { }
public static YamlConfiguration read(Path file, boolean literalKeys) throws IOException {
if (!Files.exists(file)) return parse("", literalKeys);
if (Files.size(file) > 3_000_000) throw new IOException("配置文件超过 3 MB: " + file.getFileName());
return parse(Files.readString(file, StandardCharsets.UTF_8), literalKeys);
}
public static YamlConfiguration parse(String content, boolean literalKeys) throws IOException {
if (content.length() > 3_000_000) throw new IOException("配置文本超过大小限制");
YamlConfiguration result = new YamlConfiguration();
if (literalKeys) result.options().pathSeparator('\u001f');
LoaderOptions options = new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(20);
try {
new Yaml(new SafeConstructor(options)).load(content);
result.loadFromString(content);
} catch (Exception error) { throw new IOException("YAML 无效或有重复键: " + error.getMessage(), error); }
return result;
}
public static void save(YamlConfiguration yaml, Path file) throws IOException {
Files.createDirectories(file.toAbsolutePath().getParent());
Path temporary = Files.createTempFile(file.toAbsolutePath().getParent(), "isa-config-", ".tmp");
try {
Files.writeString(temporary, yaml.saveToString(), StandardCharsets.UTF_8);
try { Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); }
catch (AtomicMoveNotSupportedException ignored) { Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING); }
} finally { Files.deleteIfExists(temporary); }
}
}
@@ -0,0 +1,7 @@
package top.itxiaohui.serveradvancements.config;
import java.util.List;
public record ValidationResult(List<String> errors, List<String> warnings) {
public boolean valid() { return errors.isEmpty(); }
}
@@ -0,0 +1,30 @@
package top.itxiaohui.serveradvancements.database;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.Properties;
/** SQLite JNI symbols require the original org.sqlite package; isolate instead of relocating. */
final class BundledSqliteDriver extends URLClassLoader {
BundledSqliteDriver(URL source) { super(new URL[]{source}, DatabaseManager.class.getClassLoader()); }
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (!name.startsWith("org.sqlite.")) return super.loadClass(name, resolve);
synchronized (getClassLoadingLock(name)) {
Class<?> type = findLoadedClass(name);
if (type == null) type = findClass(name);
if (resolve) resolveClass(type);
return type;
}
}
@Override public URL getResource(String name) {
return name.startsWith("org/sqlite/") ? findResource(name) : super.getResource(name);
}
Connection connect(String url) throws SQLException {
try {
Driver driver = (Driver) loadClass("org.sqlite.JDBC").getDeclaredConstructor().newInstance();
return driver.connect(url, new Properties());
} catch (ReflectiveOperationException error) { throw new SQLException("无法加载打包的 SQLite 驱动", error); }
}
}
@@ -0,0 +1,290 @@
package top.itxiaohui.serveradvancements.database;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.*;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
public final class DatabaseManager implements AutoCloseable {
private static final int SCHEMA_VERSION = 1;
private final JavaPlugin plugin;
private Connection connection;
private Path databasePath;
private BundledSqliteDriver bundledLoader;
private final ExecutorService io = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(4096), runnable -> {
Thread thread = new Thread(runnable, "isa-database");
thread.setDaemon(true);
return thread;
});
/** All runtime database work is serialized here, never on the server tick thread. */
public <T> CompletableFuture<T> submit(Callable<T> operation) {
CompletableFuture<T> result = new CompletableFuture<>();
try {
io.execute(() -> {
try { result.complete(operation.call()); }
catch (Throwable error) { result.completeExceptionally(error); }
});
} catch (RejectedExecutionException error) { result.completeExceptionally(error); }
return result;
}
public CompletableFuture<Void> auditAsync(String actor, String action, String target, String detail) {
return submit(() -> { audit(actor, action, target, detail); return null; });
}
public DatabaseManager(JavaPlugin plugin) { this.plugin = plugin; }
public synchronized void open() throws SQLException, IOException {
Path dataDirectory = plugin.getDataFolder().toPath().resolve("data");
Files.createDirectories(dataDirectory);
databasePath = dataDirectory.resolve("advancements.db");
// Explicitly select our bundled driver; Paper also registers a different SQLite driver.
var origin = DatabaseManager.class.getProtectionDomain().getCodeSource().getLocation();
if (origin.getPath().endsWith(".jar")) {
bundledLoader = new BundledSqliteDriver(origin);
connection = bundledLoader.connect("jdbc:sqlite:" + databasePath.toAbsolutePath());
} else {
connection = new org.sqlite.JDBC().connect("jdbc:sqlite:" + databasePath.toAbsolutePath(), new Properties());
}
try {
if (!connection.getMetaData().getDriverVersion().equals("3.50.3.0")) throw new SQLException("实际 SQLite 驱动版本与固定依赖 3.50.3.0 不符");
try (Statement statement = connection.createStatement()) {
statement.execute("PRAGMA foreign_keys=ON");
statement.execute("PRAGMA journal_mode=WAL");
statement.execute("PRAGMA synchronous=FULL");
statement.execute("PRAGMA busy_timeout=" + Math.clamp(plugin.getConfig().getInt("database.busy-timeout-millis", 5000), 0, 10000));
}
migrate();
} catch (SQLException error) {
try { connection.close(); } catch (SQLException closeError) { error.addSuppressed(closeError); }
connection = null;
throw error;
}
}
private void migrate() throws SQLException {
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)");
try (ResultSet rs = statement.executeQuery("SELECT COUNT(*) FROM schema_version")) {
if (rs.next() && rs.getInt(1) == 0) statement.executeUpdate("INSERT INTO schema_version(version) VALUES (0)");
}
int current;
try (ResultSet rs = statement.executeQuery("SELECT version FROM schema_version LIMIT 1")) {
current = rs.next() ? rs.getInt(1) : 0;
}
if (current < 1) {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS player_statistics (" +
"player_uuid TEXT NOT NULL, statistic_key TEXT NOT NULL, value REAL NOT NULL DEFAULT 0," +
"updated_at INTEGER NOT NULL, PRIMARY KEY(player_uuid, statistic_key))");
statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_player_statistics_key ON player_statistics(statistic_key)");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS player_achievement_data (" +
"player_uuid TEXT NOT NULL, achievement_id TEXT NOT NULL, condition_key TEXT NOT NULL," +
"value REAL NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL," +
"PRIMARY KEY(player_uuid, achievement_id, condition_key))");
statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_achievement_data_id ON player_achievement_data(achievement_id)");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS reward_claims (" +
"player_uuid TEXT NOT NULL, achievement_id TEXT NOT NULL, status TEXT NOT NULL," +
"attempts INTEGER NOT NULL DEFAULT 0, detail TEXT, updated_at INTEGER NOT NULL," +
"PRIMARY KEY(player_uuid, achievement_id))");
statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_reward_status ON reward_claims(status)");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS admin_audit_log (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, actor TEXT NOT NULL, action TEXT NOT NULL," +
"target TEXT, detail TEXT, created_at INTEGER NOT NULL)");
statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_audit_created ON admin_audit_log(created_at)");
statement.executeUpdate("UPDATE schema_version SET version=1");
}
if (current > SCHEMA_VERSION) throw new SQLException("数据库版本 " + current + " 高于插件支持版本 " + SCHEMA_VERSION);
connection.commit();
} catch (SQLException exception) {
connection.rollback();
throw exception;
} finally {
connection.setAutoCommit(true);
}
}
public synchronized Map<String, Double> loadStatistics(UUID playerId) throws SQLException {
ensureOpen();
Map<String, Double> result = new HashMap<>();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT statistic_key, value FROM player_statistics WHERE player_uuid=?")) {
statement.setString(1, playerId.toString());
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) result.put(rs.getString(1), rs.getDouble(2));
}
}
return result;
}
public synchronized void saveStatistics(Map<UUID, Map<String, Double>> batch) throws SQLException {
if (batch.isEmpty()) return;
ensureOpen();
String sql = "INSERT INTO player_statistics(player_uuid,statistic_key,value,updated_at) VALUES(?,?,?,?) " +
"ON CONFLICT(player_uuid,statistic_key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at";
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(sql)) {
long now = System.currentTimeMillis();
for (Map.Entry<UUID, Map<String, Double>> player : batch.entrySet()) {
for (Map.Entry<String, Double> statistic : player.getValue().entrySet()) {
statement.setString(1, player.getKey().toString());
statement.setString(2, statistic.getKey());
statement.setDouble(3, statistic.getValue());
statement.setLong(4, now);
statement.addBatch();
}
}
statement.executeBatch();
connection.commit();
} catch (SQLException exception) {
connection.rollback();
throw exception;
} finally {
connection.setAutoCommit(true);
}
}
public synchronized RewardStatus rewardStatus(UUID playerId, String achievementId) throws SQLException {
ensureOpen();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT status FROM reward_claims WHERE player_uuid=? AND achievement_id=?")) {
statement.setString(1, playerId.toString());
statement.setString(2, achievementId);
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next()) return RewardStatus.NONE;
try { return RewardStatus.valueOf(rs.getString(1)); }
catch (IllegalArgumentException ignored) { return RewardStatus.FAILED; }
}
}
}
public synchronized boolean beginReward(UUID playerId, String achievementId, boolean reclaim) throws SQLException {
ensureOpen();
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO reward_claims(player_uuid,achievement_id,status,attempts,detail,updated_at) VALUES(?,?,?,1,NULL,?) " +
"ON CONFLICT(player_uuid,achievement_id) DO UPDATE SET status='PENDING',attempts=attempts+1,detail=NULL,updated_at=excluded.updated_at " +
"WHERE reward_claims.status='CLAIMED' AND ?")) {
statement.setString(1, playerId.toString());
statement.setString(2, achievementId);
statement.setString(3, RewardStatus.PENDING.name());
statement.setLong(4, System.currentTimeMillis());
statement.setBoolean(5, reclaim);
return statement.executeUpdate() == 1;
}
}
public synchronized Reservation reserveReward(UUID playerId, String achievementId, boolean reclaim) throws SQLException {
ensureOpen();
RewardStatus status = rewardStatus(playerId, achievementId);
if (status == RewardStatus.PENDING || status == RewardStatus.FAILED) return Reservation.REVIEW_REQUIRED;
if (status == RewardStatus.CLAIMED && !reclaim) return Reservation.NO_REWARD;
if (status == RewardStatus.RESERVED) return Reservation.RESERVED;
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO reward_claims(player_uuid,achievement_id,status,attempts,detail,updated_at) VALUES(?,?,'RESERVED',1,NULL,?) " +
"ON CONFLICT(player_uuid,achievement_id) DO UPDATE SET status='RESERVED',attempts=attempts+1,detail=NULL,updated_at=excluded.updated_at " +
"WHERE reward_claims.status='CLAIMED' AND ?")) {
statement.setString(1, playerId.toString()); statement.setString(2, achievementId);
statement.setLong(3, System.currentTimeMillis()); statement.setBoolean(4, reclaim);
return statement.executeUpdate() == 1 ? Reservation.RESERVED : Reservation.REVIEW_REQUIRED;
}
}
public synchronized boolean startReward(UUID playerId, String achievementId) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"UPDATE reward_claims SET status='PENDING',updated_at=? WHERE player_uuid=? AND achievement_id=? AND status='RESERVED'")) {
statement.setLong(1, System.currentTimeMillis()); statement.setString(2, playerId.toString()); statement.setString(3, achievementId);
return statement.executeUpdate() == 1;
}
}
/** Only call when no game-side effect has run: a RESERVED record is safe to resume. */
public synchronized void releaseUnexecutedReward(UUID playerId, String achievementId) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"UPDATE reward_claims SET status='RESERVED',detail='not executed',updated_at=? WHERE player_uuid=? AND achievement_id=? AND status='PENDING'")) {
statement.setLong(1, System.currentTimeMillis()); statement.setString(2, playerId.toString()); statement.setString(3, achievementId); statement.executeUpdate();
}
}
public synchronized void finishReward(UUID playerId, String achievementId, boolean success, String detail) throws SQLException {
ensureOpen();
try (PreparedStatement statement = connection.prepareStatement(
"UPDATE reward_claims SET status=?,detail=?,updated_at=? WHERE player_uuid=? AND achievement_id=?")) {
statement.setString(1, success ? RewardStatus.CLAIMED.name() : RewardStatus.FAILED.name());
statement.setString(2, detail);
statement.setLong(3, System.currentTimeMillis());
statement.setString(4, playerId.toString());
statement.setString(5, achievementId);
statement.executeUpdate();
}
}
public synchronized void audit(String actor, String action, String target, String detail) {
try {
ensureOpen();
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO admin_audit_log(actor,action,target,detail,created_at) VALUES(?,?,?,?,?)")) {
statement.setString(1, actor);
statement.setString(2, action);
statement.setString(3, target);
statement.setString(4, detail);
statement.setLong(5, System.currentTimeMillis());
statement.executeUpdate();
}
} catch (SQLException exception) {
plugin.getLogger().severe("写入管理审计日志失败: " + exception.getMessage());
}
}
public synchronized Path backup() throws SQLException, IOException {
ensureOpen();
Path backupDirectory = plugin.getDataFolder().toPath().resolve("backups");
Files.createDirectories(backupDirectory);
String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault()).format(Instant.now());
Path snapshot = backupDirectory.resolve(timestamp + "-" + UUID.randomUUID());
Files.createDirectories(snapshot);
Path target = snapshot.resolve("advancements.db");
// VACUUM INTO creates a consistent SQLite snapshot, including committed WAL pages.
try (PreparedStatement statement = connection.prepareStatement("VACUUM INTO ?")) {
statement.setString(1, target.toAbsolutePath().toString()); statement.execute();
}
for (String name : List.of("config.yml", "advancements.yml", "messages.yml")) {
Path source = plugin.getDataFolder().toPath().resolve(name);
if (Files.exists(source)) Files.copy(source, snapshot.resolve(name), StandardCopyOption.COPY_ATTRIBUTES);
}
return target;
}
public Path databasePath() { return databasePath; }
private void ensureOpen() throws SQLException {
if (connection == null || connection.isClosed()) throw new SQLException("SQLite 连接未打开");
}
@Override public void close() throws SQLException {
io.shutdown();
try {
if (!io.awaitTermination(30, TimeUnit.SECONDS)) throw new SQLException("数据库队列未在 30 秒内排空;请保留 WAL 文件并检查日志");
} catch (InterruptedException error) { Thread.currentThread().interrupt(); throw new SQLException("等待数据库关闭被中断", error); }
synchronized (this) {
try {
if (connection != null && !connection.isClosed()) {
try (Statement statement = connection.createStatement()) { statement.execute("PRAGMA wal_checkpoint(TRUNCATE)"); }
finally { connection.close(); }
}
} finally { if (bundledLoader != null) try { bundledLoader.close(); } catch (IOException error) { throw new SQLException("关闭 SQLite 类加载器失败", error); } }
}
}
public enum RewardStatus { NONE, RESERVED, PENDING, CLAIMED, FAILED }
public enum Reservation { RESERVED, NO_REWARD, REVIEW_REQUIRED }
}
@@ -0,0 +1,128 @@
package top.itxiaohui.serveradvancements.gui;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.advancement.AdvancementManager;
import top.itxiaohui.serveradvancements.condition.ConditionEngine;
import top.itxiaohui.serveradvancements.config.ConfigurationManager;
import top.itxiaohui.serveradvancements.model.AchievementDefinition;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class AdminGui implements Listener {
public static final String PERMISSION = "itxiaohui.serveradvancements.admin";
private final JavaPlugin plugin;
private final ConfigurationManager configuration;
private final AdvancementManager advancements;
private final ConditionEngine conditions;
public AdminGui(JavaPlugin plugin, ConfigurationManager configuration, AdvancementManager advancements,
ConditionEngine conditions) {
this.plugin = plugin;
this.configuration = configuration;
this.advancements = advancements;
this.conditions = conditions;
}
public void open(Player player, int page) {
if (!player.hasPermission(PERMISSION)) return;
List<AchievementDefinition> all = new ArrayList<>(configuration.definitions().values());
int maxPage = Math.max(0, (all.size() - 1) / 45);
page = Math.max(0, Math.min(page, maxPage));
Holder holder = new Holder(page);
Inventory inventory = Bukkit.createInventory(holder, 54, Component.text("服务器成就管理 第 " + (page + 1) + " 页"));
holder.inventory = inventory;
int start = page * 45;
for (int i = start; i < Math.min(start + 45, all.size()); i++) {
AchievementDefinition definition = all.get(i);
Material material = Material.matchMaterial(definition.icon());
ItemStack item = new ItemStack(material == null ? Material.BARRIER : material);
ItemMeta meta = item.getItemMeta();
meta.displayName(Component.text(definition.name(), definition.enabled() ? NamedTextColor.GOLD : NamedTextColor.GRAY));
meta.lore(List.of(
Component.text("ID: " + definition.id(), NamedTextColor.DARK_GRAY),
Component.text(definition.description(), NamedTextColor.GRAY),
Component.text("左键: 详情 | 右键: 授予自己", NamedTextColor.YELLOW),
Component.text("Shift+左键: 启用/禁用 | Q: 撤销自己", NamedTextColor.YELLOW)));
item.setItemMeta(meta);
inventory.setItem(i - start, item);
holder.ids[i - start] = definition.id();
}
inventory.setItem(45, button(Material.ARROW, "上一页"));
inventory.setItem(47, button(Material.PLAYER_HEAD, "玩家进度:/isa progress <玩家>"));
inventory.setItem(48, button(Material.BARRIER, "删除:/isa delete <id> confirm"));
inventory.setItem(49, button(Material.WRITABLE_BOOK, "创建:使用 /isa create <id>"));
inventory.setItem(50, button(Material.REDSTONE, "重载配置"));
inventory.setItem(51, button(Material.CHEST, "备份:使用 /isa backup"));
inventory.setItem(53, button(Material.ARROW, "下一页"));
player.openInventory(inventory);
}
private ItemStack button(Material material, String name) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.displayName(Component.text(name, NamedTextColor.AQUA));
item.setItemMeta(meta);
return item;
}
@EventHandler(ignoreCancelled = true)
public void onClick(InventoryClickEvent event) {
if (!(event.getInventory().getHolder(false) instanceof Holder holder)) return;
event.setCancelled(true);
if (!(event.getWhoClicked() instanceof Player player) || !player.hasPermission(PERMISSION)) {
event.getWhoClicked().closeInventory();
return;
}
int slot = event.getRawSlot();
if (slot < 0 || slot >= 54) return;
if (slot == 45) { open(player, holder.page - 1); return; }
if (slot == 53) { open(player, holder.page + 1); return; }
if (slot == 50) { player.closeInventory(); player.performCommand("isa reload"); return; }
String id = slot < 45 ? holder.ids[slot] : null;
if (id == null) return;
AchievementDefinition definition = configuration.get(id);
if (definition == null) return;
if (event.isShiftClick() && event.isLeftClick()) {
try {
configuration.setEnabled(id, !definition.enabled());
player.closeInventory();
player.performCommand("isa reload");
} catch (IOException exception) { player.sendMessage(Component.text("保存失败: " + exception.getMessage(), NamedTextColor.RED)); }
} else if (event.getClick() == org.bukkit.event.inventory.ClickType.DROP || event.getClick() == org.bukkit.event.inventory.ClickType.CONTROL_DROP) {
player.performCommand("isa revoke " + player.getName() + " " + id);
} else if (event.isRightClick()) {
player.performCommand("isa give " + player.getName() + " " + id);
} else {
player.sendMessage(Component.text(id + " — " + definition.description(), NamedTextColor.GOLD));
player.sendMessage(Component.text("父级: " + definition.parent() + ",条件数: " + definition.conditions().size(), NamedTextColor.GRAY));
}
}
@EventHandler(ignoreCancelled = true)
public void onDrag(InventoryDragEvent event) {
if (event.getInventory().getHolder(false) instanceof Holder) event.setCancelled(true);
}
private static final class Holder implements InventoryHolder {
private final int page;
private final String[] ids = new String[45];
private Inventory inventory;
private Holder(int page) { this.page = page; }
@Override public Inventory getInventory() { return inventory; }
}
}
@@ -0,0 +1,158 @@
package top.itxiaohui.serveradvancements.listener;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.inventory.FurnaceExtractEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityBreedEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.advancement.AdvancementManager;
import top.itxiaohui.serveradvancements.condition.ConditionEngine;
import top.itxiaohui.serveradvancements.model.ConditionType;
import top.itxiaohui.serveradvancements.statistics.StatisticsService;
public final class PlayerActivityListener implements Listener {
private final JavaPlugin plugin;
private final StatisticsService statistics;
private final ConditionEngine conditions;
private final AdvancementManager advancements;
public PlayerActivityListener(JavaPlugin plugin, StatisticsService statistics, ConditionEngine conditions,
AdvancementManager advancements) {
this.plugin = plugin;
this.statistics = statistics;
this.conditions = conditions;
this.advancements = advancements;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
boolean firstJoin = !player.hasPlayedBefore();
var loadedFuture = statistics.beginSession(player);
if (firstJoin) conditions.mark(player, ConditionType.FIRST_JOIN, "");
conditions.mark(player, ConditionType.VISIT_DIMENSION, player.getWorld().getKey().toString());
conditions.setLevel(player, player.getLevel());
loadedFuture.thenAccept(loaded -> {
if (!loaded) return;
plugin.getServer().getScheduler().runTask(plugin, () -> {
if (!player.isOnline()) return;
conditions.evaluate(player);
});
});
plugin.getServer().getScheduler().runTaskLater(plugin, () -> {
if (!player.isOnline()) return;
advancements.ensureRoot(player);
}, 20L);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
statistics.endSession(event.getPlayer().getUniqueId());
statistics.flushSoon();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBreak(BlockBreakEvent event) {
conditions.record(event.getPlayer(), ConditionType.MINE_BLOCK, event.getBlock().getType().getKey().toString(), 1);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPickup(EntityPickupItemEvent event) {
if (!(event.getEntity() instanceof Player player)) return;
ItemStack stack = event.getItem().getItemStack();
conditions.record(player, ConditionType.COLLECT_ITEM, stack.getType().getKey().toString(), stack.getAmount());
conditions.record(player, ConditionType.OBTAIN_ITEM, stack.getType().getKey().toString(), stack.getAmount());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onDeath(EntityDeathEvent event) {
Player killer = event.getEntity().getKiller();
if (killer != null) conditions.record(killer, ConditionType.KILL_MOB, event.getEntityType().getKey().toString(), 1);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onWorldChange(PlayerChangedWorldEvent event) {
conditions.mark(event.getPlayer(), ConditionType.VISIT_DIMENSION, event.getPlayer().getWorld().getKey().toString());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMove(PlayerMoveEvent event) {
Location from = event.getFrom();
Location to = event.getTo();
if (to == null || from.getWorld() != to.getWorld()) return;
double distance = from.distance(to);
if (distance > 0 && distance < 100) conditions.record(event.getPlayer(), ConditionType.MOVE_DISTANCE, "", distance);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCraft(CraftItemEvent event) {
// A click is only an attempt (NOTHING, full inventory, etc.). Count the native
// successful ITEM_CRAFTED statistic below, not an estimated recipe matrix.
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onStatistic(PlayerStatisticIncrementEvent event) {
if (event.getStatistic() != Statistic.CRAFT_ITEM || event.getMaterial() == null) return;
long amount = (long) event.getNewValue() - event.getPreviousValue();
if (amount <= 0) return;
conditions.record(event.getPlayer(), ConditionType.CRAFT_ITEM, event.getMaterial().getKey().toString(), amount);
conditions.record(event.getPlayer(), ConditionType.OBTAIN_ITEM, event.getMaterial().getKey().toString(), amount);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBreed(EntityBreedEvent event) {
Entity breeder = event.getBreeder();
if (breeder instanceof Player player)
conditions.record(player, ConditionType.BREED_MOB, event.getEntityType().getKey().toString(), 1);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onLevel(PlayerLevelChangeEvent event) {
conditions.setLevel(event.getPlayer(), event.getNewLevel());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEat(PlayerItemConsumeEvent event) {
if (event.getItem().getType().isEdible())
conditions.event(event.getPlayer(), "eat_food", event.getItem().getType().getKey().toString(), 1);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onCook(FurnaceExtractEvent event) {
if (event.getItemType().isEdible())
conditions.event(event.getPlayer(), "cook_food", event.getItemType().getKey().toString(), event.getItemAmount());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onTame(EntityTameEvent event) {
if (event.getOwner() instanceof Player player)
conditions.event(player, "tame_animal", event.getEntityType().getKey().toString(), 1);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onFish(PlayerFishEvent event) {
if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && event.getCaught() instanceof org.bukkit.entity.Item item)
conditions.event(event.getPlayer(), "fish_item", item.getItemStack().getType().getKey().toString(), item.getItemStack().getAmount());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlace(BlockPlaceEvent event) {
if (event.canBuild()) conditions.event(event.getPlayer(), "place_block", event.getBlockPlaced().getType().getKey().toString(), 1);
}
}
@@ -0,0 +1,10 @@
package top.itxiaohui.serveradvancements.model;
import java.util.List;
public record AchievementDefinition(
String id, String name, String description, String icon, AdvancementFrame frame,
String parent, double x, double y, List<ConditionDefinition> conditions,
boolean hidden, boolean showToast, boolean announceChat, boolean enabled,
RewardDefinition rewards) {
}
@@ -0,0 +1,11 @@
package top.itxiaohui.serveradvancements.model;
import java.util.Locale;
public enum AdvancementFrame {
TASK, GOAL, CHALLENGE;
public static AdvancementFrame parse(String value) {
return valueOf(value.trim().toUpperCase(Locale.ROOT));
}
}
@@ -0,0 +1,62 @@
package top.itxiaohui.serveradvancements.model;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public record ConditionDefinition(ConditionType type, Map<String, Object> parameters) {
public ConditionDefinition {
parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters));
}
public String string(String key, String fallback) {
Object value = parameters.get(key);
return value == null ? fallback : String.valueOf(value);
}
public double number(String key, double fallback) {
Object value = parameters.get(key);
if (value instanceof Number number) return number.doubleValue();
try { return value == null ? fallback : Double.parseDouble(String.valueOf(value)); }
catch (NumberFormatException ignored) { return Double.NaN; }
}
public String statisticKey() {
return switch (type) {
case FIRST_JOIN -> "first_join";
case ONLINE_TIME -> "online_time_ms";
case MINE_BLOCK -> "mine_block:" + string("block", "");
case COLLECT_ITEM -> "collect_item:" + string("item", "");
case OBTAIN_ITEM -> "obtain_item:" + string("item", "");
case KILL_MOB -> "kill_mob:" + string("entity", "*");
case VISIT_DIMENSION -> "visit_dimension:" + string("dimension", "");
case MOVE_DISTANCE -> "move_distance";
case REACH_LOCATION -> "reach_location:" + string("world", "world") + ":" + string("id", string("x", "") + "," + string("y", "") + "," + string("z", "") + "," + string("radius", "5"));
case CRAFT_ITEM -> "craft_item:" + string("item", "");
case BREED_MOB -> "breed_mob:" + string("entity", "*");
case EXPERIENCE_LEVEL -> "experience_level";
case COMPLETE_ACHIEVEMENT -> "achievement:" + string("achievement", "");
case MANUAL -> "manual";
case PLAYER_STATISTIC -> "player_statistic";
case VANILLA_ADVANCEMENT -> "vanilla_advancement";
case INVENTORY_SET -> "inventory_set";
case VISIT_BIOME -> "visit_biome:" + string("biome", "");
case VISIT_STRUCTURE -> "visit_structure";
case ALTITUDE -> "altitude";
case EVENT_COUNT, EVENT_DISTINCT -> "event:" + string("event", "");
};
}
public double target() {
if (type == ConditionType.ONLINE_TIME) {
double amount = number("amount", 1);
return switch (string("unit", "seconds").toLowerCase(java.util.Locale.ROOT)) {
case "minutes", "minute" -> amount * 60_000D;
case "hours", "hour" -> amount * 3_600_000D;
case "seconds", "second" -> amount * 1_000D;
default -> Double.NaN;
};
}
return number("amount", 1);
}
}
@@ -0,0 +1,14 @@
package top.itxiaohui.serveradvancements.model;
import java.util.Locale;
public enum ConditionType {
FIRST_JOIN, ONLINE_TIME, MINE_BLOCK, COLLECT_ITEM, OBTAIN_ITEM, KILL_MOB, VISIT_DIMENSION,
MOVE_DISTANCE, REACH_LOCATION, CRAFT_ITEM, BREED_MOB, EXPERIENCE_LEVEL,
COMPLETE_ACHIEVEMENT, MANUAL, PLAYER_STATISTIC, VANILLA_ADVANCEMENT, INVENTORY_SET,
VISIT_BIOME, VISIT_STRUCTURE, ALTITUDE, EVENT_COUNT, EVENT_DISTINCT;
public static ConditionType parse(String value) {
return valueOf(value.trim().toUpperCase(Locale.ROOT));
}
}
@@ -0,0 +1,8 @@
package top.itxiaohui.serveradvancements.model;
import java.util.List;
public record RewardDefinition(int experience, List<RewardItem> items, List<String> commands,
boolean allowReclaim, String completionMessage) {
public record RewardItem(String material, int amount) {}
}
@@ -0,0 +1,124 @@
package top.itxiaohui.serveradvancements.reward;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.config.MessageService;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import top.itxiaohui.serveradvancements.model.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.BooleanSupplier;
/** Durable reservation -> execution intent -> game-side effects -> durable result. */
public final class RewardService implements AutoCloseable {
public enum Outcome { COMPLETED, RESTORED_WITHOUT_REWARD, ALREADY_COMPLETE, IN_FLIGHT, REVIEW_REQUIRED, RETRY_LATER }
private record Key(UUID player, String achievement) { }
private final JavaPlugin plugin;
private final DatabaseManager database;
private final MessageService messages;
private final Executor mainThread;
private final Set<Key> inFlight = ConcurrentHashMap.newKeySet();
private volatile boolean closed;
public RewardService(JavaPlugin plugin, DatabaseManager database, MessageService messages) {
this(plugin, database, messages, task -> Bukkit.getScheduler().runTask(plugin, task));
}
public RewardService(JavaPlugin plugin, DatabaseManager database, MessageService messages, Executor mainThread) {
this.plugin = plugin; this.database = database; this.messages = messages; this.mainThread = mainThread;
}
public boolean isInFlight(UUID id, String achievement) { return inFlight.contains(new Key(id, achievement)); }
public CompletableFuture<Outcome> grant(Player player, AchievementDefinition achievement) {
return complete(player, achievement, () -> true, () -> { });
}
public CompletableFuture<Outcome> complete(Player player, AchievementDefinition achievement, BooleanSupplier award, Runnable completed) {
Key key = new Key(player.getUniqueId(), achievement.id());
if (closed) return CompletableFuture.completedFuture(Outcome.RETRY_LATER);
if (!inFlight.add(key)) return CompletableFuture.completedFuture(Outcome.IN_FLIGHT);
CompletableFuture<Outcome> result = new CompletableFuture<>();
result.whenComplete((value, error) -> inFlight.remove(key));
database.submit(() -> database.reserveReward(key.player(), key.achievement(), achievement.rewards().allowReclaim()))
.whenComplete((reservation, error) -> {
if (error != null) { failBeforeExecution(result, key, error); return; }
if (reservation == DatabaseManager.Reservation.REVIEW_REQUIRED) { result.complete(Outcome.REVIEW_REQUIRED); return; }
if (reservation == DatabaseManager.Reservation.NO_REWARD) {
onMain(() -> {
if (!player.isOnline()) { result.complete(Outcome.RETRY_LATER); return; }
if (award.getAsBoolean()) { completed.run(); result.complete(Outcome.RESTORED_WITHOUT_REWARD); }
else result.complete(Outcome.ALREADY_COMPLETE);
}, () -> result.complete(Outcome.RETRY_LATER), result);
return;
}
// PENDING is persisted before awarding a native criterion or running any reward.
database.submit(() -> database.startReward(key.player(), key.achievement())).whenComplete((started, startError) -> {
if (startError != null) { failBeforeExecution(result, key, startError); return; }
if (!started) { result.complete(Outcome.REVIEW_REQUIRED); return; }
Runnable notExecuted = () -> database.submit(() -> {
database.releaseUnexecutedReward(key.player(), key.achievement()); return null;
}).whenComplete((ignored, releaseError) -> result.complete(Outcome.RETRY_LATER));
onMain(() -> {
if (!player.isOnline()) { notExecuted.run(); return; }
if (!award.getAsBoolean()) { notExecuted.run(); return; }
// The native state is now done; failed or uncertain effects are never automatically replayed.
boolean success = false;
String detail = "ok";
try { execute(player, achievement); success = true; }
catch (RuntimeException executionError) {
detail = executionError.toString();
plugin.getLogger().severe("奖励部分失败,需要人工核查 " + key + ": " + detail);
}
completed.run();
final boolean delivered = success; final String deliveryDetail = detail;
database.submit(() -> { database.finishReward(key.player(), key.achievement(), delivered, deliveryDetail); return null; })
.whenComplete((ignored, finishError) -> {
if (finishError != null) plugin.getLogger().severe("奖励结果保存失败,PENDING 已保留,禁止自动重放 " + key + ": " + finishError);
result.complete(delivered && finishError == null ? Outcome.COMPLETED : Outcome.REVIEW_REQUIRED);
});
}, notExecuted, result);
});
});
return result;
}
private void onMain(Runnable work, Runnable abort, CompletableFuture<Outcome> result) {
if (closed) { abort.run(); return; }
try {
mainThread.execute(() -> {
if (closed) { abort.run(); return; }
try { work.run(); }
catch (RuntimeException error) { plugin.getLogger().severe("奖励状态转换异常,保留记录核查: " + error); result.complete(Outcome.REVIEW_REQUIRED); }
});
} catch (RuntimeException error) { abort.run(); }
}
private void failBeforeExecution(CompletableFuture<Outcome> result, Key key, Throwable error) {
plugin.getLogger().warning("奖励预约失败,尚未授予进度,允许稍后重试 " + key + ": " + error);
result.complete(Outcome.RETRY_LATER);
}
private void execute(Player player, AchievementDefinition achievement) {
RewardDefinition reward = achievement.rewards();
if (reward.experience() > 0) player.giveExp(reward.experience());
for (RewardDefinition.RewardItem configured : reward.items()) {
Material material = Material.matchMaterial(configured.material());
if (material == null || configured.amount() < 1 || configured.amount() > 4096) throw new IllegalStateException("奖励物品无效");
Map<Integer, ItemStack> overflow = player.getInventory().addItem(new ItemStack(material, configured.amount()));
overflow.values().forEach(item -> player.getWorld().dropItemNaturally(player.getLocation(), item));
}
for (String raw : reward.commands()) if (!Bukkit.dispatchCommand(Bukkit.getConsoleSender(), renderCommand(raw, player))) throw new IllegalStateException("命令返回失败: " + raw);
if (!reward.completionMessage().isBlank()) player.sendMessage(reward.completionMessage());
else messages.send(player, "completed", Map.of("name", achievement.name()));
}
private String renderCommand(String input, Player player) {
if (input.length() > 1024 || input.indexOf('\n') >= 0 || input.indexOf('\r') >= 0) throw new IllegalArgumentException("奖励命令无效");
return input.replace("{player}", player.getName().replaceAll("[^A-Za-z0-9_]", ""))
.replace("{uuid}", player.getUniqueId().toString()).replaceFirst("^/", "");
}
@Override public void close() { closed = true; }
}
@@ -0,0 +1,150 @@
package top.itxiaohui.serveradvancements.statistics;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import top.itxiaohui.serveradvancements.database.DatabaseManager;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.*;
/** Versioned snapshots: never hold the cache lock during JDBC work. */
public final class StatisticsService implements AutoCloseable {
private final JavaPlugin plugin;
private final DatabaseManager database;
private final Object cacheLock = new Object();
private final Map<UUID, State> states = new HashMap<>();
private final Map<UUID, Long> sessions = new HashMap<>();
private final Set<UUID> activePlayers = new HashSet<>();
private BukkitTask flushTask;
private CompletableFuture<Void> scheduledFlush;
private volatile boolean lastFlushSucceeded = true;
private static final class State {
final Map<String, Double> values = new HashMap<>();
final Map<String, Double> additions = new HashMap<>();
final Map<String, Double> maxima = new HashMap<>();
boolean loaded;
long version;
long savedVersion;
CompletableFuture<Boolean> loading;
}
public StatisticsService(JavaPlugin plugin, DatabaseManager database) { this.plugin = plugin; this.database = database; }
public void start() {
long ticks = Math.clamp(plugin.getConfig().getLong("statistics.flush-interval-seconds", 30), 5, 3600) * 20;
flushTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> { updateOnlineSessions(); flushSoon(); }, ticks, ticks);
}
/** Synchronous diagnostic entry point; runtime joins use loadAsync instead. */
public void load(UUID id) {
State state;
synchronized (cacheLock) { state = states.computeIfAbsent(id, ignored -> new State()); if (state.loaded) return; }
try {
Map<String, Double> persisted = database.loadStatistics(id);
synchronized (cacheLock) {
if (state.loaded) return;
state.values.putAll(persisted);
state.additions.forEach((key, value) -> state.values.merge(key, value, Double::sum));
state.maxima.forEach((key, value) -> state.values.merge(key, value, Math::max));
state.additions.clear(); state.maxima.clear(); state.loaded = true;
}
} catch (SQLException error) { plugin.getLogger().severe("读取统计失败,未就绪数据不会覆盖数据库,将重试 " + id + ": " + error.getMessage()); }
}
public CompletableFuture<Boolean> loadAsync(UUID id) {
synchronized (cacheLock) {
State state = states.computeIfAbsent(id, ignored -> new State());
if (state.loaded) return CompletableFuture.completedFuture(true);
if (state.loading != null && !state.loading.isDone()) return state.loading;
state.loading = database.submit(() -> { load(id); return isReady(id); });
return state.loading;
}
}
public CompletableFuture<Boolean> beginSession(Player player) {
UUID id = player.getUniqueId();
synchronized (cacheLock) {
states.computeIfAbsent(id, ignored -> new State());
activePlayers.add(id);
if (plugin.getConfig().getBoolean("statistics.online-time-enabled", true)) sessions.putIfAbsent(id, System.nanoTime());
}
return loadAsync(id);
}
public void endSession(UUID id) {
synchronized (cacheLock) { activePlayers.remove(id); Long start = sessions.remove(id); if (start != null) increment(id, "online_time_ms", Math.max(0, (System.nanoTime() - start) / 1_000_000D)); }
}
public void updateOnlineSessions() {
synchronized (cacheLock) {
long now = System.nanoTime();
sessions.replaceAll((id, start) -> { increment(id, "online_time_ms", Math.max(0, (now - start) / 1_000_000D)); return now; });
}
}
public boolean isReady(UUID id) { synchronized (cacheLock) { State state = states.get(id); return state != null && state.loaded; } }
public double increment(UUID id, String key, double amount) {
synchronized (cacheLock) {
if (!Double.isFinite(amount) || amount < 0) return get(id, key);
State state = states.computeIfAbsent(id, ignored -> new State());
Map<String, Double> target = state.loaded ? state.values : state.additions;
double value = target.getOrDefault(key, 0D) + amount;
if (!Double.isFinite(value)) return get(id, key);
target.put(key, value); state.version++;
return get(id, key);
}
}
public void setMax(UUID id, String key, double value) {
if (!Double.isFinite(value) || value < 0) return;
synchronized (cacheLock) {
State state = states.computeIfAbsent(id, ignored -> new State());
Map<String, Double> target = state.loaded ? state.values : state.maxima;
if (value > target.getOrDefault(key, 0D)) { target.put(key, value); state.version++; }
}
}
public double get(UUID id, String key) {
synchronized (cacheLock) {
State state = states.get(id); if (state == null) return 0;
return Math.max(state.values.getOrDefault(key, 0D) + state.additions.getOrDefault(key, 0D), state.maxima.getOrDefault(key, 0D));
}
}
public Map<String, Double> snapshot(UUID id) { synchronized (cacheLock) { State state = states.get(id); return state == null ? Map.of() : Map.copyOf(state.values); } }
public int cachedPlayerCount() { synchronized (cacheLock) { return states.size(); } }
public CompletableFuture<Void> flushSoon() {
synchronized (cacheLock) {
if (scheduledFlush != null && !scheduledFlush.isDone()) return scheduledFlush;
scheduledFlush = flushAllAsync(); return scheduledFlush;
}
}
public CompletableFuture<Void> flushAllAsync() {
return database.submit(() -> {
flushAsyncBody();
if (!lastFlushSucceeded) throw new SQLException("有统计尚未保存,备份/关闭不能视为已完整刷盘");
return null;
});
}
private void flushAsyncBody() {
List<UUID> awaiting;
synchronized (cacheLock) { awaiting = states.entrySet().stream().filter(e -> !e.getValue().loaded).map(Map.Entry::getKey).toList(); }
for (UUID id : awaiting) load(id);
lastFlushSucceeded = true;
Map<UUID, Map<String, Double>> batch = new HashMap<>(); Map<UUID, Long> versions = new HashMap<>();
synchronized (cacheLock) {
states.forEach((id, state) -> {
if (!state.loaded && state.version != state.savedVersion) lastFlushSucceeded = false;
if (state.loaded && state.version != state.savedVersion) { batch.put(id, Map.copyOf(state.values)); versions.put(id, state.version); }
});
}
try {
if (!batch.isEmpty()) database.saveStatistics(batch);
synchronized (cacheLock) {
versions.forEach((id, version) -> { State state = states.get(id); if (state != null) state.savedVersion = version; });
states.entrySet().removeIf(entry -> { State state = entry.getValue(); return state.loaded && state.version == state.savedVersion && !activePlayers.contains(entry.getKey()); });
}
} catch (SQLException error) { lastFlushSucceeded = false; plugin.getLogger().severe("批量保存失败,内存版本保留以重试: " + error.getMessage()); }
}
public void flushBlocking() {
updateOnlineSessions();
try { flushAllAsync().get(30, TimeUnit.SECONDS); }
catch (Exception error) { throw new IllegalStateException("统计刷盘失败,已保留缓存: " + error.getMessage(), error); }
}
@Override public void close() {
if (flushTask != null) flushTask.cancel();
synchronized (cacheLock) { for (UUID id : new ArrayList<>(activePlayers)) endSession(id); }
flushBlocking();
}
}
+218
View File
@@ -0,0 +1,218 @@
achievements:
first_join:
name: "首次加入服务器"
description: "欢迎来到服务器"
icon: "minecraft:oak_door"
frame: task
parent: root
display: { x: 1, y: 3 }
hidden: false
show-toast: true
announce-chat: false
enabled: true
conditions:
- { type: first_join }
rewards:
experience: 10
allow-reclaim: false
items: []
commands: []
first_log:
name: "第一块木头"
description: "累计挖掘 1 个橡木原木"
icon: "minecraft:oak_log"
frame: task
parent: root
display: { x: 1, y: 0 }
enabled: true
conditions:
- { type: mine_block, block: "minecraft:oak_log", amount: 1 }
rewards: { experience: 10, items: [], commands: [] }
mineral_collector:
name: "矿物收藏家"
description: "累计挖掘 32 个铁矿石"
icon: "minecraft:iron_ore"
frame: goal
parent: first_log
display: { x: 2, y: 0 }
enabled: true
conditions:
- { type: mine_block, block: "minecraft:iron_ore", amount: 32 }
rewards: { experience: 50, items: [], commands: [] }
diamond_collector:
name: "钻石收藏家"
description: "累计拾取 64 个钻石"
icon: "minecraft:diamond"
frame: goal
parent: mineral_collector
display: { x: 3, y: 0 }
enabled: true
conditions:
- { type: collect_item, item: "minecraft:diamond", amount: 64 }
rewards:
experience: 100
items:
- { item: "minecraft:emerald", amount: 3 }
commands: []
netherite_collector:
name: "下界合金收藏家"
description: "累计拾取 4 个下界合金锭"
icon: "minecraft:netherite_ingot"
frame: challenge
parent: diamond_collector
display: { x: 4, y: 0 }
enabled: true
conditions:
- { type: collect_item, item: "minecraft:netherite_ingot", amount: 4 }
rewards: { experience: 250, items: [], commands: [] }
first_combat:
name: "初次战斗"
description: "击杀任意一只生物"
icon: "minecraft:iron_sword"
frame: task
parent: root
display: { x: 1, y: -2 }
enabled: true
conditions:
- { type: kill_mob, entity: "*", amount: 1 }
rewards: { experience: 10, items: [], commands: [] }
zombie_hunter:
name: "僵尸猎人"
description: "累计击杀 25 只僵尸"
icon: "minecraft:rotten_flesh"
frame: goal
parent: first_combat
display: { x: 2, y: -2 }
enabled: true
conditions:
- { type: kill_mob, entity: "minecraft:zombie", amount: 25 }
rewards: { experience: 80, items: [], commands: [] }
skeleton_slayer:
name: "骷髅克星"
description: "累计击杀 25 只骷髅"
icon: "minecraft:bone"
frame: goal
parent: first_combat
display: { x: 2, y: -1 }
enabled: true
conditions:
- { type: kill_mob, entity: "minecraft:skeleton", amount: 25 }
rewards: { experience: 80, items: [], commands: [] }
ender_dragon:
name: "末影龙挑战者"
description: "亲手击杀末影龙"
icon: "minecraft:dragon_head"
frame: challenge
parent: zombie_hunter
display: { x: 3, y: -2 }
enabled: true
conditions:
- { type: kill_mob, entity: "minecraft:ender_dragon", amount: 1 }
rewards: { experience: 500, items: [], commands: [] }
wither_conqueror:
name: "凋灵征服者"
description: "亲手击杀凋灵"
icon: "minecraft:nether_star"
frame: challenge
parent: skeleton_slayer
display: { x: 3, y: -1 }
enabled: true
conditions:
- { type: kill_mob, entity: "minecraft:wither", amount: 1 }
rewards: { experience: 500, items: [], commands: [] }
first_explore:
name: "初次探索"
description: "累计移动 1000 格"
icon: "minecraft:compass"
frame: task
parent: root
display: { x: 1, y: 1 }
enabled: true
conditions:
- { type: move_distance, amount: 1000 }
rewards: { experience: 30, items: [], commands: [] }
enter_nether:
name: "进入下界"
description: "首次进入下界"
icon: "minecraft:obsidian"
frame: task
parent: first_explore
display: { x: 2, y: 1 }
enabled: true
conditions:
- { type: visit_dimension, dimension: "minecraft:the_nether" }
rewards: { experience: 50, items: [], commands: [] }
visit_end:
name: "末地探险家"
description: "首次进入末地"
icon: "minecraft:end_stone"
frame: goal
parent: enter_nether
display: { x: 3, y: 1 }
enabled: true
conditions:
- { type: visit_dimension, dimension: "minecraft:the_end" }
rewards: { experience: 100, items: [], commands: [] }
traveler:
name: "远行者"
description: "累计移动 10000 格"
icon: "minecraft:elytra"
frame: goal
parent: first_explore
display: { x: 3, y: 2 }
enabled: true
conditions:
- { type: move_distance, amount: 10000 }
rewards: { experience: 150, items: [], commands: [] }
online_10h:
name: "累计在线 10 小时"
description: "在服务器累计在线 10 小时"
icon: "minecraft:clock"
frame: goal
parent: first_join
display: { x: 2, y: 3 }
enabled: true
conditions:
- { type: online_time, amount: 10, unit: hours }
rewards: { experience: 100, items: [], commands: [] }
online_100h:
name: "累计在线 100 小时"
description: "在服务器累计在线 100 小时"
icon: "minecraft:clock"
frame: challenge
parent: online_10h
display: { x: 3, y: 3 }
enabled: true
conditions:
- { type: online_time, amount: 100, unit: hours }
rewards: { experience: 1000, items: [], commands: [] }
survival_master:
name: "完成全部生存成就"
description: "完成木头、矿物、钻石和下界合金成就"
icon: "minecraft:totem_of_undying"
frame: challenge
parent: netherite_collector
display: { x: 5, y: 0 }
enabled: true
conditions:
- { type: complete_achievement, achievement: first_log }
- { type: complete_achievement, achievement: mineral_collector }
- { type: complete_achievement, achievement: diamond_collector }
- { type: complete_achievement, achievement: netherite_collector }
rewards: { experience: 1000, items: [], commands: [] }
+24
View File
@@ -0,0 +1,24 @@
language: zh_CN
root:
id: root
title: "服务器成就树"
description: "记录你在本服务器中的冒险旅程"
icon: "minecraft:nether_star"
background: "minecraft:textures/block/deepslate_tiles.png"
auto-grant: true
defaults:
show-toast: true
announce-chat: false
allow-reward-reclaim: false
statistics:
online-time-enabled: true
flush-interval-seconds: 30
database:
busy-timeout-millis: 5000
logging:
debug: false
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
prefix: "&8[&6服务器成就&8] &r"
no-permission: "&c你没有权限执行此操作。"
player-only: "&c该命令只能由游戏内玩家执行。"
unknown-achievement: "&c不存在成就:{id}"
invalid-player: "&c找不到玩家:{player}"
granted: "&a已向 {player} 授予成就 {id}。"
revoked: "&e已撤销 {player} 的成就 {id}(累计统计未清除)。"
completed: "&a你完成了服务器成就:&6{name}"
reloaded: "&a配置未发生定义变化;消息已重载,当前有 {count} 个有效成就。"
reload-failed: "&c配置重载失败,继续使用旧定义。详情见控制台。"
reload-restart-required: "&e配置校验通过,但 Advancement 定义发生变化。为保证安全,本次未应用;请正常重启服务器。"
already-completed: "&e{player} 已经完成成就 {id},未重复发放奖励。"
created: "&a已在 advancements.yml 创建成就 {id},请编辑后执行 /isa reload。"
deleted: "&e已删除成就 {id},请执行 /isa reload 应用。"
delete-confirm: "&c再次执行 /isa delete {id} confirm 确认删除。玩家原版进度不会被批量清理。"
backup-created: "&a备份已创建:{path}"
validation-ok: "&a配置校验通过,共 {count} 个成就。"
+29
View File
@@ -0,0 +1,29 @@
name: ItxiaohuiServerAdvancements
version: '${version}'
main: top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements
api-version: '1.21'
description: 使用 Minecraft 原版进度界面的服务器成就树
author: itxiaohui
load: POSTWORLD
commands:
isa:
description: 服务器成就树管理命令
usage: /isa help
aliases: [itxiaohuiadvancements]
permissions:
itxiaohui.serveradvancements.admin:
description: 管理服务器成就树全部功能
default: op
children:
itxiaohui.serveradvancements.give: true
itxiaohui.serveradvancements.revoke: true
itxiaohui.serveradvancements.view: true
itxiaohui.serveradvancements.give:
description: 手动授予服务器成就
default: op
itxiaohui.serveradvancements.revoke:
description: 撤销服务器成就
default: op
itxiaohui.serveradvancements.view:
description: 查看玩家成就统计
default: op
@@ -0,0 +1,28 @@
package top.itxiaohui.serveradvancements.model;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ConditionDefinitionTest {
@Test void convertsOnlineHoursToMilliseconds() {
ConditionDefinition condition = new ConditionDefinition(ConditionType.ONLINE_TIME,
Map.of("amount", 10, "unit", "hours"));
assertEquals(36_000_000D, condition.target());
assertEquals("online_time_ms", condition.statisticKey());
}
@Test void buildsStableQualifiedStatisticKeys() {
ConditionDefinition mined = new ConditionDefinition(ConditionType.MINE_BLOCK,
Map.of("block", "minecraft:stone", "amount", 1000));
assertEquals("mine_block:minecraft:stone", mined.statisticKey());
assertEquals(1000D, mined.target());
}
@Test void parsesConditionNamesCaseInsensitively() {
assertEquals(ConditionType.COMPLETE_ACHIEVEMENT, ConditionType.parse("complete_achievement"));
assertThrows(IllegalArgumentException.class, () -> ConditionType.parse("not_real"));
}
}