Compare commits
6
Commits
v1.3.1
..
18cfbc2002
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18cfbc2002 | ||
|
|
5c760b26c6 | ||
|
|
2cad93de9a | ||
|
|
2aeb8d0340 | ||
|
|
2479192ad3 | ||
|
|
b57c7d4843 |
@@ -5,24 +5,9 @@ updates:
|
|||||||
schedule:
|
schedule:
|
||||||
interval: weekly
|
interval: weekly
|
||||||
open-pull-requests-limit: 5
|
open-pull-requests-limit: 5
|
||||||
groups:
|
|
||||||
gradle-dependencies:
|
|
||||||
patterns:
|
|
||||||
- "*"
|
|
||||||
ignore:
|
|
||||||
# 最低 Paper API 由版本兼容架构固定管理,不能自动升级为最新服务端版本。
|
|
||||||
- dependency-name: "io.papermc.paper:paper-api"
|
|
||||||
# 稳定发布不接受 paperweight 快照版本。
|
|
||||||
- dependency-name: "io.papermc.paperweight.userdev"
|
|
||||||
versions:
|
|
||||||
- "*-SNAPSHOT"
|
|
||||||
|
|
||||||
- package-ecosystem: github-actions
|
- package-ecosystem: github-actions
|
||||||
directory: /
|
directory: /
|
||||||
schedule:
|
schedule:
|
||||||
interval: weekly
|
interval: weekly
|
||||||
open-pull-requests-limit: 5
|
open-pull-requests-limit: 5
|
||||||
groups:
|
|
||||||
github-actions:
|
|
||||||
patterns:
|
|
||||||
- "*"
|
|
||||||
|
|||||||
@@ -28,52 +28,7 @@ jobs:
|
|||||||
- name: 验证 Gradle Wrapper
|
- name: 验证 Gradle Wrapper
|
||||||
uses: gradle/actions/wrapper-validation@v4
|
uses: gradle/actions/wrapper-validation@v4
|
||||||
|
|
||||||
- name: 配置 Gradle
|
|
||||||
uses: gradle/actions/setup-gradle@v4
|
|
||||||
|
|
||||||
- name: 授予执行权限
|
|
||||||
run: chmod +x gradlew
|
|
||||||
|
|
||||||
- name: 构建插件
|
- name: 构建插件
|
||||||
run: ./gradlew clean build --no-daemon
|
uses: gradle/actions/setup-gradle@v4
|
||||||
|
|
||||||
- name: 上传测试产物
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
with:
|
||||||
name: EssentialsC-test-build
|
arguments: clean build
|
||||||
path: build/libs/EssentialsC-*.jar
|
|
||||||
if-no-files-found: error
|
|
||||||
|
|
||||||
paper-smoke-test:
|
|
||||||
name: Paper ${{ matrix.paper }} / Java ${{ matrix.java }}
|
|
||||||
needs: build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- paper: '1.21.11'
|
|
||||||
java: '21'
|
|
||||||
- paper: '26.1.2'
|
|
||||||
java: '25'
|
|
||||||
- paper: '26.2'
|
|
||||||
java: '25'
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: 检出代码
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 设置 Java ${{ matrix.java }}
|
|
||||||
uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
java-version: ${{ matrix.java }}
|
|
||||||
distribution: temurin
|
|
||||||
|
|
||||||
- name: 下载插件产物
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: EssentialsC-test-build
|
|
||||||
path: build/libs
|
|
||||||
|
|
||||||
- name: 启动 Paper 并验证插件
|
|
||||||
run: bash scripts/smoke-test-paper.sh '${{ matrix.paper }}'
|
|
||||||
|
|||||||
@@ -16,28 +16,18 @@ jobs:
|
|||||||
- name: 检出代码
|
- name: 检出代码
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: 设置 Java 25
|
- name: 设置 Java 21
|
||||||
uses: actions/setup-java@v4
|
uses: actions/setup-java@v4
|
||||||
with:
|
with:
|
||||||
java-version: '25'
|
java-version: '21'
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
cache: gradle
|
cache: gradle
|
||||||
|
|
||||||
- name: 授予执行权限
|
- name: 授予执行权限
|
||||||
run: chmod +x gradlew
|
run: chmod +x gradlew
|
||||||
|
|
||||||
- name: 配置 Gradle
|
|
||||||
uses: gradle/actions/setup-gradle@v4
|
|
||||||
|
|
||||||
- name: 构建插件
|
- name: 构建插件
|
||||||
shell: bash
|
run: ./gradlew build
|
||||||
run: |
|
|
||||||
VERSION="${GITHUB_REF_NAME#v}"
|
|
||||||
if [[ "$VERSION" == "$GITHUB_REF_NAME" || ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
|
||||||
echo "无效的发布标签: $GITHUB_REF_NAME" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
./gradlew clean build --no-daemon -PpluginVersion="$VERSION"
|
|
||||||
|
|
||||||
- name: 创建发行版
|
- name: 创建发行版
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
# 更新日志
|
|
||||||
|
|
||||||
## 1.3.1 - 2026-08-16
|
|
||||||
|
|
||||||
### 移除
|
|
||||||
|
|
||||||
- 移除内置维护模式、相关命令、权限、配置和 LuckPerms 软依赖;维护功能建议使用独立的 Maintenance 插件。
|
|
||||||
|
|
||||||
### 调整
|
|
||||||
|
|
||||||
- GitHub 仓库迁移至 InfstarMC 组织,并同步更新项目文档与下载地址。
|
|
||||||
|
|
||||||
### 升级说明
|
|
||||||
|
|
||||||
- 升级时不再读取 `maintenance.yml`;为避免删除管理员数据,服务器目录中的旧文件会原样保留,可在确认迁移完成后手动删除。
|
|
||||||
|
|
||||||
## 1.3.0 - 2026-08-05
|
|
||||||
|
|
||||||
### 新增
|
|
||||||
|
|
||||||
- 按 HuskHomes 的单服逻辑完整实现 TPA 请求、接受、拒绝、忽略、预热、冷却、位置快照、音效与相关权限。
|
|
||||||
- 新增维护模式,包括 MOTD、BossBar、登录拦截、白名单、管理员通知和 LuckPerms 异步权限检查。
|
|
||||||
- 新增 SkinBridge,可识别 InfstarMC、LittleSkin 与自定义 Blessing Skin Provider,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
|
||||||
- 新增管理模式独立状态存储与玩家功能状态管理。
|
|
||||||
|
|
||||||
### 优化
|
|
||||||
|
|
||||||
- 按便捷方块、管理、修复与皮肤功能重新整理运行时模块。
|
|
||||||
- 完善潜影盒会话保护、TPA 请求队列、配置迁移、数据原子写入与持久化错误处理。
|
|
||||||
- 验证兼容 Paper `1.21.11` 与 `26.2`,最终插件保持 Java 21 字节码兼容。
|
|
||||||
- 移除实验性的 JEI 配方同步及其版本适配子项目,插件继续通过 Paper 公共 API 兼容支持的服务端版本。
|
|
||||||
- 迁移 Paper 弃用 API,并将弃用警告设为构建错误。
|
|
||||||
- 统一 HuskHomes 风格的中英文消息、颜色和配置注释。
|
|
||||||
|
|
||||||
### 注意事项
|
|
||||||
|
|
||||||
- 最低服务端版本为 Paper `1.21.11`,不支持 Folia 或 Fabric 服务端。
|
|
||||||
- LuckPerms 为推荐软依赖;未安装时维护模式会在玩家加入后复核绕过权限。
|
|
||||||
- SkinBridge 默认关闭,启用前必须配置有效的 MineSkin API Key。
|
|
||||||
- 主配置版本为 `2`。
|
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
轻量、现代、面向 Paper 服务端的基础功能插件,灵感来自 CMI,但更聚焦于常用能力与模块化构建。
|
轻量、现代、面向 Paper 服务端的基础功能插件,灵感来自 CMI,但更聚焦于常用能力与模块化构建。
|
||||||
|
|
||||||
[](https://github.com/InfstarMC/EssentialsC/releases)
|
[](https://github.com/Coldsmiles/EssentialsC/releases)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://papermc.io/)
|
[](https://papermc.io/)
|
||||||
[](https://adoptium.net/)
|
[](https://adoptium.net/)
|
||||||
|
|
||||||
@@ -11,8 +11,8 @@
|
|||||||
|
|
||||||
- 最低支持版本为 `Paper 1.21.11`
|
- 最低支持版本为 `Paper 1.21.11`
|
||||||
- 已适配 `Paper 26.2`
|
- 已适配 `Paper 26.2`
|
||||||
- 插件统一使用 Paper 公共 API 和 Java 21 字节码,无需按服务端版本拆分构建
|
- 主插件使用 `Java 21`,Paper 26.x 版本适配模块使用对应服务端要求的 Java 工具链
|
||||||
- 配置按职责拆分:主行为与 SkinBridge、模块开关、菜单布局和语言文本分别管理
|
- 配置按职责拆分:主行为与 SkinBridge、模块开关、菜单布局、维护模式和语言文本分别管理
|
||||||
- 支持运行期模块开关,避免为不同功能组合构建多个插件版本
|
- 支持运行期模块开关,避免为不同功能组合构建多个插件版本
|
||||||
|
|
||||||
## 主要功能
|
## 主要功能
|
||||||
@@ -43,21 +43,16 @@
|
|||||||
- `/seen` `(/info)`
|
- `/seen` `(/info)`
|
||||||
- `/tpsbar`
|
- `/tpsbar`
|
||||||
- `/essc admin` 管理模式切换
|
- `/essc admin` 管理模式切换
|
||||||
|
- `/maintenance` `(/maint)` 维护模式管理
|
||||||
### 控制台命令
|
|
||||||
|
|
||||||
- `/essc help`、`/essc version`、`/essc reload`
|
|
||||||
- `/seen [玩家]`、`/heal [玩家]`、`/feed [玩家]`、`/tpsbar [玩家]`
|
|
||||||
- `/essc skin [status|refresh] [玩家]`
|
|
||||||
|
|
||||||
依赖发送者位置、背包或玩家交互状态的命令仅允许在游戏内执行。控制台执行玩家状态命令时必须明确提供目标玩家。
|
|
||||||
|
|
||||||
### 其它功能
|
### 其它功能
|
||||||
|
|
||||||
- Shift + 右键快捷打开潜影盒
|
- Shift + 右键快捷打开潜影盒
|
||||||
- 潜影盒交互保护,尽量避免刷物品、吞物品和嵌套放入问题
|
- 潜影盒交互保护,尽量避免刷物品、吞物品和嵌套放入问题
|
||||||
- 管理模式独立背包、装备栏与状态切换
|
- 管理模式独立背包、装备栏与状态切换
|
||||||
|
- 维护模式:替换 MOTD、登录拦截、白名单放行和管理员拦截通知
|
||||||
- Enderman 掉落方块控制
|
- Enderman 掉落方块控制
|
||||||
|
- JEI 配方同步修复
|
||||||
|
|
||||||
## 模块配置
|
## 模块配置
|
||||||
|
|
||||||
@@ -68,20 +63,20 @@
|
|||||||
| `blocks` | 开启 | 便捷方块命令、`/essc blocks` 菜单、潜影盒快捷打开 |
|
| `blocks` | 开启 | 便捷方块命令、`/essc blocks` 菜单、潜影盒快捷打开 |
|
||||||
| `admin-mode` | 开启 | `/essc admin` 管理模式与独立状态保存 |
|
| `admin-mode` | 开启 | `/essc admin` 管理模式与独立状态保存 |
|
||||||
| `tpsbar` | 开启 | 插件版 TPSBar,检测到服务端原生命令时自动避免冲突 |
|
| `tpsbar` | 开启 | 插件版 TPSBar,检测到服务端原生命令时自动避免冲突 |
|
||||||
|
| `jei-sync` | 开启 | Fabric / NeoForge JEI 配方同步修复 |
|
||||||
| `mob-drops` | 关闭 | 末影人掉落控制,默认关闭以保留过去标准版行为 |
|
| `mob-drops` | 关闭 | 末影人掉落控制,默认关闭以保留过去标准版行为 |
|
||||||
|
| `maintenance` | 开启 | 维护模式命令、MOTD 替换、登录拦截、白名单和拦截通知 |
|
||||||
| `skin-bridge` | 关闭 | 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤 |
|
| `skin-bridge` | 关闭 | 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤 |
|
||||||
|
|
||||||
修改模块开关后使用 `/essc reload` 即可刷新运行期服务、监听器和命令门禁。可选模块命令始终注册,模块关闭时会返回统一的停用提示,因此无需为了启用命令重启服务器。
|
修改模块开关后使用 `/essc reload` 即可刷新运行期服务、监听器和命令门禁。可选模块命令始终注册,模块关闭时会返回统一的停用提示,因此无需为了启用命令重启服务器。
|
||||||
|
|
||||||
## 安装说明
|
## 安装说明
|
||||||
|
|
||||||
1. 从 [Releases](https://github.com/InfstarMC/EssentialsC/releases) 下载所需版本。
|
1. 从 [Releases](https://github.com/Coldsmiles/EssentialsC/releases) 下载所需版本。
|
||||||
2. 将插件放入服务端的 `plugins/` 目录。
|
2. 将插件放入服务端的 `plugins/` 目录。
|
||||||
3. 启动一次服务端以生成配置文件。
|
3. 启动一次服务端以生成配置文件。
|
||||||
4. 按需修改 `plugins/EssentialsC/` 下的配置文件与 `lang/` 语言文件。
|
4. 按需修改 `plugins/EssentialsC/` 下的配置文件与 `lang/` 语言文件。
|
||||||
5. 使用权限插件为玩家分配所需权限。
|
5. 如有需要,使用权限插件为玩家授权。
|
||||||
|
|
||||||
维护功能建议独立安装 [Maintenance](https://github.com/kennytv/Maintenance)。EssentialsC 不再内置维护模式,也不要求安装该插件。
|
|
||||||
|
|
||||||
## 配置说明
|
## 配置说明
|
||||||
|
|
||||||
@@ -92,6 +87,7 @@ SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-
|
|||||||
- `config.yml`
|
- `config.yml`
|
||||||
- 语言选择
|
- 语言选择
|
||||||
- 管理模式行为
|
- 管理模式行为
|
||||||
|
- JEI 同步开关
|
||||||
- 掉落控制
|
- 掉落控制
|
||||||
- TPSBar 模式
|
- TPSBar 模式
|
||||||
- TPA 请求、预热、冷却和音效
|
- TPA 请求、预热、冷却和音效
|
||||||
@@ -100,6 +96,14 @@ SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-
|
|||||||
- 功能模块开关
|
- 功能模块开关
|
||||||
- `blocks-menu.yml`
|
- `blocks-menu.yml`
|
||||||
- 便捷菜单分区、槽位、材质和权限
|
- 便捷菜单分区、槽位、材质和权限
|
||||||
|
- `maintenance.yml`
|
||||||
|
- 维护模式状态
|
||||||
|
- 维护 MOTD
|
||||||
|
- 维护踢出提示
|
||||||
|
- 维护 BossBar
|
||||||
|
- 绕过权限
|
||||||
|
- 维护白名单
|
||||||
|
- 拦截通知权限
|
||||||
- `lang/zh_CN.yml`、`lang/en_US.yml`
|
- `lang/zh_CN.yml`、`lang/en_US.yml`
|
||||||
- 命令反馈
|
- 命令反馈
|
||||||
- 帮助信息
|
- 帮助信息
|
||||||
@@ -109,8 +113,6 @@ SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-
|
|||||||
|
|
||||||
主配置当前使用 `config-version: 2`。SkinBridge 直接配置在 `config.yml` 中,便捷菜单配置仍保存在独立文件中。
|
主配置当前使用 `config-version: 2`。SkinBridge 直接配置在 `config.yml` 中,便捷菜单配置仍保存在独立文件中。
|
||||||
|
|
||||||
版本变化与升级说明见 [CHANGELOG.md](CHANGELOG.md)。
|
|
||||||
|
|
||||||
## 权限示例
|
## 权限示例
|
||||||
|
|
||||||
常用权限节点:
|
常用权限节点:
|
||||||
@@ -140,10 +142,13 @@ essentialsc.tpa.bypass-cooldown
|
|||||||
essentialsc.tpa.warmup.3
|
essentialsc.tpa.warmup.3
|
||||||
essentialsc.command.admin
|
essentialsc.command.admin
|
||||||
essentialsc.command.tpsbar
|
essentialsc.command.tpsbar
|
||||||
|
essentialsc.command.maintenance
|
||||||
essentialsc.command.skin
|
essentialsc.command.skin
|
||||||
essentialsc.command.skin.status
|
essentialsc.command.skin.status
|
||||||
essentialsc.command.skin.refresh
|
essentialsc.command.skin.refresh
|
||||||
essentialsc.command.skin.others
|
essentialsc.command.skin.others
|
||||||
|
essentialsc.maintenance.bypass
|
||||||
|
essentialsc.maintenance.notify
|
||||||
essentialsc.shulkerbox.open
|
essentialsc.shulkerbox.open
|
||||||
essentialsc.mobdrops.enderman
|
essentialsc.mobdrops.enderman
|
||||||
essentialsc.*
|
essentialsc.*
|
||||||
@@ -154,7 +159,7 @@ essentialsc.*
|
|||||||
## 从源码构建
|
## 从源码构建
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/InfstarMC/EssentialsC.git
|
git clone https://github.com/Coldsmiles/EssentialsC.git
|
||||||
cd EssentialsC
|
cd EssentialsC
|
||||||
./gradlew build
|
./gradlew build
|
||||||
```
|
```
|
||||||
@@ -173,8 +178,8 @@ Windows 可使用:
|
|||||||
./gradlew shadowJar
|
./gradlew shadowJar
|
||||||
./gradlew build
|
./gradlew build
|
||||||
./gradlew deployToPaper12111
|
./gradlew deployToPaper12111
|
||||||
|
./gradlew deployToPaper2612
|
||||||
./gradlew deployToPaper262
|
./gradlew deployToPaper262
|
||||||
./gradlew deployToLeaves262
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 本地测试服
|
## 本地测试服
|
||||||
@@ -184,15 +189,16 @@ Windows 可使用:
|
|||||||
| 测试服 | 端口 | 部署任务 | 启动脚本 |
|
| 测试服 | 端口 | 部署任务 | 启动脚本 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Paper 1.21.11 | `25566` | `deployToPaper12111` | `test-server/paper-1.21.11/start.bat` |
|
| Paper 1.21.11 | `25566` | `deployToPaper12111` | `test-server/paper-1.21.11/start.bat` |
|
||||||
| Paper 26.2 | `25567` | `deployToPaper262` | `test-server/paper-26.2/start.bat` |
|
| Paper 26.1.2 | `25565` | `deployToPaper2612` | `test-server/paper-26.1.2/start.bat` |
|
||||||
| Leaves 26.2 | `25568` | `deployToLeaves262` | `test-server/leaves-26.2/start.bat` |
|
| Paper 26.2 | 以本地配置为准 | `deployToPaper262` | `test-server/paper-26.2/start.bat` |
|
||||||
|
|
||||||
IDEA 运行配置会先构建插件,再由启动脚本复制最新 JAR,并保留插件数据以便测试升级流程。手动执行部署任务会替换 `EssentialsC*.jar` 并删除 `plugins/EssentialsC` 数据目录,用于测试全新安装及默认配置生成。
|
IDEA 运行配置会在启动测试服前自动执行对应部署任务。部署任务会替换 `EssentialsC*.jar`,并删除 `plugins/EssentialsC` 数据目录,以便测试新增默认配置和语言文本。
|
||||||
|
|
||||||
## 开发说明
|
## 开发说明
|
||||||
|
|
||||||
- 使用 `paperweight-userdev` 进行 Paper 开发
|
- 使用 `paperweight-userdev` 进行 Paper 开发
|
||||||
- 使用 Paper Lifecycle Command API 注册命令,避免直接反射 Bukkit CommandMap
|
- 使用 Paper Lifecycle Command API 注册命令,避免直接反射 Bukkit CommandMap
|
||||||
|
- 涉及 NMS 的功能通过 `compat-api` + `versions/v<版本>` 适配模块隔离,主插件只依赖稳定接口;当前包含 `1.21.11`、`26.1.2`、`26.2`
|
||||||
- 运行时通过 `modules.yml` 控制模块加载,命令始终注册并按模块状态执行门禁
|
- 运行时通过 `modules.yml` 控制模块加载,命令始终注册并按模块状态执行门禁
|
||||||
- 普通 push/PR 会执行构建与测试,版本标签继续生成 GitHub Release
|
- 普通 push/PR 会执行构建与测试,版本标签继续生成 GitHub Release
|
||||||
|
|
||||||
@@ -202,5 +208,5 @@ IDEA 运行配置会先构建插件,再由启动脚本复制最新 JAR,并
|
|||||||
|
|
||||||
## 仓库
|
## 仓库
|
||||||
|
|
||||||
- GitHub: <https://github.com/InfstarMC/EssentialsC>
|
- GitHub: <https://github.com/Coldsmiles/EssentialsC>
|
||||||
- Gitea: <https://git.infstar.cn/InfStarMC/EssentialsC>
|
- Gitea: <https://git.infstar.cn/InfStarMC/EssentialsC>
|
||||||
|
|||||||
+16
-43
@@ -1,7 +1,6 @@
|
|||||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||||
import org.gradle.language.jvm.tasks.ProcessResources
|
import org.gradle.language.jvm.tasks.ProcessResources
|
||||||
import org.gradle.api.tasks.testing.Test
|
import org.gradle.api.tasks.testing.Test
|
||||||
import java.util.zip.ZipFile
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java'
|
id 'java'
|
||||||
@@ -10,8 +9,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
group = 'cn.infstar'
|
group = 'cn.infstar'
|
||||||
def pluginVersion = providers.gradleProperty('pluginVersion').orElse('1.3.1').get()
|
version = '1.4.0'
|
||||||
version = pluginVersion
|
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
@@ -23,6 +21,7 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
||||||
|
implementation project(':compat-api')
|
||||||
implementation 'com.google.code.gson:gson:2.11.0'
|
implementation 'com.google.code.gson:gson:2.11.0'
|
||||||
testImplementation platform('org.junit:junit-bom:5.13.4')
|
testImplementation platform('org.junit:junit-bom:5.13.4')
|
||||||
testImplementation 'org.junit.jupiter:junit-jupiter'
|
testImplementation 'org.junit.jupiter:junit-jupiter'
|
||||||
@@ -35,11 +34,8 @@ java {
|
|||||||
|
|
||||||
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
allprojects {
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
tasks.withType(JavaCompile).configureEach {
|
||||||
options.encoding = 'UTF-8'
|
options.encoding = 'UTF-8'
|
||||||
options.compilerArgs.addAll(['-Xlint:deprecation', '-Werror'])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType(ProcessResources).configureEach {
|
tasks.withType(ProcessResources).configureEach {
|
||||||
@@ -51,9 +47,9 @@ tasks.withType(Test).configureEach {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('processResources', ProcessResources).configure {
|
tasks.named('processResources', ProcessResources).configure {
|
||||||
inputs.property('version', pluginVersion)
|
inputs.property('version', project.version)
|
||||||
filesMatching('paper-plugin.yml') {
|
filesMatching('paper-plugin.yml') {
|
||||||
expand('version': pluginVersion)
|
expand('version': project.version)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,48 +60,25 @@ tasks.named('jar').configure {
|
|||||||
tasks.named('shadowJar', ShadowJar).configure {
|
tasks.named('shadowJar', ShadowJar).configure {
|
||||||
group = 'build'
|
group = 'build'
|
||||||
description = '构建包含全部运行期可开关模块的 EssentialsC 插件。'
|
description = '构建包含全部运行期可开关模块的 EssentialsC 插件。'
|
||||||
archiveFileName.set("EssentialsC-${pluginVersion}.jar")
|
archiveFileName.set("EssentialsC-${project.version}.jar")
|
||||||
configurations = [project.configurations.runtimeClasspath]
|
configurations = [project.configurations.runtimeClasspath]
|
||||||
relocate 'com.google.gson', 'cn.infstar.essentialsC.libs.gson'
|
relocate 'com.google.gson', 'cn.infstar.essentialsC.libs.gson'
|
||||||
|
|
||||||
|
[
|
||||||
|
project(':versions:v1_21_11'),
|
||||||
|
project(':versions:v26_1_2'),
|
||||||
|
project(':versions:v26_2')
|
||||||
|
].each { adapterProject ->
|
||||||
|
def adapterJar = adapterProject.tasks.named('jar')
|
||||||
|
dependsOn(adapterJar)
|
||||||
|
from(adapterJar.flatMap { it.archiveFile }.map { archiveFile -> zipTree(archiveFile) })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('assemble').configure {
|
tasks.named('assemble').configure {
|
||||||
dependsOn(tasks.named('shadowJar'))
|
dependsOn(tasks.named('shadowJar'))
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.register('verifyJava21Bytecode') {
|
|
||||||
group = 'verification'
|
|
||||||
description = '验证最终插件中的全部 class 均可由 Java 21 加载。'
|
|
||||||
dependsOn(tasks.named('shadowJar'))
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
def artifact = tasks.named('shadowJar', ShadowJar).get().archiveFile.get().asFile
|
|
||||||
def unsupportedClasses = []
|
|
||||||
new ZipFile(artifact).withCloseable { zip ->
|
|
||||||
zip.entries().each { entry ->
|
|
||||||
if (!entry.directory && entry.name.endsWith('.class')) {
|
|
||||||
zip.getInputStream(entry).withCloseable { input ->
|
|
||||||
byte[] header = input.readNBytes(8)
|
|
||||||
if (header.length == 8) {
|
|
||||||
int majorVersion = ((header[6] & 0xff) << 8) | (header[7] & 0xff)
|
|
||||||
if (majorVersion > 65) {
|
|
||||||
unsupportedClasses.add("${entry.name} (class ${majorVersion})")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!unsupportedClasses.isEmpty()) {
|
|
||||||
throw new GradleException("检测到无法由 Java 21 加载的类:\n" + unsupportedClasses.join('\n'))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('check').configure {
|
|
||||||
dependsOn(tasks.named('verifyJava21Bytecode'))
|
|
||||||
}
|
|
||||||
|
|
||||||
def registerTestServerDeployTask = { String taskName, String serverPath, String serverName ->
|
def registerTestServerDeployTask = { String taskName, String serverPath, String serverName ->
|
||||||
tasks.register(taskName, Copy) {
|
tasks.register(taskName, Copy) {
|
||||||
group = 'deployment'
|
group = 'deployment'
|
||||||
@@ -126,5 +99,5 @@ def registerTestServerDeployTask = { String taskName, String serverPath, String
|
|||||||
}
|
}
|
||||||
|
|
||||||
registerTestServerDeployTask('deployToPaper12111', 'test-server/paper-1.21.11', 'Paper 1.21.11')
|
registerTestServerDeployTask('deployToPaper12111', 'test-server/paper-1.21.11', 'Paper 1.21.11')
|
||||||
|
registerTestServerDeployTask('deployToPaper2612', 'test-server/paper-26.1.2', 'Paper 26.1.2')
|
||||||
registerTestServerDeployTask('deployToPaper262', 'test-server/paper-26.2', 'Paper 26.2')
|
registerTestServerDeployTask('deployToPaper262', 'test-server/paper-26.2', 'Paper 26.2')
|
||||||
registerTestServerDeployTask('deployToLeaves262', 'test-server/leaves-26.2', 'Leaves 26.2')
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven {
|
||||||
|
name = 'papermc'
|
||||||
|
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
compileOnly 'io.papermc.paper:paper-api:1.21.11-R0.1-SNAPSHOT'
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package cn.infstar.essentialsC.compat.jei;
|
||||||
|
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public interface JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
|
void sendFabricRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
||||||
|
|
||||||
|
void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
||||||
|
}
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
paper_version="${1:?必须提供 Paper 版本}"
|
|
||||||
workspace="$(mktemp -d)"
|
|
||||||
server_pid=""
|
|
||||||
plugin_jar="$(find build/libs -maxdepth 1 -type f -name 'EssentialsC-*.jar' -print -quit)"
|
|
||||||
if [[ -z "$plugin_jar" ]]; then
|
|
||||||
echo "未找到 EssentialsC 构建产物。" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
plugin_filename="$(basename "$plugin_jar")"
|
|
||||||
plugin_version="${plugin_filename#EssentialsC-}"
|
|
||||||
plugin_version="${plugin_version%.jar}"
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
if [[ -n "$server_pid" ]] && kill -0 "$server_pid" 2>/dev/null; then
|
|
||||||
kill -TERM "$server_pid" 2>/dev/null || true
|
|
||||||
for _ in $(seq 1 10); do
|
|
||||||
if ! kill -0 "$server_pid" 2>/dev/null; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
if kill -0 "$server_pid" 2>/dev/null; then
|
|
||||||
kill -KILL "$server_pid" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
wait "$server_pid" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
for _ in 1 2 3; do
|
|
||||||
if rm -rf "$workspace"; then
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
echo "警告:无法完全清理临时测试目录 $workspace" >&2
|
|
||||||
}
|
|
||||||
trap cleanup EXIT
|
|
||||||
|
|
||||||
metadata_url="https://fill.papermc.io/v3/projects/paper/versions/${paper_version}/builds/latest"
|
|
||||||
download_url="$(curl --fail --silent --show-error --location "$metadata_url" \
|
|
||||||
| python3 -c 'import json,sys; print(json.load(sys.stdin)["downloads"]["server:default"]["url"])')"
|
|
||||||
|
|
||||||
curl --fail --silent --show-error --location "$download_url" --output "$workspace/paper.jar"
|
|
||||||
mkdir -p "$workspace/plugins"
|
|
||||||
cp "$plugin_jar" "$workspace/plugins/EssentialsC.jar"
|
|
||||||
printf 'eula=true\n' > "$workspace/eula.txt"
|
|
||||||
printf 'online-mode=false\nserver-port=0\nenable-query=false\n' > "$workspace/server.properties"
|
|
||||||
|
|
||||||
(
|
|
||||||
cd "$workspace"
|
|
||||||
exec java -Xms512M -Xmx1G -jar paper.jar --nogui > server.log 2>&1
|
|
||||||
) &
|
|
||||||
server_pid=$!
|
|
||||||
|
|
||||||
for _ in $(seq 1 120); do
|
|
||||||
if grep -Fq "EssentialsC v${plugin_version} 已启用" "$workspace/server.log"; then
|
|
||||||
if grep -Eq 'UnsupportedClassVersionError|Error occurred while enabling EssentialsC|Could not load.*EssentialsC' "$workspace/server.log"; then
|
|
||||||
cat "$workspace/server.log"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Paper ${paper_version} 启动验证通过。"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
if ! kill -0 "$server_pid" 2>/dev/null; then
|
|
||||||
cat "$workspace/server.log"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
cat "$workspace/server.log"
|
|
||||||
echo "Paper ${paper_version} 启动验证超时。" >&2
|
|
||||||
exit 1
|
|
||||||
@@ -20,3 +20,8 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rootProject.name = 'EssentialsC'
|
rootProject.name = 'EssentialsC'
|
||||||
|
|
||||||
|
include 'compat-api'
|
||||||
|
include 'versions:v1_21_11'
|
||||||
|
include 'versions:v26_1_2'
|
||||||
|
include 'versions:v26_2'
|
||||||
|
|||||||
@@ -2,16 +2,17 @@ package cn.infstar.essentialsC;
|
|||||||
|
|
||||||
import cn.infstar.essentialsC.admin.AdminModeManager;
|
import cn.infstar.essentialsC.admin.AdminModeManager;
|
||||||
import cn.infstar.essentialsC.commands.BaseCommand;
|
import cn.infstar.essentialsC.commands.BaseCommand;
|
||||||
import cn.infstar.essentialsC.commands.BlocksMenuCommand;
|
|
||||||
import cn.infstar.essentialsC.commands.CommandRegistry;
|
import cn.infstar.essentialsC.commands.CommandRegistry;
|
||||||
import cn.infstar.essentialsC.commands.HelpCommand;
|
import cn.infstar.essentialsC.commands.HelpCommand;
|
||||||
import cn.infstar.essentialsC.commands.PaperCommand;
|
import cn.infstar.essentialsC.commands.PaperCommand;
|
||||||
import cn.infstar.essentialsC.commands.VanishCommand;
|
import cn.infstar.essentialsC.commands.VanishCommand;
|
||||||
|
import cn.infstar.essentialsC.listeners.JeiRecipeSyncListener;
|
||||||
import cn.infstar.essentialsC.listeners.MobDropListener;
|
import cn.infstar.essentialsC.listeners.MobDropListener;
|
||||||
import cn.infstar.essentialsC.listeners.MobDropMenuListener;
|
import cn.infstar.essentialsC.listeners.MobDropMenuListener;
|
||||||
import cn.infstar.essentialsC.listeners.ShulkerBoxListener;
|
import cn.infstar.essentialsC.listeners.ShulkerBoxListener;
|
||||||
import cn.infstar.essentialsC.listeners.VanishListener;
|
import cn.infstar.essentialsC.listeners.VanishListener;
|
||||||
import cn.infstar.essentialsC.player.PlayerStateManager;
|
import cn.infstar.essentialsC.maintenance.MaintenanceListener;
|
||||||
|
import cn.infstar.essentialsC.maintenance.MaintenanceManager;
|
||||||
import cn.infstar.essentialsC.skinbridge.SkinBridgeManager;
|
import cn.infstar.essentialsC.skinbridge.SkinBridgeManager;
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||||
import cn.infstar.essentialsC.tpsbar.TpsBarManager;
|
import cn.infstar.essentialsC.tpsbar.TpsBarManager;
|
||||||
@@ -20,6 +21,7 @@ import org.bukkit.command.CommandSender;
|
|||||||
import org.bukkit.command.TabCompleter;
|
import org.bukkit.command.TabCompleter;
|
||||||
import org.bukkit.event.HandlerList;
|
import org.bukkit.event.HandlerList;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
|
import org.bukkit.plugin.messaging.Messenger;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
import io.papermc.paper.command.brigadier.BasicCommand;
|
import io.papermc.paper.command.brigadier.BasicCommand;
|
||||||
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
||||||
@@ -36,11 +38,12 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
private ModuleManager moduleManager;
|
private ModuleManager moduleManager;
|
||||||
private FeatureConfigManager featureConfigManager;
|
private FeatureConfigManager featureConfigManager;
|
||||||
private AdminModeManager adminModeManager;
|
private AdminModeManager adminModeManager;
|
||||||
|
private MaintenanceManager maintenanceManager;
|
||||||
private TeleportRequestManager teleportRequestManager;
|
private TeleportRequestManager teleportRequestManager;
|
||||||
private PlayerStateManager playerStateManager;
|
private MaintenanceListener maintenanceListener;
|
||||||
private TpsBarService tpsBarManager;
|
private TpsBarService tpsBarManager;
|
||||||
private ShulkerBoxListener shulkerBoxListener;
|
private ShulkerBoxListener shulkerBoxListener;
|
||||||
private BlocksMenuCommand blocksMenuCommandListener;
|
private JeiRecipeSyncListener jeiRecipeSyncListener;
|
||||||
private MobDropListener mobDropListener;
|
private MobDropListener mobDropListener;
|
||||||
private MobDropMenuListener mobDropMenuListener;
|
private MobDropMenuListener mobDropMenuListener;
|
||||||
private VanishListener vanishListener;
|
private VanishListener vanishListener;
|
||||||
@@ -50,9 +53,9 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onEnable() {
|
public void onEnable() {
|
||||||
featureConfigManager = new FeatureConfigManager(this);
|
|
||||||
langManager = new LangManager(this);
|
langManager = new LangManager(this);
|
||||||
moduleManager = new ModuleManager(this);
|
moduleManager = new ModuleManager(this);
|
||||||
|
featureConfigManager = new FeatureConfigManager(this);
|
||||||
|
|
||||||
reloadRuntimeModules();
|
reloadRuntimeModules();
|
||||||
registerCommands();
|
registerCommands();
|
||||||
@@ -68,23 +71,21 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
if (adminModeManager != null) {
|
if (adminModeManager != null) {
|
||||||
adminModeManager.shutdown();
|
adminModeManager.shutdown();
|
||||||
}
|
}
|
||||||
|
if (maintenanceManager != null) {
|
||||||
|
maintenanceManager.shutdown();
|
||||||
|
}
|
||||||
if (teleportRequestManager != null) {
|
if (teleportRequestManager != null) {
|
||||||
teleportRequestManager.shutdown();
|
teleportRequestManager.shutdown();
|
||||||
}
|
}
|
||||||
if (playerStateManager != null) {
|
|
||||||
playerStateManager.shutdown();
|
|
||||||
}
|
|
||||||
if (skinBridgeManager != null) {
|
if (skinBridgeManager != null) {
|
||||||
skinBridgeManager.shutdown();
|
skinBridgeManager.shutdown();
|
||||||
}
|
}
|
||||||
if (shulkerBoxListener != null) {
|
|
||||||
shulkerBoxListener.shutdown();
|
|
||||||
}
|
|
||||||
if (vanishListener != null) {
|
if (vanishListener != null) {
|
||||||
vanishListener.shutdown();
|
vanishListener.shutdown();
|
||||||
}
|
}
|
||||||
VanishCommand.clearAll(this);
|
VanishCommand.clearAll(this);
|
||||||
unregisterRuntimeListeners();
|
unregisterRuntimeListeners();
|
||||||
|
unregisterPluginChannels();
|
||||||
getLogger().info("EssentialsC 已禁用。");
|
getLogger().info("EssentialsC 已禁用。");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,12 +105,12 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
return featureConfigManager;
|
return featureConfigManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TeleportRequestManager getTeleportRequestManager() {
|
public MaintenanceManager getMaintenanceManager() {
|
||||||
return teleportRequestManager;
|
return maintenanceManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PlayerStateManager getPlayerStateManager() {
|
public TeleportRequestManager getTeleportRequestManager() {
|
||||||
return playerStateManager;
|
return teleportRequestManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TpsBarService getTpsBarManager() {
|
public TpsBarService getTpsBarManager() {
|
||||||
@@ -124,17 +125,15 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
moduleStatus.clear();
|
moduleStatus.clear();
|
||||||
refreshCorePlayerFeatures();
|
refreshCorePlayerFeatures();
|
||||||
refreshAdminMode();
|
refreshAdminMode();
|
||||||
|
refreshMaintenance();
|
||||||
refreshTpsBar();
|
refreshTpsBar();
|
||||||
refreshBlocks();
|
refreshBlocks();
|
||||||
|
refreshJeiSync();
|
||||||
refreshMobDrops();
|
refreshMobDrops();
|
||||||
refreshSkinBridge();
|
refreshSkinBridge();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void refreshCorePlayerFeatures() {
|
private void refreshCorePlayerFeatures() {
|
||||||
if (playerStateManager == null) {
|
|
||||||
playerStateManager = new PlayerStateManager(this);
|
|
||||||
getServer().getPluginManager().registerEvents(playerStateManager, this);
|
|
||||||
}
|
|
||||||
if (vanishListener == null) {
|
if (vanishListener == null) {
|
||||||
vanishListener = new VanishListener(this);
|
vanishListener = new VanishListener(this);
|
||||||
getServer().getPluginManager().registerEvents(vanishListener, this);
|
getServer().getPluginManager().registerEvents(vanishListener, this);
|
||||||
@@ -167,6 +166,32 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
setModuleStatus("管理模式", true, "监听器已注册");
|
setModuleStatus("管理模式", true, "监听器已注册");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void refreshMaintenance() {
|
||||||
|
if (!moduleManager.isEnabled(ModuleManager.MAINTENANCE)) {
|
||||||
|
if (maintenanceManager != null) {
|
||||||
|
maintenanceManager.shutdown();
|
||||||
|
maintenanceManager = null;
|
||||||
|
}
|
||||||
|
if (maintenanceListener != null) {
|
||||||
|
HandlerList.unregisterAll(maintenanceListener);
|
||||||
|
maintenanceListener = null;
|
||||||
|
}
|
||||||
|
setModuleStatus("维护模式", false, "已禁用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maintenanceManager == null) {
|
||||||
|
maintenanceManager = new MaintenanceManager(this);
|
||||||
|
} else {
|
||||||
|
maintenanceManager.reload();
|
||||||
|
}
|
||||||
|
if (maintenanceListener == null) {
|
||||||
|
maintenanceListener = new MaintenanceListener(this);
|
||||||
|
getServer().getPluginManager().registerEvents(maintenanceListener, this);
|
||||||
|
}
|
||||||
|
setModuleStatus("维护模式", true, maintenanceManager.isEnabled() ? "当前开启" : "当前关闭");
|
||||||
|
}
|
||||||
|
|
||||||
private void refreshTpsBar() {
|
private void refreshTpsBar() {
|
||||||
if (!moduleManager.isEnabled(ModuleManager.TPSBAR)) {
|
if (!moduleManager.isEnabled(ModuleManager.TPSBAR)) {
|
||||||
if (tpsBarManager != null) {
|
if (tpsBarManager != null) {
|
||||||
@@ -199,12 +224,7 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
|
|
||||||
private void refreshBlocks() {
|
private void refreshBlocks() {
|
||||||
if (!moduleManager.isEnabled(ModuleManager.BLOCKS)) {
|
if (!moduleManager.isEnabled(ModuleManager.BLOCKS)) {
|
||||||
if (blocksMenuCommandListener != null) {
|
|
||||||
HandlerList.unregisterAll(blocksMenuCommandListener);
|
|
||||||
blocksMenuCommandListener = null;
|
|
||||||
}
|
|
||||||
if (shulkerBoxListener != null) {
|
if (shulkerBoxListener != null) {
|
||||||
shulkerBoxListener.shutdown();
|
|
||||||
HandlerList.unregisterAll(shulkerBoxListener);
|
HandlerList.unregisterAll(shulkerBoxListener);
|
||||||
shulkerBoxListener = null;
|
shulkerBoxListener = null;
|
||||||
}
|
}
|
||||||
@@ -216,16 +236,27 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
shulkerBoxListener = new ShulkerBoxListener(this);
|
shulkerBoxListener = new ShulkerBoxListener(this);
|
||||||
getServer().getPluginManager().registerEvents(shulkerBoxListener, this);
|
getServer().getPluginManager().registerEvents(shulkerBoxListener, this);
|
||||||
}
|
}
|
||||||
if (blocksMenuCommandListener == null) {
|
|
||||||
BaseCommand command = CommandRegistry.getCommand("blocks");
|
|
||||||
if (command instanceof BlocksMenuCommand blocksMenuCommand) {
|
|
||||||
blocksMenuCommandListener = blocksMenuCommand;
|
|
||||||
getServer().getPluginManager().registerEvents(blocksMenuCommandListener, this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setModuleStatus("便捷方块", true, "命令和潜影盒监听器已启用");
|
setModuleStatus("便捷方块", true, "命令和潜影盒监听器已启用");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void refreshJeiSync() {
|
||||||
|
if (jeiRecipeSyncListener != null) {
|
||||||
|
HandlerList.unregisterAll(jeiRecipeSyncListener);
|
||||||
|
jeiRecipeSyncListener = null;
|
||||||
|
}
|
||||||
|
unregisterPluginChannels();
|
||||||
|
|
||||||
|
if (!moduleManager.isEnabled(ModuleManager.JEI_SYNC)) {
|
||||||
|
setModuleStatus("JEI 同步", false, "已禁用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerPluginChannels();
|
||||||
|
jeiRecipeSyncListener = new JeiRecipeSyncListener(this);
|
||||||
|
getServer().getPluginManager().registerEvents(jeiRecipeSyncListener, this);
|
||||||
|
setModuleStatus("JEI 同步", true, "插件消息通道已注册");
|
||||||
|
}
|
||||||
|
|
||||||
private void refreshMobDrops() {
|
private void refreshMobDrops() {
|
||||||
if (!moduleManager.isEnabled(ModuleManager.MOB_DROPS)) {
|
if (!moduleManager.isEnabled(ModuleManager.MOB_DROPS)) {
|
||||||
if (mobDropListener != null) {
|
if (mobDropListener != null) {
|
||||||
@@ -248,7 +279,6 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
}
|
}
|
||||||
if (mobDropMenuListener == null) {
|
if (mobDropMenuListener == null) {
|
||||||
mobDropMenuListener = new MobDropMenuListener(this);
|
mobDropMenuListener = new MobDropMenuListener(this);
|
||||||
getServer().getPluginManager().registerEvents(mobDropMenuListener, this);
|
|
||||||
}
|
}
|
||||||
setModuleStatus("生物掉落", true, "末影人掉落控制已启用");
|
setModuleStatus("生物掉落", true, "末影人掉落控制已启用");
|
||||||
}
|
}
|
||||||
@@ -273,15 +303,27 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
setModuleStatus("皮肤桥接", true, skinBridgeManager.getModuleDetail());
|
setModuleStatus("皮肤桥接", true, skinBridgeManager.getModuleDetail());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void registerPluginChannels() {
|
||||||
|
Messenger messenger = getServer().getMessenger();
|
||||||
|
messenger.registerOutgoingPluginChannel(this, "fabric:recipe_sync");
|
||||||
|
messenger.registerOutgoingPluginChannel(this, "neoforge:recipe_content");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unregisterPluginChannels() {
|
||||||
|
Messenger messenger = getServer().getMessenger();
|
||||||
|
messenger.unregisterOutgoingPluginChannel(this, "fabric:recipe_sync");
|
||||||
|
messenger.unregisterOutgoingPluginChannel(this, "neoforge:recipe_content");
|
||||||
|
}
|
||||||
|
|
||||||
private void unregisterRuntimeListeners() {
|
private void unregisterRuntimeListeners() {
|
||||||
unregisterListener(adminModeManager);
|
unregisterListener(adminModeManager);
|
||||||
|
unregisterListener(maintenanceListener);
|
||||||
unregisterListener(shulkerBoxListener);
|
unregisterListener(shulkerBoxListener);
|
||||||
unregisterListener(blocksMenuCommandListener);
|
unregisterListener(jeiRecipeSyncListener);
|
||||||
unregisterListener(mobDropListener);
|
unregisterListener(mobDropListener);
|
||||||
unregisterListener(mobDropMenuListener);
|
unregisterListener(mobDropMenuListener);
|
||||||
unregisterListener(vanishListener);
|
unregisterListener(vanishListener);
|
||||||
unregisterListener(teleportRequestManager);
|
unregisterListener(teleportRequestManager);
|
||||||
unregisterListener(playerStateManager);
|
|
||||||
unregisterListener(skinBridgeManager);
|
unregisterListener(skinBridgeManager);
|
||||||
if (tpsBarManager instanceof Listener listener) {
|
if (tpsBarManager instanceof Listener listener) {
|
||||||
unregisterListener(listener);
|
unregisterListener(listener);
|
||||||
@@ -304,7 +346,7 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
.count();
|
.count();
|
||||||
long disabledCount = moduleStatus.size() - enabledCount;
|
long disabledCount = moduleStatus.size() - enabledCount;
|
||||||
|
|
||||||
getLogger().info("EssentialsC v" + getPluginMeta().getVersion()
|
getLogger().info("EssentialsC v" + getDescription().getVersion()
|
||||||
+ " 已启用 | 模块: " + enabledCount + " 启用, " + disabledCount + " 关闭");
|
+ " 已启用 | 模块: " + enabledCount + " 启用, " + disabledCount + " 关闭");
|
||||||
|
|
||||||
if (!getConfig().getBoolean("debug", false)) {
|
if (!getConfig().getBoolean("debug", false)) {
|
||||||
@@ -373,15 +415,9 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
@Override
|
@Override
|
||||||
public Collection<String> suggest(CommandSourceStack commandSourceStack, String[] args) {
|
public Collection<String> suggest(CommandSourceStack commandSourceStack, String[] args) {
|
||||||
if (executor instanceof TabCompleter completer) {
|
if (executor instanceof TabCompleter completer) {
|
||||||
String[] completionArgs = args.length == 0 ? new String[]{""} : args;
|
return completer.onTabComplete(commandSourceStack.getSender(), commandAdapter, name, args);
|
||||||
return completer.onTabComplete(commandSourceStack.getSender(), commandAdapter, name, completionArgs);
|
|
||||||
}
|
}
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String permission() {
|
|
||||||
return "essentialsc".equals(name) ? null : executor.getPermission();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package cn.infstar.essentialsC;
|
|||||||
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
import org.bukkit.configuration.ConfigurationSection;
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
|
|
||||||
@@ -11,49 +10,31 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理主配置与独立功能配置,并负责按顺序执行配置迁移。
|
* 管理独立功能配置,并负责迁移旧版配置结构。
|
||||||
*/
|
*/
|
||||||
public final class FeatureConfigManager {
|
public final class FeatureConfigManager {
|
||||||
|
|
||||||
private static final int MAIN_CONFIG_VERSION = 2;
|
private static final int MAIN_CONFIG_VERSION = 2;
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final File mainConfigFile;
|
|
||||||
private final File blocksMenuFile;
|
private final File blocksMenuFile;
|
||||||
private FileConfiguration blocksMenuConfig;
|
private FileConfiguration blocksMenuConfig;
|
||||||
|
|
||||||
public FeatureConfigManager(EssentialsC plugin) {
|
public FeatureConfigManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.mainConfigFile = new File(plugin.getDataFolder(), "config.yml");
|
|
||||||
this.blocksMenuFile = new File(plugin.getDataFolder(), "blocks-menu.yml");
|
this.blocksMenuFile = new File(plugin.getDataFolder(), "blocks-menu.yml");
|
||||||
reload();
|
reload();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
ensureResource(mainConfigFile, "config.yml");
|
|
||||||
ensureResource(blocksMenuFile, "blocks-menu.yml");
|
ensureResource(blocksMenuFile, "blocks-menu.yml");
|
||||||
|
|
||||||
blocksMenuConfig = loadWithDefaults(blocksMenuFile, "blocks-menu.yml");
|
blocksMenuConfig = loadWithDefaults(blocksMenuFile, "blocks-menu.yml");
|
||||||
YamlConfiguration loadedMainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
migrateLegacyMainConfig();
|
||||||
YamlConfiguration mainConfig = migrateMainConfigVersion(loadedMainConfig);
|
migrateLegacyDebugSettings();
|
||||||
|
updateMainConfigVersion();
|
||||||
boolean mainChanged = mainConfig != loadedMainConfig;
|
|
||||||
mainChanged |= migrateLegacyMainConfig(mainConfig);
|
|
||||||
mainChanged |= migrateLegacyDebugSettings(mainConfig);
|
|
||||||
mainChanged |= removeRetiredJeiSettings(mainConfig);
|
|
||||||
if (mainConfig.getInt("config-version", 0) != MAIN_CONFIG_VERSION) {
|
|
||||||
mainConfig.set("config-version", MAIN_CONFIG_VERSION);
|
|
||||||
mainChanged = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mainChanged) {
|
|
||||||
save(mainConfig, mainConfigFile);
|
|
||||||
}
|
|
||||||
plugin.reloadConfig();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public FileConfiguration getBlocksMenuConfig() {
|
public FileConfiguration getBlocksMenuConfig() {
|
||||||
@@ -64,66 +45,31 @@ public final class FeatureConfigManager {
|
|||||||
save(blocksMenuConfig, blocksMenuFile);
|
save(blocksMenuConfig, blocksMenuFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean updateMainConfigValue(String path, Object value) {
|
private void migrateLegacyMainConfig() {
|
||||||
YamlConfiguration mainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
FileConfiguration mainConfig = plugin.getConfig();
|
||||||
mainConfig.set(path, value);
|
boolean migrated = false;
|
||||||
if (!save(mainConfig, mainConfigFile)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
plugin.getConfig().set(path, value);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private YamlConfiguration migrateMainConfigVersion(YamlConfiguration existingConfig) {
|
|
||||||
int existingVersion = existingConfig.getInt("config-version", 0);
|
|
||||||
if (existingVersion >= MAIN_CONFIG_VERSION) {
|
|
||||||
return existingConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
File backupFile = new File(plugin.getDataFolder(),
|
|
||||||
"config.v" + existingVersion + ".bak-" + System.currentTimeMillis() + ".yml");
|
|
||||||
try {
|
|
||||||
Files.copy(mainConfigFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
YamlConfiguration migratedConfig = loadResource("config.yml");
|
|
||||||
if (migratedConfig == null) {
|
|
||||||
existingConfig.set("config-version", MAIN_CONFIG_VERSION);
|
|
||||||
return existingConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (String path : existingConfig.getKeys(true)) {
|
|
||||||
boolean legacyFeaturePath = path.startsWith("skin-bridge.") || path.startsWith("blocks-menu.");
|
|
||||||
if (!existingConfig.isConfigurationSection(path)
|
|
||||||
&& (migratedConfig.contains(path) || legacyFeaturePath)) {
|
|
||||||
migratedConfig.set(path, existingConfig.get(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
migratedConfig.set("config-version", MAIN_CONFIG_VERSION);
|
|
||||||
plugin.getLogger().info("已将 config.yml 从版本 " + existingVersion
|
|
||||||
+ " 迁移到 " + MAIN_CONFIG_VERSION + ",备份文件: " + backupFile.getName());
|
|
||||||
return migratedConfig;
|
|
||||||
} catch (IOException exception) {
|
|
||||||
plugin.getLogger().severe("迁移 config.yml 失败: " + exception.getMessage());
|
|
||||||
return existingConfig;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean migrateLegacyMainConfig(FileConfiguration mainConfig) {
|
|
||||||
if (!mainConfig.contains("blocks-menu", true)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (mainConfig.contains("blocks-menu", true)) {
|
||||||
copySection(mainConfig.getConfigurationSection("blocks-menu"), blocksMenuConfig);
|
copySection(mainConfig.getConfigurationSection("blocks-menu"), blocksMenuConfig);
|
||||||
mainConfig.set("blocks-menu", null);
|
mainConfig.set("blocks-menu", null);
|
||||||
saveBlocksMenuConfig();
|
migrated = true;
|
||||||
plugin.getLogger().info("已将便捷菜单配置迁移到 blocks-menu.yml。");
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean migrateLegacyDebugSettings(FileConfiguration mainConfig) {
|
if (!migrated) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mainConfig.set("config-version", MAIN_CONFIG_VERSION);
|
||||||
|
saveMainConfig();
|
||||||
|
plugin.getLogger().info("已将便捷菜单配置迁移到 blocks-menu.yml。");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void migrateLegacyDebugSettings() {
|
||||||
|
FileConfiguration mainConfig = plugin.getConfig();
|
||||||
boolean hasJeiDebug = mainConfig.contains("jei-sync.debug", true);
|
boolean hasJeiDebug = mainConfig.contains("jei-sync.debug", true);
|
||||||
boolean hasSkinBridgeDebug = mainConfig.contains("skin-bridge.debug", true);
|
boolean hasSkinBridgeDebug = mainConfig.contains("skin-bridge.debug", true);
|
||||||
if (!hasJeiDebug && !hasSkinBridgeDebug) {
|
if (!hasJeiDebug && !hasSkinBridgeDebug) {
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean debugEnabled = mainConfig.getBoolean("debug", false)
|
boolean debugEnabled = mainConfig.getBoolean("debug", false)
|
||||||
@@ -132,18 +78,16 @@ public final class FeatureConfigManager {
|
|||||||
mainConfig.set("debug", debugEnabled);
|
mainConfig.set("debug", debugEnabled);
|
||||||
mainConfig.set("jei-sync.debug", null);
|
mainConfig.set("jei-sync.debug", null);
|
||||||
mainConfig.set("skin-bridge.debug", null);
|
mainConfig.set("skin-bridge.debug", null);
|
||||||
|
saveMainConfig();
|
||||||
plugin.getLogger().info("已将独立功能调试开关合并到 config.yml 的全局 debug。");
|
plugin.getLogger().info("已将独立功能调试开关合并到 config.yml 的全局 debug。");
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean removeRetiredJeiSettings(FileConfiguration mainConfig) {
|
private void updateMainConfigVersion() {
|
||||||
if (!mainConfig.contains("jei-sync", true)) {
|
if (plugin.getConfig().getInt("config-version", 0) >= MAIN_CONFIG_VERSION) {
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
|
plugin.getConfig().set("config-version", MAIN_CONFIG_VERSION);
|
||||||
mainConfig.set("jei-sync", null);
|
saveMainConfig();
|
||||||
plugin.getLogger().info("已从 config.yml 移除停用的 JEI 配方同步配置。");
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void copySection(ConfigurationSection source, FileConfiguration target) {
|
private void copySection(ConfigurationSection source, FileConfiguration target) {
|
||||||
@@ -157,59 +101,34 @@ public final class FeatureConfigManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private YamlConfiguration loadWithDefaults(File file, String resourcePath) {
|
private FileConfiguration loadWithDefaults(File file, String resourcePath) {
|
||||||
YamlConfiguration config = loadFile(file);
|
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
|
||||||
YamlConfiguration defaults = loadResource(resourcePath);
|
InputStream defaultsStream = plugin.getResource(resourcePath);
|
||||||
if (defaults != null) {
|
if (defaultsStream != null) {
|
||||||
|
YamlConfiguration defaults = YamlConfiguration.loadConfiguration(
|
||||||
|
new InputStreamReader(defaultsStream, StandardCharsets.UTF_8)
|
||||||
|
);
|
||||||
config.setDefaults(defaults);
|
config.setDefaults(defaults);
|
||||||
config.options().copyDefaults(true);
|
config.options().copyDefaults(true);
|
||||||
}
|
}
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
private YamlConfiguration loadFile(File file) {
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
config.options().parseComments(true);
|
|
||||||
try {
|
|
||||||
config.load(file);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
plugin.getLogger().severe("加载 " + file.getName() + " 失败: " + exception.getMessage());
|
|
||||||
throw new IllegalStateException("无法加载 " + file.getName() + ",请修复配置格式后重试。", exception);
|
|
||||||
}
|
|
||||||
return config;
|
|
||||||
}
|
|
||||||
|
|
||||||
private YamlConfiguration loadResource(String resourcePath) {
|
|
||||||
InputStream resource = plugin.getResource(resourcePath);
|
|
||||||
if (resource == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
config.options().parseComments(true);
|
|
||||||
try (InputStream input = resource;
|
|
||||||
InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) {
|
|
||||||
config.load(reader);
|
|
||||||
return config;
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
plugin.getLogger().severe("加载内置资源 " + resourcePath + " 失败: " + exception.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureResource(File file, String resourcePath) {
|
private void ensureResource(File file, String resourcePath) {
|
||||||
if (!file.exists()) {
|
if (!file.exists()) {
|
||||||
plugin.saveResource(resourcePath, false);
|
plugin.saveResource(resourcePath, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean save(FileConfiguration config, File file) {
|
private void save(FileConfiguration config, File file) {
|
||||||
try {
|
try {
|
||||||
AtomicYamlWriter.save(config, file);
|
AtomicYamlWriter.save(config, file);
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
plugin.getLogger().warning("保存 " + file.getName() + " 失败: " + exception.getMessage());
|
plugin.getLogger().warning("保存 " + file.getName() + " 失败: " + exception.getMessage());
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void saveMainConfig() {
|
||||||
|
save(plugin.getConfig(), new File(plugin.getDataFolder(), "config.yml"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package cn.infstar.essentialsC;
|
package cn.infstar.essentialsC;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||||
|
import org.bukkit.ChatColor;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
@@ -12,6 +14,8 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -20,13 +24,9 @@ import java.util.regex.Pattern;
|
|||||||
|
|
||||||
public class LangManager {
|
public class LangManager {
|
||||||
|
|
||||||
|
private static final int CURRENT_CONFIG_VERSION = 2;
|
||||||
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("(?i)&#([0-9a-f]{6})");
|
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("(?i)&#([0-9a-f]{6})");
|
||||||
private static final Pattern MINI_MESSAGE_TAG_PATTERN = Pattern.compile(
|
|
||||||
"(?<!\\\\)(</?)([A-Za-z][A-Za-z0-9_-]*)(?=[:>])"
|
|
||||||
);
|
|
||||||
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
|
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
|
||||||
private static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.legacyAmpersand();
|
|
||||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
|
||||||
private static final Map<String, String> THEME_COLORS = Map.of(
|
private static final Map<String, String> THEME_COLORS = Map.of(
|
||||||
"&a", "�fb9a",
|
"&a", "�fb9a",
|
||||||
"&b", "ᒦff",
|
"&b", "ᒦff",
|
||||||
@@ -37,11 +37,13 @@ public class LangManager {
|
|||||||
);
|
);
|
||||||
|
|
||||||
private final JavaPlugin plugin;
|
private final JavaPlugin plugin;
|
||||||
|
private FileConfiguration config;
|
||||||
private FileConfiguration langFile;
|
private FileConfiguration langFile;
|
||||||
private String currentLanguage;
|
private String currentLanguage;
|
||||||
|
|
||||||
public LangManager(JavaPlugin plugin) {
|
public LangManager(JavaPlugin plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
loadConfig();
|
||||||
loadLanguage();
|
loadLanguage();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +74,8 @@ public class LangManager {
|
|||||||
public Component getComponent(String path, Map<String, String> placeholders) {
|
public Component getComponent(String path, Map<String, String> placeholders) {
|
||||||
String value = langFile.getString(path);
|
String value = langFile.getString(path);
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return LEGACY_SECTION.deserialize(translateColorCodes("&c缺少语言文本: " + path));
|
return LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(translateColorCodes("&c缺少语言文本: " + path));
|
||||||
}
|
}
|
||||||
|
|
||||||
return renderToComponent(applyPlaceholders(value, placeholders));
|
return renderToComponent(applyPlaceholders(value, placeholders));
|
||||||
@@ -85,7 +88,8 @@ public class LangManager {
|
|||||||
public Component getPrefixedComponent(String path, Map<String, String> placeholders) {
|
public Component getPrefixedComponent(String path, Map<String, String> placeholders) {
|
||||||
String value = langFile.getString(path);
|
String value = langFile.getString(path);
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return LEGACY_SECTION.deserialize(getPrefix() + translateColorCodes("&c缺少语言文本: " + path));
|
return LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(getPrefix() + translateColorCodes("&c缺少语言文本: " + path));
|
||||||
}
|
}
|
||||||
return renderToComponent(langFile.getString("prefix", "") + applyPlaceholders(value, placeholders));
|
return renderToComponent(langFile.getString("prefix", "") + applyPlaceholders(value, placeholders));
|
||||||
}
|
}
|
||||||
@@ -112,6 +116,7 @@ public class LangManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
|
loadConfig();
|
||||||
loadLanguage();
|
loadLanguage();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,8 +124,66 @@ public class LangManager {
|
|||||||
return currentLanguage;
|
return currentLanguage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void loadConfig() {
|
||||||
|
File configFile = new File(plugin.getDataFolder(), "config.yml");
|
||||||
|
if (!configFile.exists()) {
|
||||||
|
plugin.saveResource("config.yml", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
migrateConfigIfNeeded(configFile);
|
||||||
|
config = YamlConfiguration.loadConfiguration(configFile);
|
||||||
|
config.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
||||||
|
config.addDefault("language", "zh_CN");
|
||||||
|
config.addDefault("debug", false);
|
||||||
|
config.options().copyDefaults(true);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void migrateConfigIfNeeded(File configFile) {
|
||||||
|
FileConfiguration existingConfig = YamlConfiguration.loadConfiguration(configFile);
|
||||||
|
int existingVersion = existingConfig.getInt("config-version", 0);
|
||||||
|
if (existingVersion >= CURRENT_CONFIG_VERSION) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
File backupFile = new File(plugin.getDataFolder(),
|
||||||
|
"config.v" + existingVersion + ".bak-" + System.currentTimeMillis() + ".yml");
|
||||||
|
|
||||||
|
try {
|
||||||
|
Files.copy(configFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
InputStream defaultConfigStream = plugin.getResource("config.yml");
|
||||||
|
if (defaultConfigStream != null) {
|
||||||
|
YamlConfiguration migratedConfig = YamlConfiguration.loadConfiguration(
|
||||||
|
new InputStreamReader(defaultConfigStream, StandardCharsets.UTF_8)
|
||||||
|
);
|
||||||
|
for (String path : existingConfig.getKeys(true)) {
|
||||||
|
boolean migratedFeaturePath = path.startsWith("skin-bridge.") || path.startsWith("blocks-menu.");
|
||||||
|
if (!existingConfig.isConfigurationSection(path)
|
||||||
|
&& (migratedConfig.contains(path) || migratedFeaturePath)) {
|
||||||
|
migratedConfig.set(path, existingConfig.get(path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boolean debugEnabled = existingConfig.getBoolean("debug", false)
|
||||||
|
|| existingConfig.getBoolean("jei-sync.debug", false)
|
||||||
|
|| existingConfig.getBoolean("skin-bridge.debug", false);
|
||||||
|
migratedConfig.set("debug", debugEnabled);
|
||||||
|
migratedConfig.set("jei-sync.debug", null);
|
||||||
|
migratedConfig.set("config-version", CURRENT_CONFIG_VERSION);
|
||||||
|
AtomicYamlWriter.save(migratedConfig, configFile);
|
||||||
|
} else {
|
||||||
|
existingConfig.set("config-version", CURRENT_CONFIG_VERSION);
|
||||||
|
AtomicYamlWriter.save(existingConfig, configFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
plugin.getLogger().info("已将 config.yml 从版本 " + existingVersion
|
||||||
|
+ " 迁移到 " + CURRENT_CONFIG_VERSION + ",备份文件: " + backupFile.getName());
|
||||||
|
} catch (IOException e) {
|
||||||
|
plugin.getLogger().severe("迁移 config.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void loadLanguage() {
|
private void loadLanguage() {
|
||||||
currentLanguage = plugin.getConfig().getString("language", "zh_CN");
|
currentLanguage = config.getString("language", "zh_CN");
|
||||||
|
|
||||||
File langFolder = new File(plugin.getDataFolder(), "lang");
|
File langFolder = new File(plugin.getDataFolder(), "lang");
|
||||||
if (!langFolder.exists() && !langFolder.mkdirs()) {
|
if (!langFolder.exists() && !langFolder.mkdirs()) {
|
||||||
@@ -164,25 +227,18 @@ public class LangManager {
|
|||||||
langFile.setDefaults(selectedDefaults);
|
langFile.setDefaults(selectedDefaults);
|
||||||
}
|
}
|
||||||
|
|
||||||
static String applyPlaceholders(String value, Map<String, String> placeholders) {
|
private String applyPlaceholders(String value, Map<String, String> placeholders) {
|
||||||
String result = value;
|
String result = value;
|
||||||
boolean miniMessage = looksLikeMiniMessage(value);
|
|
||||||
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
|
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
|
||||||
String replacement = miniMessage
|
result = result.replace("{" + entry.getKey() + "}", escapeMiniMessageReplacement(entry.getValue()));
|
||||||
? escapeMiniMessageReplacement(entry.getValue())
|
|
||||||
: entry.getValue();
|
|
||||||
result = result.replace("{" + entry.getKey() + "}", replacement == null ? "" : replacement);
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
static String escapeMiniMessageReplacement(String value) {
|
private String escapeMiniMessageReplacement(String value) {
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
if (value.indexOf('§') >= 0) {
|
|
||||||
return MINI_MESSAGE.serialize(LEGACY_SECTION.deserialize(value));
|
|
||||||
}
|
|
||||||
return value.replace("\\", "\\\\").replace("<", "\\<");
|
return value.replace("\\", "\\\\").replace("<", "\\<");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +251,7 @@ public class LangManager {
|
|||||||
for (Map.Entry<String, String> color : THEME_COLORS.entrySet()) {
|
for (Map.Entry<String, String> color : THEME_COLORS.entrySet()) {
|
||||||
themedText = themedText.replace(color.getKey(), color.getValue());
|
themedText = themedText.replace(color.getKey(), color.getValue());
|
||||||
}
|
}
|
||||||
return LEGACY_SECTION.serialize(LEGACY_AMPERSAND.deserialize(expandHexColors(themedText)));
|
return ChatColor.translateAlternateColorCodes('&', expandHexColors(themedText));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String expandHexColors(String text) {
|
private String expandHexColors(String text) {
|
||||||
@@ -214,7 +270,7 @@ public class LangManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String renderToLegacy(String text) {
|
private String renderToLegacy(String text) {
|
||||||
return LEGACY_SECTION.serialize(renderToComponent(text));
|
return LegacyComponentSerializer.legacySection().serialize(renderToComponent(text));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Component renderToComponent(String text) {
|
private Component renderToComponent(String text) {
|
||||||
@@ -223,28 +279,16 @@ public class LangManager {
|
|||||||
}
|
}
|
||||||
if (looksLikeMiniMessage(text)) {
|
if (looksLikeMiniMessage(text)) {
|
||||||
try {
|
try {
|
||||||
return MINI_MESSAGE.deserialize(normalizeMiniMessageTags(text));
|
return MINI_MESSAGE.deserialize(text);
|
||||||
} catch (RuntimeException ignored) {
|
} catch (RuntimeException ignored) {
|
||||||
// 配置中 MiniMessage 语法错误时回退到旧颜色码解析,避免消息完全不可用。
|
// 配置中 MiniMessage 语法错误时回退到旧颜色码解析,避免消息完全不可用。
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return LEGACY_SECTION.deserialize(translateColorCodes(text));
|
return LegacyComponentSerializer.legacySection().deserialize(translateColorCodes(text));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean looksLikeMiniMessage(String text) {
|
private boolean looksLikeMiniMessage(String text) {
|
||||||
int open = text.indexOf('<');
|
int open = text.indexOf('<');
|
||||||
return open >= 0 && text.indexOf('>', open) > open;
|
return open >= 0 && text.indexOf('>', open) > open;
|
||||||
}
|
}
|
||||||
|
|
||||||
static String normalizeMiniMessageTags(String text) {
|
|
||||||
Matcher matcher = MINI_MESSAGE_TAG_PATTERN.matcher(text);
|
|
||||||
StringBuilder result = new StringBuilder();
|
|
||||||
while (matcher.find()) {
|
|
||||||
matcher.appendReplacement(result, Matcher.quoteReplacement(
|
|
||||||
matcher.group(1) + matcher.group(2).toLowerCase(java.util.Locale.ROOT)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
matcher.appendTail(result);
|
|
||||||
return result.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
package cn.infstar.essentialsC;
|
package cn.infstar.essentialsC;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -18,7 +15,9 @@ public final class ModuleManager {
|
|||||||
public static final String BLOCKS = "blocks";
|
public static final String BLOCKS = "blocks";
|
||||||
public static final String ADMIN_MODE = "admin-mode";
|
public static final String ADMIN_MODE = "admin-mode";
|
||||||
public static final String TPSBAR = "tpsbar";
|
public static final String TPSBAR = "tpsbar";
|
||||||
|
public static final String JEI_SYNC = "jei-sync";
|
||||||
public static final String MOB_DROPS = "mob-drops";
|
public static final String MOB_DROPS = "mob-drops";
|
||||||
|
public static final String MAINTENANCE = "maintenance";
|
||||||
public static final String SKIN_BRIDGE = "skin-bridge";
|
public static final String SKIN_BRIDGE = "skin-bridge";
|
||||||
|
|
||||||
private static final Map<String, Boolean> DEFAULT_MODULES = new LinkedHashMap<>();
|
private static final Map<String, Boolean> DEFAULT_MODULES = new LinkedHashMap<>();
|
||||||
@@ -27,7 +26,9 @@ public final class ModuleManager {
|
|||||||
DEFAULT_MODULES.put(BLOCKS, true);
|
DEFAULT_MODULES.put(BLOCKS, true);
|
||||||
DEFAULT_MODULES.put(ADMIN_MODE, true);
|
DEFAULT_MODULES.put(ADMIN_MODE, true);
|
||||||
DEFAULT_MODULES.put(TPSBAR, true);
|
DEFAULT_MODULES.put(TPSBAR, true);
|
||||||
|
DEFAULT_MODULES.put(JEI_SYNC, true);
|
||||||
DEFAULT_MODULES.put(MOB_DROPS, false);
|
DEFAULT_MODULES.put(MOB_DROPS, false);
|
||||||
|
DEFAULT_MODULES.put(MAINTENANCE, true);
|
||||||
DEFAULT_MODULES.put(SKIN_BRIDGE, false);
|
DEFAULT_MODULES.put(SKIN_BRIDGE, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,36 +47,12 @@ public final class ModuleManager {
|
|||||||
plugin.saveResource("modules.yml", false);
|
plugin.saveResource("modules.yml", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
YamlConfiguration loaded = new YamlConfiguration();
|
modulesConfig = YamlConfiguration.loadConfiguration(modulesFile);
|
||||||
loaded.options().parseComments(true);
|
|
||||||
try {
|
|
||||||
loaded.load(modulesFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
plugin.getLogger().severe("加载 modules.yml 失败: " + exception.getMessage());
|
|
||||||
throw new IllegalStateException("无法加载 modules.yml,请修复配置格式后重试。", exception);
|
|
||||||
}
|
|
||||||
modulesConfig = loaded;
|
|
||||||
boolean removedRetiredModules = false;
|
|
||||||
for (String retiredModule : new String[]{"jei-sync", "maintenance"}) {
|
|
||||||
String retiredPath = "modules." + retiredModule;
|
|
||||||
if (modulesConfig.contains(retiredPath, true)) {
|
|
||||||
modulesConfig.set(retiredPath, null);
|
|
||||||
removedRetiredModules = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
modulesConfig.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
modulesConfig.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
||||||
for (Map.Entry<String, Boolean> module : DEFAULT_MODULES.entrySet()) {
|
for (Map.Entry<String, Boolean> module : DEFAULT_MODULES.entrySet()) {
|
||||||
modulesConfig.addDefault(path(module.getKey()), module.getValue());
|
modulesConfig.addDefault(path(module.getKey()), module.getValue());
|
||||||
}
|
}
|
||||||
modulesConfig.options().copyDefaults(true);
|
modulesConfig.options().copyDefaults(true);
|
||||||
if (removedRetiredModules) {
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(modulesConfig, modulesFile);
|
|
||||||
plugin.getLogger().info("已从 modules.yml 移除退役功能的配置项。");
|
|
||||||
} catch (IOException exception) {
|
|
||||||
plugin.getLogger().warning("清理 modules.yml 中的退役配置失败: " + exception.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEnabled(String moduleKey) {
|
public boolean isEnabled(String moduleKey) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.infstar.essentialsC.admin;
|
package cn.infstar.essentialsC.admin;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import org.bukkit.GameMode;
|
import org.bukkit.GameMode;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.attribute.Attribute;
|
import org.bukkit.attribute.Attribute;
|
||||||
@@ -14,6 +15,7 @@ import org.bukkit.inventory.ItemStack;
|
|||||||
import org.bukkit.inventory.PlayerInventory;
|
import org.bukkit.inventory.PlayerInventory;
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
import org.bukkit.scheduler.BukkitTask;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
@@ -26,7 +28,8 @@ public final class AdminModeManager implements Listener {
|
|||||||
private static final float VANILLA_FLY_SPEED = 0.1F;
|
private static final float VANILLA_FLY_SPEED = 0.1F;
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final AdminModeStore store;
|
private final File dataFile;
|
||||||
|
private final YamlConfiguration data;
|
||||||
private final Set<UUID> activePlayers = new HashSet<>();
|
private final Set<UUID> activePlayers = new HashSet<>();
|
||||||
|
|
||||||
private BukkitTask actionBarTask;
|
private BukkitTask actionBarTask;
|
||||||
@@ -34,7 +37,8 @@ public final class AdminModeManager implements Listener {
|
|||||||
public AdminModeManager(EssentialsC plugin) {
|
public AdminModeManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
addConfigDefaults();
|
addConfigDefaults();
|
||||||
this.store = new AdminModeStore(plugin);
|
this.dataFile = new File(plugin.getDataFolder(), "admin-mode.yml");
|
||||||
|
this.data = YamlConfiguration.loadConfiguration(dataFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
@@ -78,37 +82,21 @@ public final class AdminModeManager implements Listener {
|
|||||||
actionBarTask.cancel();
|
actionBarTask.cancel();
|
||||||
actionBarTask = null;
|
actionBarTask = null;
|
||||||
}
|
}
|
||||||
|
saveData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
Player player = event.getPlayer();
|
Player player = event.getPlayer();
|
||||||
YamlConfiguration data = store.load(player.getUniqueId());
|
String playerPath = getPlayerPath(player);
|
||||||
if (data == null) {
|
if (!data.getBoolean(playerPath + ".active", false)) {
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!data.getBoolean("active", false)) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
saveProfile(player, data, "admin");
|
saveProfile(player, playerPath + ".admin");
|
||||||
if (!saveData(player, data)) {
|
restoreNormalProfile(player);
|
||||||
activePlayers.add(player.getUniqueId());
|
data.set(playerPath + ".active", false);
|
||||||
startActionBarTask();
|
saveData();
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
restoreNormalProfile(player, data);
|
|
||||||
data.set("active", false);
|
|
||||||
if (!saveData(player, data)) {
|
|
||||||
data.set("active", true);
|
|
||||||
loadProfile(player, data, "admin");
|
|
||||||
activePlayers.add(player.getUniqueId());
|
|
||||||
startActionBarTask();
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sendLangMessage(player, "admin-mode.messages.crash-restored");
|
sendLangMessage(player, "admin-mode.messages.crash-restored");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,21 +109,17 @@ public final class AdminModeManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void enable(Player player) {
|
private void enable(Player player) {
|
||||||
YamlConfiguration data = store.load(player.getUniqueId());
|
String playerPath = getPlayerPath(player);
|
||||||
if (data == null) {
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
player.closeInventory();
|
player.closeInventory();
|
||||||
saveProfile(player, data, "normal");
|
saveProfile(player, playerPath + ".normal");
|
||||||
data.set("active", true);
|
data.set(playerPath + ".active", true);
|
||||||
if (!saveData(player, data)) {
|
if (!saveData()) {
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
sendLangMessage(player, "admin-mode.messages.save-failed");
|
||||||
data.set("active", false);
|
data.set(playerPath + ".active", false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!loadProfile(player, data, "admin")) {
|
if (!loadProfile(player, playerPath + ".admin")) {
|
||||||
clearInventory(player);
|
clearInventory(player);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,53 +129,32 @@ public final class AdminModeManager implements Listener {
|
|||||||
player.setAllowFlight(true);
|
player.setAllowFlight(true);
|
||||||
player.setFlying(true);
|
player.setFlying(true);
|
||||||
player.setFlySpeed(getAdminFlySpeed());
|
player.setFlySpeed(getAdminFlySpeed());
|
||||||
|
saveData();
|
||||||
|
|
||||||
sendLangMessage(player, "admin-mode.messages.enabled");
|
sendLangMessage(player, "admin-mode.messages.enabled");
|
||||||
sendActionBar(player);
|
sendActionBar(player);
|
||||||
startActionBarTask();
|
startActionBarTask();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean disable(Player player, boolean notify) {
|
private void disable(Player player, boolean notify) {
|
||||||
YamlConfiguration data = store.load(player.getUniqueId());
|
String playerPath = getPlayerPath(player);
|
||||||
if (data == null) {
|
|
||||||
if (notify) {
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
player.closeInventory();
|
player.closeInventory();
|
||||||
saveProfile(player, data, "admin");
|
saveProfile(player, playerPath + ".admin");
|
||||||
data.set("active", true);
|
restoreNormalProfile(player);
|
||||||
if (!saveData(player, data)) {
|
|
||||||
if (notify) {
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
restoreNormalProfile(player, data);
|
|
||||||
|
|
||||||
data.set("active", false);
|
|
||||||
if (!saveData(player, data)) {
|
|
||||||
data.set("active", true);
|
|
||||||
loadProfile(player, data, "admin");
|
|
||||||
activePlayers.add(player.getUniqueId());
|
|
||||||
if (notify) {
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
activePlayers.remove(player.getUniqueId());
|
activePlayers.remove(player.getUniqueId());
|
||||||
|
data.set(playerPath + ".active", false);
|
||||||
|
saveData();
|
||||||
|
|
||||||
if (notify) {
|
if (notify) {
|
||||||
sendLangMessage(player, "admin-mode.messages.disabled");
|
sendLangMessage(player, "admin-mode.messages.disabled");
|
||||||
}
|
}
|
||||||
stopActionBarTaskIfIdle();
|
stopActionBarTaskIfIdle();
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void restoreNormalProfile(Player player, YamlConfiguration data) {
|
private void restoreNormalProfile(Player player) {
|
||||||
if (!loadProfile(player, data, "normal")) {
|
String playerPath = getPlayerPath(player);
|
||||||
|
if (!loadProfile(player, playerPath + ".normal")) {
|
||||||
clearInventory(player);
|
clearInventory(player);
|
||||||
player.setGameMode(GameMode.SURVIVAL);
|
player.setGameMode(GameMode.SURVIVAL);
|
||||||
player.setAllowFlight(false);
|
player.setAllowFlight(false);
|
||||||
@@ -200,7 +163,7 @@ public final class AdminModeManager implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void saveProfile(Player player, YamlConfiguration data, String path) {
|
private void saveProfile(Player player, String path) {
|
||||||
PlayerInventory inventory = player.getInventory();
|
PlayerInventory inventory = player.getInventory();
|
||||||
data.set(path + ".storage", Arrays.asList(inventory.getStorageContents()));
|
data.set(path + ".storage", Arrays.asList(inventory.getStorageContents()));
|
||||||
data.set(path + ".armor", Arrays.asList(inventory.getArmorContents()));
|
data.set(path + ".armor", Arrays.asList(inventory.getArmorContents()));
|
||||||
@@ -221,24 +184,24 @@ public final class AdminModeManager implements Listener {
|
|||||||
data.set(path + ".fire-ticks", player.getFireTicks());
|
data.set(path + ".fire-ticks", player.getFireTicks());
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean loadProfile(Player player, YamlConfiguration data, String path) {
|
private boolean loadProfile(Player player, String path) {
|
||||||
if (!data.contains(path)) {
|
if (!data.contains(path)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
PlayerInventory inventory = player.getInventory();
|
PlayerInventory inventory = player.getInventory();
|
||||||
clearInventory(player);
|
clearInventory(player);
|
||||||
inventory.setStorageContents(readItemArray(data, path + ".storage", inventory.getStorageContents().length));
|
inventory.setStorageContents(readItemArray(path + ".storage", inventory.getStorageContents().length));
|
||||||
inventory.setArmorContents(readItemArray(data, path + ".armor", inventory.getArmorContents().length));
|
inventory.setArmorContents(readItemArray(path + ".armor", inventory.getArmorContents().length));
|
||||||
inventory.setExtraContents(readItemArray(data, path + ".extra", inventory.getExtraContents().length));
|
inventory.setExtraContents(readItemArray(path + ".extra", inventory.getExtraContents().length));
|
||||||
inventory.setHeldItemSlot(clampHeldSlot(data.getInt(path + ".held-slot", inventory.getHeldItemSlot())));
|
inventory.setHeldItemSlot(clampHeldSlot(data.getInt(path + ".held-slot", inventory.getHeldItemSlot())));
|
||||||
player.setItemOnCursor(readItem(data, path + ".cursor"));
|
player.setItemOnCursor(readItem(path + ".cursor"));
|
||||||
|
|
||||||
player.setGameMode(readGameMode(data, path + ".game-mode", player.getGameMode()));
|
player.setGameMode(readGameMode(path + ".game-mode", player.getGameMode()));
|
||||||
player.setAllowFlight(data.getBoolean(path + ".allow-flight", player.getAllowFlight()));
|
player.setAllowFlight(data.getBoolean(path + ".allow-flight", player.getAllowFlight()));
|
||||||
player.setFlying(data.getBoolean(path + ".flying", false) && player.getAllowFlight());
|
player.setFlying(data.getBoolean(path + ".flying", false) && player.getAllowFlight());
|
||||||
player.setFlySpeed(clampFlySpeed(data.getDouble(path + ".fly-speed", VANILLA_FLY_SPEED)));
|
player.setFlySpeed(clampFlySpeed(data.getDouble(path + ".fly-speed", VANILLA_FLY_SPEED)));
|
||||||
player.setHealth(readHealth(player, data, path + ".health"));
|
player.setHealth(readHealth(player, path + ".health"));
|
||||||
player.setFoodLevel(clampFoodLevel(data.getInt(path + ".food-level", player.getFoodLevel())));
|
player.setFoodLevel(clampFoodLevel(data.getInt(path + ".food-level", player.getFoodLevel())));
|
||||||
player.setSaturation(clampSaturation(data.getDouble(path + ".saturation", player.getSaturation())));
|
player.setSaturation(clampSaturation(data.getDouble(path + ".saturation", player.getSaturation())));
|
||||||
player.setExhaustion(clampExhaustion(data.getDouble(path + ".exhaustion", player.getExhaustion())));
|
player.setExhaustion(clampExhaustion(data.getDouble(path + ".exhaustion", player.getExhaustion())));
|
||||||
@@ -249,7 +212,7 @@ public final class AdminModeManager implements Listener {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ItemStack[] readItemArray(YamlConfiguration data, String path, int size) {
|
private ItemStack[] readItemArray(String path, int size) {
|
||||||
ItemStack[] items = new ItemStack[size];
|
ItemStack[] items = new ItemStack[size];
|
||||||
List<?> list = data.getList(path);
|
List<?> list = data.getList(path);
|
||||||
if (list == null) {
|
if (list == null) {
|
||||||
@@ -265,7 +228,7 @@ public final class AdminModeManager implements Listener {
|
|||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
private GameMode readGameMode(YamlConfiguration data, String path, GameMode fallback) {
|
private GameMode readGameMode(String path, GameMode fallback) {
|
||||||
try {
|
try {
|
||||||
return GameMode.valueOf(data.getString(path, fallback.name()));
|
return GameMode.valueOf(data.getString(path, fallback.name()));
|
||||||
} catch (IllegalArgumentException ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
@@ -273,7 +236,7 @@ public final class AdminModeManager implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private double readHealth(Player player, YamlConfiguration data, String path) {
|
private double readHealth(Player player, String path) {
|
||||||
double maxHealth = player.getAttribute(Attribute.MAX_HEALTH) != null
|
double maxHealth = player.getAttribute(Attribute.MAX_HEALTH) != null
|
||||||
? player.getAttribute(Attribute.MAX_HEALTH).getValue()
|
? player.getAttribute(Attribute.MAX_HEALTH).getValue()
|
||||||
: player.getHealth();
|
: player.getHealth();
|
||||||
@@ -284,7 +247,7 @@ public final class AdminModeManager implements Listener {
|
|||||||
return Math.min(Math.max(1.0D, health), maxHealth);
|
return Math.min(Math.max(1.0D, health), maxHealth);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ItemStack readItem(YamlConfiguration data, String path) {
|
private ItemStack readItem(String path) {
|
||||||
Object value = data.get(path);
|
Object value = data.get(path);
|
||||||
if (value instanceof ItemStack itemStack) {
|
if (value instanceof ItemStack itemStack) {
|
||||||
return itemStack;
|
return itemStack;
|
||||||
@@ -371,12 +334,22 @@ public final class AdminModeManager implements Listener {
|
|||||||
return (float) Math.max(0.0D, Math.min(1.0D, exp));
|
return (float) Math.max(0.0D, Math.min(1.0D, exp));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String getPlayerPath(Player player) {
|
||||||
|
return "players." + player.getUniqueId();
|
||||||
|
}
|
||||||
|
|
||||||
private void sendLangMessage(Player player, String path) {
|
private void sendLangMessage(Player player, String path) {
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(path));
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(path));
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean saveData(Player player, YamlConfiguration data) {
|
private boolean saveData() {
|
||||||
return store.save(player.getUniqueId(), data);
|
try {
|
||||||
|
AtomicYamlWriter.save(data, dataFile);
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("保存 admin-mode.yml 失败: " + e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addConfigDefaults() {
|
private void addConfigDefaults() {
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.admin;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
final class AdminModeStore {
|
|
||||||
|
|
||||||
private final File directory;
|
|
||||||
private final File legacyFile;
|
|
||||||
private final Logger logger;
|
|
||||||
|
|
||||||
AdminModeStore(EssentialsC plugin) {
|
|
||||||
this(new File(plugin.getDataFolder(), "admin-mode"),
|
|
||||||
new File(plugin.getDataFolder(), "admin-mode.yml"), plugin.getLogger());
|
|
||||||
}
|
|
||||||
|
|
||||||
AdminModeStore(File directory, File legacyFile, Logger logger) {
|
|
||||||
this.directory = directory;
|
|
||||||
this.legacyFile = legacyFile;
|
|
||||||
this.logger = logger;
|
|
||||||
migrateLegacyFile();
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration load(UUID playerId) {
|
|
||||||
File playerFile = getPlayerFile(playerId);
|
|
||||||
YamlConfiguration data = new YamlConfiguration();
|
|
||||||
if (!playerFile.exists()) {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
data.load(playerFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
logger.warning("加载管理模式玩家存档失败 (" + playerId + "): " + exception.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean save(UUID playerId, YamlConfiguration data) {
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(data, getPlayerFile(playerId));
|
|
||||||
return true;
|
|
||||||
} catch (IOException exception) {
|
|
||||||
logger.warning("保存管理模式玩家存档失败 (" + playerId + "): " + exception.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void migrateLegacyFile() {
|
|
||||||
if (!legacyFile.exists()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration legacy = new YamlConfiguration();
|
|
||||||
try {
|
|
||||||
legacy.load(legacyFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
logger.warning("加载旧 admin-mode.yml 失败,已保留原文件: " + exception.getMessage());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigurationSection players = legacy.getConfigurationSection("players");
|
|
||||||
if (players != null) {
|
|
||||||
for (String playerIdText : players.getKeys(false)) {
|
|
||||||
UUID playerId;
|
|
||||||
try {
|
|
||||||
playerId = UUID.fromString(playerIdText);
|
|
||||||
} catch (IllegalArgumentException exception) {
|
|
||||||
logger.warning("忽略 admin-mode.yml 中无效的玩家 UUID: " + playerIdText);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (getPlayerFile(playerId).exists()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
YamlConfiguration migrated = new YamlConfiguration();
|
|
||||||
copySection(players.getConfigurationSection(playerIdText), migrated);
|
|
||||||
if (!save(playerId, migrated)) {
|
|
||||||
logger.warning("admin-mode.yml 迁移未完成,已保留原文件供下次重试。");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
File backup = new File(legacyFile.getParentFile(),
|
|
||||||
"admin-mode.legacy-" + System.currentTimeMillis() + ".yml");
|
|
||||||
try {
|
|
||||||
Files.move(legacyFile.toPath(), backup.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
logger.info("已将 admin-mode.yml 拆分为每玩家存档,旧文件已备份为 " + backup.getName());
|
|
||||||
} catch (IOException exception) {
|
|
||||||
logger.warning("备份旧 admin-mode.yml 失败: " + exception.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void copySection(ConfigurationSection source, YamlConfiguration target) {
|
|
||||||
if (source == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (String path : source.getKeys(true)) {
|
|
||||||
if (!source.isConfigurationSection(path)) {
|
|
||||||
target.set(path, source.get(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private File getPlayerFile(UUID playerId) {
|
|
||||||
return new File(directory, playerId + ".yml");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class AnvilCommand extends BaseCommand {
|
public class AnvilCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class AnvilCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.ANVIL.builder().checkReachable(false).build(player));
|
player.openAnvil(null, true);
|
||||||
playBlockShortcutSound(player, Material.ANVIL, Sound.BLOCK_ANVIL_USE);
|
playBlockShortcutSound(player, Material.ANVIL, Sound.BLOCK_ANVIL_USE);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,17 +49,12 @@ public abstract class BaseCommand implements CommandExecutor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||||
return dispatch(sender, args);
|
if (sender instanceof Player player) {
|
||||||
}
|
if (!player.hasPermission(permission)) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
||||||
final boolean dispatch(CommandSender sender, String[] args) {
|
|
||||||
if (!sender.hasPermission(permission)) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
|
||||||
Map.of("permission", permission)));
|
Map.of("permission", permission)));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sender instanceof Player player) {
|
|
||||||
return execute(player, args);
|
return execute(player, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
|
import org.bukkit.ChatColor;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.NamespacedKey;
|
import org.bukkit.NamespacedKey;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
@@ -15,8 +16,6 @@ import org.bukkit.inventory.InventoryHolder;
|
|||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
import org.bukkit.inventory.meta.ItemMeta;
|
import org.bukkit.inventory.meta.ItemMeta;
|
||||||
import org.bukkit.persistence.PersistentDataType;
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
import net.kyori.adventure.text.Component;
|
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -26,12 +25,14 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
|
|
||||||
private static final int MENU_SIZE = 36;
|
private static final int MENU_SIZE = 36;
|
||||||
private static final int[] DIVIDER_SLOTS = {4, 13, 22, 31};
|
private static final int[] DIVIDER_SLOTS = {4, 13, 22, 31};
|
||||||
|
private static boolean listenerRegistered = false;
|
||||||
|
|
||||||
private final NamespacedKey blockKey;
|
private final NamespacedKey blockKey;
|
||||||
|
|
||||||
private static final class BlocksMenuHolder implements InventoryHolder {
|
private static final class BlocksMenuHolder implements InventoryHolder {
|
||||||
private final Inventory inventory;
|
private final Inventory inventory;
|
||||||
|
|
||||||
private BlocksMenuHolder(Component title) {
|
private BlocksMenuHolder(String title) {
|
||||||
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,6 +45,10 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
public BlocksMenuCommand() {
|
public BlocksMenuCommand() {
|
||||||
super("essentialsc.command.blocks");
|
super("essentialsc.command.blocks");
|
||||||
addConfigDefaults();
|
addConfigDefaults();
|
||||||
|
if (!listenerRegistered) {
|
||||||
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
|
listenerRegistered = true;
|
||||||
|
}
|
||||||
this.blockKey = new NamespacedKey(plugin, "block_key");
|
this.blockKey = new NamespacedKey(plugin, "block_key");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +59,7 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void openMenu(Player player) {
|
private void openMenu(Player player) {
|
||||||
Inventory menu = new BlocksMenuHolder(getLang().getComponent("blocks-menu.title")).getInventory();
|
Inventory menu = new BlocksMenuHolder(getLang().getString("blocks-menu.title")).getInventory();
|
||||||
|
|
||||||
FileConfiguration menuConfig = plugin.getFeatureConfigManager().getBlocksMenuConfig();
|
FileConfiguration menuConfig = plugin.getFeatureConfigManager().getBlocksMenuConfig();
|
||||||
var sectionsConfig = menuConfig.getConfigurationSection("sections");
|
var sectionsConfig = menuConfig.getConfigurationSection("sections");
|
||||||
@@ -165,10 +170,8 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
ItemStack item = new ItemStack(menuItem.material());
|
ItemStack item = new ItemStack(menuItem.material());
|
||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
if (meta != null) {
|
if (meta != null) {
|
||||||
meta.displayName(legacyComponent(menuItem.name()));
|
meta.setDisplayName(menuItem.name());
|
||||||
meta.lore(menuItem.lore().isEmpty() ? null : menuItem.lore().stream()
|
meta.setLore(menuItem.lore().isEmpty() ? null : menuItem.lore());
|
||||||
.map(this::legacyComponent)
|
|
||||||
.toList());
|
|
||||||
if (menuItem.commandKey() != null && !menuItem.commandKey().isBlank()) {
|
if (menuItem.commandKey() != null && !menuItem.commandKey().isBlank()) {
|
||||||
meta.getPersistentDataContainer().set(blockKey, PersistentDataType.STRING, menuItem.commandKey());
|
meta.getPersistentDataContainer().set(blockKey, PersistentDataType.STRING, menuItem.commandKey());
|
||||||
}
|
}
|
||||||
@@ -181,7 +184,7 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
ItemStack divider = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
|
ItemStack divider = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
|
||||||
ItemMeta meta = divider.getItemMeta();
|
ItemMeta meta = divider.getItemMeta();
|
||||||
if (meta != null) {
|
if (meta != null) {
|
||||||
meta.displayName(Component.text(" "));
|
meta.setDisplayName(" ");
|
||||||
divider.setItemMeta(meta);
|
divider.setItemMeta(meta);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,8 +250,8 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Component legacyComponent(String text) {
|
private String translateColor(String text) {
|
||||||
return LegacyComponentSerializer.legacySection().deserialize(text == null ? "" : text);
|
return text == null ? "" : ChatColor.translateAlternateColorCodes('&', text);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addConfigDefaults() {
|
private void addConfigDefaults() {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class CartographyTableCommand extends BaseCommand {
|
public class CartographyTableCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class CartographyTableCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.CARTOGRAPHY_TABLE.builder().checkReachable(false).build(player));
|
player.openCartographyTable(null, true);
|
||||||
playBlockShortcutSound(player, Material.CARTOGRAPHY_TABLE, Sound.ENTITY_VILLAGER_WORK_CARTOGRAPHER);
|
playBlockShortcutSound(player, Material.CARTOGRAPHY_TABLE, Sound.ENTITY_VILLAGER_WORK_CARTOGRAPHER);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ public final class CommandRegistry {
|
|||||||
registerCore("tpignore", "essentialsc.command.tpignore", TpIgnoreCommand::new);
|
registerCore("tpignore", "essentialsc.command.tpignore", TpIgnoreCommand::new);
|
||||||
register("tpsbar", "essentialsc.command.tpsbar", ModuleManager.TPSBAR, TpsBarCommand::new);
|
register("tpsbar", "essentialsc.command.tpsbar", ModuleManager.TPSBAR, TpsBarCommand::new);
|
||||||
register("mobdrops", "essentialsc.mobdrops.enderman", ModuleManager.MOB_DROPS, MobDropCommand::new);
|
register("mobdrops", "essentialsc.mobdrops.enderman", ModuleManager.MOB_DROPS, MobDropCommand::new);
|
||||||
|
register("maintenance", "essentialsc.command.maintenance", ModuleManager.MAINTENANCE, MaintenanceCommand::new, "maint");
|
||||||
registerSubCommand("admin", "essentialsc.command.admin", ModuleManager.ADMIN_MODE, AdminCommand::new);
|
registerSubCommand("admin", "essentialsc.command.admin", ModuleManager.ADMIN_MODE, AdminCommand::new);
|
||||||
registerSubCommand("skin", "essentialsc.command.skin", ModuleManager.SKIN_BRIDGE, SkinBridgeCommand::new);
|
registerSubCommand("skin", "essentialsc.command.skin", ModuleManager.SKIN_BRIDGE, SkinBridgeCommand::new);
|
||||||
}
|
}
|
||||||
@@ -175,7 +176,8 @@ public final class CommandRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void clearInitializationFailures() {
|
public static void clearCache() {
|
||||||
|
COMMAND_CACHE.clear();
|
||||||
UNAVAILABLE_COMMANDS.clear();
|
UNAVAILABLE_COMMANDS.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.command.CommandSender;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -25,7 +24,7 @@ public class FeedCommand extends BaseCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Player target = Bukkit.getPlayerExact(args[0]);
|
Player target = Bukkit.getPlayer(args[0]);
|
||||||
if (target == null) {
|
if (target == null) {
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||||
return true;
|
return true;
|
||||||
@@ -37,30 +36,6 @@ public class FeedCommand extends BaseCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
|
||||||
if (args.length != 1) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.feed-usage-console"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (!sender.hasPermission("essentialsc.command.feed.others")) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player target = Bukkit.getPlayerExact(args[0]);
|
|
||||||
if (target == null) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
feedPlayer(target);
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.feed-other", Map.of("player", target.getName())));
|
|
||||||
target.sendMessage(getLang().getPrefixedString("messages.feed-by-other",
|
|
||||||
Map.of("admin", getLang().getString("messages.console-name"))));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void feedPlayer(Player player) {
|
private void feedPlayer(Player player) {
|
||||||
player.setFoodLevel(20);
|
player.setFoodLevel(20);
|
||||||
player.setSaturation(20f);
|
player.setSaturation(20f);
|
||||||
|
|||||||
@@ -10,13 +10,15 @@ public class FlyCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
boolean currentFlyState = plugin.getPlayerStateManager().isFlyEnabled(player);
|
boolean currentFlyState = player.getAllowFlight();
|
||||||
|
|
||||||
if (currentFlyState) {
|
if (currentFlyState) {
|
||||||
plugin.getPlayerStateManager().disableFly(player);
|
player.setAllowFlight(false);
|
||||||
|
player.setFlying(false);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.fly-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.fly-disabled"));
|
||||||
} else {
|
} else {
|
||||||
plugin.getPlayerStateManager().enableFly(player);
|
player.setAllowFlight(true);
|
||||||
|
player.setFlying(true);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.fly-enabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.fly-enabled"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
|
||||||
public class GlowCommand extends BaseCommand {
|
public class GlowCommand extends BaseCommand {
|
||||||
|
|
||||||
|
private final NamespacedKey enabledKey;
|
||||||
|
|
||||||
public GlowCommand() {
|
public GlowCommand() {
|
||||||
super("essentialsc.command.glow");
|
super("essentialsc.command.glow");
|
||||||
|
this.enabledKey = new NamespacedKey(plugin, "glow_enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -19,11 +24,15 @@ public class GlowCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (targetState) {
|
if (targetState) {
|
||||||
plugin.getPlayerStateManager().enableGlow(player);
|
player.setGlowing(true);
|
||||||
|
player.getPersistentDataContainer().set(enabledKey, PersistentDataType.BYTE, (byte) 1);
|
||||||
playShortcutSound(player, Sound.BLOCK_AMETHYST_BLOCK_CHIME);
|
playShortcutSound(player, Sound.BLOCK_AMETHYST_BLOCK_CHIME);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.glow-enabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.glow-enabled"));
|
||||||
} else {
|
} else {
|
||||||
plugin.getPlayerStateManager().disableGlow(player);
|
if (currentState) {
|
||||||
|
player.setGlowing(false);
|
||||||
|
player.getPersistentDataContainer().remove(enabledKey);
|
||||||
|
}
|
||||||
playShortcutSound(player, Sound.BLOCK_AMETHYST_CLUSTER_FALL);
|
playShortcutSound(player, Sound.BLOCK_AMETHYST_CLUSTER_FALL);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.glow-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.glow-disabled"));
|
||||||
}
|
}
|
||||||
@@ -44,6 +53,7 @@ public class GlowCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private boolean isPluginGlowEnabled(Player player) {
|
private boolean isPluginGlowEnabled(Player player) {
|
||||||
return plugin.getPlayerStateManager().isGlowEnabled(player);
|
Byte value = player.getPersistentDataContainer().get(enabledKey, PersistentDataType.BYTE);
|
||||||
|
return value != null && value == (byte) 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class GrindstoneCommand extends BaseCommand {
|
public class GrindstoneCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class GrindstoneCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.GRINDSTONE.builder().checkReachable(false).build(player));
|
player.openGrindstone(null, true);
|
||||||
playBlockShortcutSound(player, Material.GRINDSTONE, Sound.BLOCK_GRINDSTONE_USE);
|
playBlockShortcutSound(player, Material.GRINDSTONE, Sound.BLOCK_GRINDSTONE_USE);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.attribute.Attribute;
|
|
||||||
import org.bukkit.attribute.AttributeInstance;
|
|
||||||
import org.bukkit.command.CommandSender;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -27,7 +24,7 @@ public class HealCommand extends BaseCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Player target = Bukkit.getPlayerExact(args[0]);
|
Player target = Bukkit.getPlayer(args[0]);
|
||||||
if (target == null) {
|
if (target == null) {
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||||
return true;
|
return true;
|
||||||
@@ -39,33 +36,8 @@ public class HealCommand extends BaseCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
|
||||||
if (args.length != 1) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.heal-usage-console"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (!sender.hasPermission("essentialsc.command.heal.others")) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission-others"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player target = Bukkit.getPlayerExact(args[0]);
|
|
||||||
if (target == null) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
healPlayer(target);
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.heal-other", Map.of("player", target.getName())));
|
|
||||||
target.sendMessage(getLang().getPrefixedString("messages.heal-by-other",
|
|
||||||
Map.of("admin", getLang().getString("messages.console-name"))));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void healPlayer(Player player) {
|
private void healPlayer(Player player) {
|
||||||
AttributeInstance maxHealth = player.getAttribute(Attribute.MAX_HEALTH);
|
player.setHealth(player.getMaxHealth());
|
||||||
player.setHealth(maxHealth == null ? player.getHealth() : maxHealth.getValue());
|
|
||||||
player.setFoodLevel(20);
|
player.setFoodLevel(20);
|
||||||
player.setSaturation(20f);
|
player.setSaturation(20f);
|
||||||
player.clearActivePotionEffects();
|
player.clearActivePotionEffects();
|
||||||
|
|||||||
@@ -20,17 +20,6 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
super("essentialsc.command.help");
|
super("essentialsc.command.help");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
|
||||||
if (args.length > 0) {
|
|
||||||
if (sender instanceof Player player) {
|
|
||||||
return handleCommand(sender, player, args);
|
|
||||||
}
|
|
||||||
return executeConsole(sender, args);
|
|
||||||
}
|
|
||||||
return super.onCommand(sender, command, label, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
return handleCommand(player, player, args);
|
return handleCommand(player, player, args);
|
||||||
@@ -38,76 +27,24 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||||
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
|
if (args.length > 0 && args[0].equalsIgnoreCase("reload")) {
|
||||||
sendConsoleHelp(sender);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (args[0].equalsIgnoreCase("reload")) {
|
|
||||||
if (!sender.hasPermission("essentialsc.command.reload")) {
|
if (!sender.hasPermission("essentialsc.command.reload")) {
|
||||||
sendNoPermission(sender, "essentialsc.command.reload");
|
sendNoPermission(sender, "essentialsc.command.reload");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
plugin.getFeatureConfigManager().reload();
|
plugin.reloadConfig();
|
||||||
EssentialsC.getLangManager().reload();
|
EssentialsC.getLangManager().reload();
|
||||||
|
plugin.getFeatureConfigManager().reload();
|
||||||
plugin.getModuleManager().reload();
|
plugin.getModuleManager().reload();
|
||||||
CommandRegistry.clearInitializationFailures();
|
CommandRegistry.clearCache();
|
||||||
plugin.reloadRuntimeModules();
|
plugin.reloadRuntimeModules();
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("messages.player-only"));
|
||||||
if (args[0].equalsIgnoreCase("version") || args[0].equalsIgnoreCase("v")) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.version",
|
|
||||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.paper-version",
|
|
||||||
Map.of("version", Bukkit.getVersion())));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
String actualCommand = getActualCommand(args[0]);
|
|
||||||
BaseCommand targetCommand = CommandRegistry.getCommand(actualCommand);
|
|
||||||
if (actualCommand != null && targetCommand != null) {
|
|
||||||
return targetCommand.dispatch(sender, Arrays.copyOfRange(args, 1, args.length));
|
|
||||||
}
|
|
||||||
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.unknown-subcommand",
|
|
||||||
Map.of("command", args[0])));
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.help-usage"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendConsoleHelp(CommandSender sender) {
|
|
||||||
LangManager lang = getLang();
|
|
||||||
sendPrefixed(sender, lang.getString("help.title"));
|
|
||||||
sendPrefixed(sender, lang.getString("help.version",
|
|
||||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
|
||||||
sender.sendMessage("");
|
|
||||||
|
|
||||||
sendPrefixed(sender, lang.getString("help.section-other"));
|
|
||||||
if (sender.hasPermission("essentialsc.command.reload")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.reload"));
|
|
||||||
}
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.version"));
|
|
||||||
if (CommandRegistry.isAvailable("seen") && sender.hasPermission("essentialsc.command.seen")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.seen"));
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("heal") && sender.hasPermission("essentialsc.command.heal")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.heal"));
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("feed") && sender.hasPermission("essentialsc.command.feed")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.feed"));
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("skin") && sender.hasPermission("essentialsc.command.skin")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.skin"));
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("tpsbar") && sender.hasPermission("essentialsc.command.tpsbar")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.tpsbar"));
|
|
||||||
}
|
|
||||||
sender.sendMessage("");
|
|
||||||
sendPrefixed(sender, lang.getString("help.footer"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean handleCommand(CommandSender sender, Player player, String[] args) {
|
private boolean handleCommand(CommandSender sender, Player player, String[] args) {
|
||||||
if (args.length > 0) {
|
if (args.length > 0) {
|
||||||
String subCommand = args[0].toLowerCase();
|
String subCommand = args[0].toLowerCase();
|
||||||
@@ -117,10 +54,11 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
sendNoPermission(sender, "essentialsc.command.reload");
|
sendNoPermission(sender, "essentialsc.command.reload");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
plugin.getFeatureConfigManager().reload();
|
plugin.reloadConfig();
|
||||||
EssentialsC.getLangManager().reload();
|
EssentialsC.getLangManager().reload();
|
||||||
|
plugin.getFeatureConfigManager().reload();
|
||||||
plugin.getModuleManager().reload();
|
plugin.getModuleManager().reload();
|
||||||
CommandRegistry.clearInitializationFailures();
|
CommandRegistry.clearCache();
|
||||||
plugin.reloadRuntimeModules();
|
plugin.reloadRuntimeModules();
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
sender.sendMessage(getLang().getPrefixedString("messages.config-reloaded"));
|
||||||
return true;
|
return true;
|
||||||
@@ -146,7 +84,7 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
if (subCommand.equals("version") || subCommand.equals("v")) {
|
if (subCommand.equals("version") || subCommand.equals("v")) {
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.version",
|
player.sendMessage(getLang().getPrefixedString("messages.version",
|
||||||
Map.of("version", plugin.getPluginMeta().getVersion())));
|
Map.of("version", plugin.getDescription().getVersion())));
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.paper-version",
|
player.sendMessage(getLang().getPrefixedString("messages.paper-version",
|
||||||
Map.of("version", Bukkit.getVersion())));
|
Map.of("version", Bukkit.getVersion())));
|
||||||
return true;
|
return true;
|
||||||
@@ -159,7 +97,7 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
LangManager lang = getLang();
|
LangManager lang = getLang();
|
||||||
String version = plugin.getPluginMeta().getVersion();
|
String version = plugin.getDescription().getVersion();
|
||||||
|
|
||||||
sendPrefixed(player, lang.getString("help.title"));
|
sendPrefixed(player, lang.getString("help.title"));
|
||||||
sendPrefixed(player, lang.getString("help.version", Map.of("version", version)));
|
sendPrefixed(player, lang.getString("help.version", Map.of("version", version)));
|
||||||
@@ -278,6 +216,10 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
otherCommands.append(lang.getString("help.commands.tpsbar")).append("\n");
|
otherCommands.append(lang.getString("help.commands.tpsbar")).append("\n");
|
||||||
hasOtherCommands = true;
|
hasOtherCommands = true;
|
||||||
}
|
}
|
||||||
|
if (CommandRegistry.isAvailable("maintenance") && player.hasPermission("essentialsc.command.maintenance")) {
|
||||||
|
otherCommands.append(lang.getString("help.commands.maintenance")).append("\n");
|
||||||
|
hasOtherCommands = true;
|
||||||
|
}
|
||||||
|
|
||||||
if (hasOtherCommands) {
|
if (hasOtherCommands) {
|
||||||
sendPrefixed(player, lang.getString("help.section-other"));
|
sendPrefixed(player, lang.getString("help.section-other"));
|
||||||
@@ -295,7 +237,7 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void sendPrefixed(CommandSender sender, String message) {
|
private void sendPrefixed(CommandSender sender, String message) {
|
||||||
sender.sendMessage(getLang().getPrefix() + message);
|
sender.sendMessage(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendPrefixedLines(CommandSender sender, String message) {
|
private void sendPrefixedLines(CommandSender sender, String message) {
|
||||||
@@ -359,6 +301,8 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
{"tpignore", "essentialsc.command.tpignore"},
|
{"tpignore", "essentialsc.command.tpignore"},
|
||||||
{"skin", "essentialsc.command.skin"},
|
{"skin", "essentialsc.command.skin"},
|
||||||
{"tpsbar", "essentialsc.command.tpsbar"},
|
{"tpsbar", "essentialsc.command.tpsbar"},
|
||||||
|
{"maintenance", "essentialsc.command.maintenance"},
|
||||||
|
{"maint", "essentialsc.command.maintenance"},
|
||||||
{"mobdrops", "essentialsc.mobdrops.enderman"},
|
{"mobdrops", "essentialsc.mobdrops.enderman"},
|
||||||
{"admin", "essentialsc.command.admin"},
|
{"admin", "essentialsc.command.admin"},
|
||||||
{"version", null},
|
{"version", null},
|
||||||
@@ -441,6 +385,10 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
return players;
|
return players;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ((subCmd.equals("maintenance") || subCmd.equals("maint"))
|
||||||
|
&& sender.hasPermission("essentialsc.command.maintenance")) {
|
||||||
|
return completeMaintenanceArgs(args[1]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args.length == 3 && args[0].equalsIgnoreCase("skin")
|
if (args.length == 3 && args[0].equalsIgnoreCase("skin")
|
||||||
@@ -485,4 +433,14 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
return completions;
|
return completions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<String> completeMaintenanceArgs(String partialInput) {
|
||||||
|
List<String> completions = new ArrayList<>();
|
||||||
|
String partial = partialInput.toLowerCase();
|
||||||
|
for (String option : List.of("on", "off", "status", "reload", "add", "remove", "list")) {
|
||||||
|
if (option.startsWith(partial)) {
|
||||||
|
completions.add(option);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return completions;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class LoomCommand extends BaseCommand {
|
public class LoomCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class LoomCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.LOOM.builder().checkReachable(false).build(player));
|
player.openLoom(null, true);
|
||||||
playBlockShortcutSound(player, Material.LOOM, Sound.UI_LOOM_SELECT_PATTERN);
|
playBlockShortcutSound(player, Material.LOOM, Sound.UI_LOOM_SELECT_PATTERN);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.maintenance.MaintenanceManager;
|
||||||
|
import org.bukkit.command.Command;
|
||||||
|
import org.bukkit.command.CommandSender;
|
||||||
|
import org.bukkit.command.TabCompleter;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MaintenanceCommand extends BaseCommand implements TabCompleter {
|
||||||
|
|
||||||
|
public MaintenanceCommand() {
|
||||||
|
super("essentialsc.command.maintenance");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean execute(Player player, String[] args) {
|
||||||
|
return executeCommand(player, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||||
|
return executeCommand(sender, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean executeCommand(CommandSender sender, String[] args) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (maintenanceManager == null) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.length == 0 || args[0].equalsIgnoreCase("status")) {
|
||||||
|
sendStatus(sender, maintenanceManager);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (args[0].toLowerCase(Locale.ROOT)) {
|
||||||
|
case "on", "enable", "enabled" -> {
|
||||||
|
maintenanceManager.setEnabled(true);
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.enabled"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case "off", "disable", "disabled" -> {
|
||||||
|
maintenanceManager.setEnabled(false);
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.disabled"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case "reload" -> {
|
||||||
|
maintenanceManager.reload();
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.reloaded"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case "add" -> {
|
||||||
|
if (args.length < 2) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.add-usage"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
String target = args[1];
|
||||||
|
if (maintenanceManager.addWhitelistEntry(target)) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-added",
|
||||||
|
Map.of("player", target)));
|
||||||
|
} else {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-exists",
|
||||||
|
Map.of("player", target)));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case "remove" -> {
|
||||||
|
if (args.length < 2) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.remove-usage"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
String target = args[1];
|
||||||
|
if (maintenanceManager.removeWhitelistEntry(target)) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-removed",
|
||||||
|
Map.of("player", target)));
|
||||||
|
} else {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-missing",
|
||||||
|
Map.of("player", target)));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case "list" -> {
|
||||||
|
sendWhitelist(sender, maintenanceManager);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.usage"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendStatus(CommandSender sender, MaintenanceManager maintenanceManager) {
|
||||||
|
String status = getLang().getString(maintenanceManager.isEnabled()
|
||||||
|
? "maintenance.status.enabled"
|
||||||
|
: "maintenance.status.disabled");
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.status",
|
||||||
|
Map.of(
|
||||||
|
"status", status,
|
||||||
|
"whitelist_count", String.valueOf(maintenanceManager.getWhitelistCount())
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendWhitelist(CommandSender sender, MaintenanceManager maintenanceManager) {
|
||||||
|
List<String> entries = maintenanceManager.getWhitelistEntries();
|
||||||
|
if (entries.isEmpty()) {
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-empty"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-list",
|
||||||
|
Map.of(
|
||||||
|
"count", String.valueOf(entries.size()),
|
||||||
|
"entries", String.join(", ", entries)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||||
|
if (!sender.hasPermission(getPermission())) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.length == 1) {
|
||||||
|
return complete(args[0], List.of("on", "off", "status", "reload", "add", "remove", "list"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.length == 2 && args[0].equalsIgnoreCase("add")) {
|
||||||
|
return complete(args[1], plugin.getServer().getOnlinePlayers().stream()
|
||||||
|
.map(Player::getName)
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.length == 2 && args[0].equalsIgnoreCase("remove")) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (maintenanceManager == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return complete(args[1], maintenanceManager.getWhitelistEntries());
|
||||||
|
}
|
||||||
|
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> complete(String input, List<String> options) {
|
||||||
|
String partial = input.toLowerCase(Locale.ROOT);
|
||||||
|
List<String> completions = new ArrayList<>();
|
||||||
|
for (String option : options) {
|
||||||
|
if (option.toLowerCase(Locale.ROOT).startsWith(partial)) {
|
||||||
|
completions.add(option);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return completions;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,8 +8,6 @@ import org.bukkit.inventory.Inventory;
|
|||||||
import org.bukkit.inventory.InventoryHolder;
|
import org.bukkit.inventory.InventoryHolder;
|
||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
import org.bukkit.inventory.meta.ItemMeta;
|
import org.bukkit.inventory.meta.ItemMeta;
|
||||||
import net.kyori.adventure.text.Component;
|
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -22,7 +20,7 @@ public class MobDropCommand extends BaseCommand {
|
|||||||
public static final class MobDropMenuHolder implements InventoryHolder {
|
public static final class MobDropMenuHolder implements InventoryHolder {
|
||||||
private final Inventory inventory;
|
private final Inventory inventory;
|
||||||
|
|
||||||
public MobDropMenuHolder(Component title) {
|
public MobDropMenuHolder(String title) {
|
||||||
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
this.inventory = Bukkit.createInventory(this, MENU_SIZE, title);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,17 +47,17 @@ public class MobDropCommand extends BaseCommand {
|
|||||||
? "mobdrops-menu.status.enabled"
|
? "mobdrops-menu.status.enabled"
|
||||||
: "mobdrops-menu.status.disabled");
|
: "mobdrops-menu.status.disabled");
|
||||||
|
|
||||||
Inventory menu = new MobDropMenuHolder(lang.getComponent("mobdrops-menu.title")).getInventory();
|
Inventory menu = new MobDropMenuHolder(lang.getString("mobdrops-menu.title")).getInventory();
|
||||||
|
|
||||||
ItemStack endermanItem = new ItemStack(Material.ENDER_PEARL);
|
ItemStack endermanItem = new ItemStack(Material.ENDER_PEARL);
|
||||||
ItemMeta endermanMeta = endermanItem.getItemMeta();
|
ItemMeta endermanMeta = endermanItem.getItemMeta();
|
||||||
if (endermanMeta != null) {
|
if (endermanMeta != null) {
|
||||||
endermanMeta.displayName(legacyComponent(lang.getString("mobdrops-menu.enderman.name")));
|
endermanMeta.setDisplayName(lang.getString("mobdrops-menu.enderman.name"));
|
||||||
endermanMeta.lore(List.of(
|
endermanMeta.setLore(List.of(
|
||||||
lang.getString("mobdrops-menu.enderman.status", Map.of("status", status)),
|
lang.getString("mobdrops-menu.enderman.status", Map.of("status", status)),
|
||||||
"",
|
"",
|
||||||
lang.getString("mobdrops-menu.enderman.toggle")
|
lang.getString("mobdrops-menu.enderman.toggle")
|
||||||
).stream().map(MobDropCommand::legacyComponent).toList());
|
));
|
||||||
endermanItem.setItemMeta(endermanMeta);
|
endermanItem.setItemMeta(endermanMeta);
|
||||||
}
|
}
|
||||||
menu.setItem(ENDERMAN_SLOT, endermanItem);
|
menu.setItem(ENDERMAN_SLOT, endermanItem);
|
||||||
@@ -67,7 +65,7 @@ public class MobDropCommand extends BaseCommand {
|
|||||||
ItemStack glass = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
|
ItemStack glass = new ItemStack(Material.BLACK_STAINED_GLASS_PANE);
|
||||||
ItemMeta glassMeta = glass.getItemMeta();
|
ItemMeta glassMeta = glass.getItemMeta();
|
||||||
if (glassMeta != null) {
|
if (glassMeta != null) {
|
||||||
glassMeta.displayName(Component.text(" "));
|
glassMeta.setDisplayName(" ");
|
||||||
glass.setItemMeta(glassMeta);
|
glass.setItemMeta(glassMeta);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,10 +82,6 @@ public class MobDropCommand extends BaseCommand {
|
|||||||
return ENDERMAN_SLOT;
|
return ENDERMAN_SLOT;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Component legacyComponent(String text) {
|
|
||||||
return LegacyComponentSerializer.legacySection().deserialize(text == null ? "" : text);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void openMobDropMenu(Player player) {
|
private void openMobDropMenu(Player player) {
|
||||||
openMobDropMenu(plugin, player);
|
openMobDropMenu(plugin, player);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.potion.PotionEffect;
|
||||||
|
import org.bukkit.potion.PotionEffectType;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
|
||||||
public class NightVisionCommand extends BaseCommand {
|
public class NightVisionCommand extends BaseCommand {
|
||||||
|
|
||||||
|
private final NamespacedKey enabledKey;
|
||||||
|
|
||||||
public NightVisionCommand() {
|
public NightVisionCommand() {
|
||||||
super("essentialsc.command.nightvision");
|
super("essentialsc.command.nightvision");
|
||||||
|
this.enabledKey = new NamespacedKey(plugin, "nightvision_enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -19,11 +26,15 @@ public class NightVisionCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (targetState) {
|
if (targetState) {
|
||||||
plugin.getPlayerStateManager().enableNightVision(player);
|
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false, false));
|
||||||
|
player.getPersistentDataContainer().set(enabledKey, PersistentDataType.BYTE, (byte) 1);
|
||||||
playShortcutSound(player, Sound.BLOCK_BEACON_POWER_SELECT);
|
playShortcutSound(player, Sound.BLOCK_BEACON_POWER_SELECT);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.nightvision-enabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.nightvision-enabled"));
|
||||||
} else {
|
} else {
|
||||||
plugin.getPlayerStateManager().disableNightVision(player);
|
if (currentState) {
|
||||||
|
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
|
||||||
|
player.getPersistentDataContainer().remove(enabledKey);
|
||||||
|
}
|
||||||
playShortcutSound(player, Sound.BLOCK_BEACON_DEACTIVATE);
|
playShortcutSound(player, Sound.BLOCK_BEACON_DEACTIVATE);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.nightvision-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.nightvision-disabled"));
|
||||||
}
|
}
|
||||||
@@ -44,6 +55,7 @@ public class NightVisionCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private boolean isPluginNightVisionEnabled(Player player) {
|
private boolean isPluginNightVisionEnabled(Player player) {
|
||||||
return plugin.getPlayerStateManager().isNightVisionEnabled(player);
|
Byte value = player.getPersistentDataContainer().get(enabledKey, PersistentDataType.BYTE);
|
||||||
|
return value != null && value == (byte) 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.OfflinePlayer;
|
import org.bukkit.OfflinePlayer;
|
||||||
import org.bukkit.command.CommandSender;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
@@ -17,56 +16,38 @@ public class SeenCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
return executeCommand(player, player, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
|
||||||
return executeCommand(sender, null, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean executeCommand(CommandSender sender, Player viewer, String[] args) {
|
|
||||||
if (args.length == 0) {
|
if (args.length == 0) {
|
||||||
sender.sendMessage(getLang().getPrefixedString(viewer == null
|
player.sendMessage(getLang().getPrefixedString("messages.seen-usage"));
|
||||||
? "messages.seen-usage-console"
|
|
||||||
: "messages.seen-usage"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player onlineTarget = Bukkit.getPlayerExact(args[0]);
|
|
||||||
if (onlineTarget != null && VanishCommand.isVanished(onlineTarget)
|
|
||||||
&& viewer != null && !viewer.hasPermission(VanishCommand.SEE_PERMISSION)) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]);
|
OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]);
|
||||||
if (!target.hasPlayedBefore() && !target.isOnline()) {
|
if (!target.hasPlayedBefore() && !target.isOnline()) {
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
sender.sendMessage(getLang().getPrefixedComponent("messages.seen-header",
|
player.sendMessage(getLang().getPrefixedComponent("messages.seen-header",
|
||||||
Map.of("player", String.valueOf(target.getName()))));
|
Map.of("player", String.valueOf(target.getName()))));
|
||||||
|
|
||||||
if (target.isOnline()) {
|
if (target.isOnline()) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-status-online"));
|
player.sendMessage(getLang().getComponent("messages.seen-status-online"));
|
||||||
Player onlinePlayer = target.getPlayer();
|
Player onlinePlayer = target.getPlayer();
|
||||||
if (onlinePlayer != null) {
|
if (onlinePlayer != null) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-world",
|
player.sendMessage(getLang().getComponent("messages.seen-world",
|
||||||
Map.of("world", onlinePlayer.getWorld().getName())));
|
Map.of("world", onlinePlayer.getWorld().getName())));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-status-offline"));
|
player.sendMessage(getLang().getComponent("messages.seen-status-offline"));
|
||||||
long lastSeen = target.getLastSeen();
|
long lastSeen = target.getLastSeen();
|
||||||
if (lastSeen > 0) {
|
if (lastSeen > 0) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-last-online",
|
player.sendMessage(getLang().getComponent("messages.seen-last-online",
|
||||||
Map.of("time", format.format(new Date(lastSeen)))));
|
Map.of("time", format.format(new Date(lastSeen)))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-first-joined",
|
player.sendMessage(getLang().getComponent("messages.seen-first-joined",
|
||||||
Map.of("time", format.format(new Date(target.getFirstPlayed())))));
|
Map.of("time", format.format(new Date(target.getFirstPlayed())))));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class SmithingTableCommand extends BaseCommand {
|
public class SmithingTableCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class SmithingTableCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.SMITHING.builder().checkReachable(false).build(player));
|
player.openSmithingTable(null, true);
|
||||||
playBlockShortcutSound(player, Material.SMITHING_TABLE, Sound.BLOCK_SMITHING_TABLE_USE);
|
playBlockShortcutSound(player, Material.SMITHING_TABLE, Sound.BLOCK_SMITHING_TABLE_USE);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class StonecutterCommand extends BaseCommand {
|
public class StonecutterCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class StonecutterCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.STONECUTTER.builder().checkReachable(false).build(player));
|
player.openStonecutter(null, true);
|
||||||
playBlockShortcutSound(player, Material.STONECUTTER, Sound.UI_STONECUTTER_SELECT_RECIPE);
|
playBlockShortcutSound(player, Material.STONECUTTER, Sound.UI_STONECUTTER_SELECT_RECIPE);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,13 +17,10 @@ public final class TpIgnoreCommand extends BaseCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager.ToggleIgnoreResult result = manager.toggleIgnoringRequests(player);
|
boolean ignoring = manager.toggleIgnoringRequests(player);
|
||||||
String messagePath = switch (result) {
|
player.sendMessage(getLang().getPrefixedComponent(ignoring
|
||||||
case ENABLED -> "tpa.messages.ignore-enabled";
|
? "tpa.messages.ignore-enabled"
|
||||||
case DISABLED -> "tpa.messages.ignore-disabled";
|
: "tpa.messages.ignore-disabled"));
|
||||||
case SAVE_FAILED -> "tpa.messages.ignore-save-failed";
|
|
||||||
};
|
|
||||||
player.sendMessage(getLang().getPrefixedComponent(messagePath));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,37 +63,17 @@ public class TpsBarCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
protected boolean executeConsole(CommandSender sender, String[] args) {
|
||||||
TpsBarService tpsBarService = plugin.getTpsBarManager();
|
sender.sendMessage(getLang().getPrefixedString("messages.player-only"));
|
||||||
if (tpsBarService == null) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (args.length != 1) {
|
|
||||||
sender.sendMessage(tpsBarService.getUsageMessage());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (!sender.hasPermission("essentialsc.command.tpsbar.others")) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission",
|
|
||||||
Map.of("permission", "essentialsc.command.tpsbar.others")));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player target = Bukkit.getPlayerExact(args[0]);
|
|
||||||
if (target == null) {
|
|
||||||
sender.sendMessage(tpsBarService.getPlayerNotFoundMessage(args[0]));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean enabled = tpsBarService.toggle(target);
|
|
||||||
sender.sendMessage(getLang().getPrefixedString(enabled
|
|
||||||
? "tpsbar.messages.enabled-other"
|
|
||||||
: "tpsbar.messages.disabled-other", Map.of("player", target.getName())));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||||
if (args.length != 1 || !sender.hasPermission("essentialsc.command.tpsbar.others")) {
|
if (args.length != 1 || !(sender instanceof Player player)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!player.hasPermission("essentialsc.command.tpsbar.others")) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,10 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -29,23 +27,14 @@ public class VanishCommand extends BaseCommand {
|
|||||||
|
|
||||||
if (vanishedPlayers.contains(uuid)) {
|
if (vanishedPlayers.contains(uuid)) {
|
||||||
vanishedPlayers.remove(uuid);
|
vanishedPlayers.remove(uuid);
|
||||||
if (!saveState(plugin)) {
|
|
||||||
vanishedPlayers.add(uuid);
|
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-save-failed"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
showPlayerToAll(plugin, player);
|
showPlayerToAll(plugin, player);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.vanish-disabled"));
|
||||||
} else {
|
} else {
|
||||||
vanishedPlayers.add(uuid);
|
vanishedPlayers.add(uuid);
|
||||||
if (!saveState(plugin)) {
|
|
||||||
vanishedPlayers.remove(uuid);
|
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-save-failed"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
hidePlayerFromAll(plugin, player);
|
hidePlayerFromAll(plugin, player);
|
||||||
player.sendMessage(getLang().getPrefixedString("messages.vanish-enabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.vanish-enabled"));
|
||||||
}
|
}
|
||||||
|
saveState(plugin);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,13 +44,7 @@ public class VanishCommand extends BaseCommand {
|
|||||||
if (!stateFile.exists()) {
|
if (!stateFile.exists()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
YamlConfiguration state = new YamlConfiguration();
|
FileConfiguration state = YamlConfiguration.loadConfiguration(stateFile);
|
||||||
try {
|
|
||||||
state.load(stateFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
plugin.getLogger().severe("加载 vanished-players.yml 失败: " + exception.getMessage());
|
|
||||||
throw new IllegalStateException("无法加载 vanished-players.yml,请修复文件格式后重试。", exception);
|
|
||||||
}
|
|
||||||
for (String value : state.getStringList("players")) {
|
for (String value : state.getStringList("players")) {
|
||||||
try {
|
try {
|
||||||
vanishedPlayers.add(UUID.fromString(value));
|
vanishedPlayers.add(UUID.fromString(value));
|
||||||
@@ -82,22 +65,15 @@ public class VanishCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean restoreVisibility(EssentialsC plugin, Player player, boolean notify) {
|
public static void restoreVisibility(EssentialsC plugin, Player player, boolean notify) {
|
||||||
if (!vanishedPlayers.remove(player.getUniqueId())) {
|
if (!vanishedPlayers.remove(player.getUniqueId())) {
|
||||||
return true;
|
return;
|
||||||
}
|
|
||||||
if (!saveState(plugin)) {
|
|
||||||
vanishedPlayers.add(player.getUniqueId());
|
|
||||||
if (notify) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-save-failed"));
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
showPlayerToAll(plugin, player);
|
showPlayerToAll(plugin, player);
|
||||||
|
saveState(plugin);
|
||||||
if (notify) {
|
if (notify) {
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-permission-removed"));
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-permission-removed"));
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void applyHiddenState(EssentialsC plugin, Player player) {
|
public static void applyHiddenState(EssentialsC plugin, Player player) {
|
||||||
@@ -135,7 +111,7 @@ public class VanishCommand extends BaseCommand {
|
|||||||
return vanishedPlayers.contains(player.getUniqueId());
|
return vanishedPlayers.contains(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean saveState(EssentialsC plugin) {
|
private static void saveState(EssentialsC plugin) {
|
||||||
if (stateFile == null) {
|
if (stateFile == null) {
|
||||||
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
||||||
}
|
}
|
||||||
@@ -143,10 +119,8 @@ public class VanishCommand extends BaseCommand {
|
|||||||
state.set("players", vanishedPlayers.stream().map(UUID::toString).sorted().toList());
|
state.set("players", vanishedPlayers.stream().map(UUID::toString).sorted().toList());
|
||||||
try {
|
try {
|
||||||
AtomicYamlWriter.save(state, stateFile);
|
AtomicYamlWriter.save(state, stateFile);
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
plugin.getLogger().warning("保存 vanished-players.yml 失败: " + exception.getMessage());
|
plugin.getLogger().warning("保存 vanished-players.yml 失败: " + exception.getMessage());
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.inventory.MenuType;
|
|
||||||
|
|
||||||
public class WorkbenchCommand extends BaseCommand {
|
public class WorkbenchCommand extends BaseCommand {
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ public class WorkbenchCommand extends BaseCommand {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
player.openInventory(MenuType.CRAFTING.builder().checkReachable(false).build(player));
|
player.openWorkbench(null, true);
|
||||||
playBlockShortcutSound(player, Material.CRAFTING_TABLE, Sound.UI_BUTTON_CLICK);
|
playBlockShortcutSound(player, Material.CRAFTING_TABLE, Sound.UI_BUTTON_CLICK);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package cn.infstar.essentialsC.listeners;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.event.EventHandler;
|
||||||
|
import org.bukkit.event.Listener;
|
||||||
|
import org.bukkit.event.player.PlayerJoinEvent;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为 Fabric / NeoForge 客户端补发配方同步数据,修复 1.21.2+ 的 JEI 配方显示问题。
|
||||||
|
*/
|
||||||
|
public class JeiRecipeSyncListener implements Listener {
|
||||||
|
|
||||||
|
private static final Set<String> WARNED_UNSUPPORTED_VERSIONS = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
|
private final EssentialsC plugin;
|
||||||
|
private final boolean debug;
|
||||||
|
private final boolean sendPlayerMessage;
|
||||||
|
private final int brandCheckDelayTicks;
|
||||||
|
private final JeiRecipeSyncAdapter adapter;
|
||||||
|
|
||||||
|
public JeiRecipeSyncListener(EssentialsC plugin) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
|
||||||
|
FileConfiguration config = plugin.getConfig();
|
||||||
|
config.addDefault("jei-sync.brand-check-delay-ticks", 20);
|
||||||
|
config.options().copyDefaults(true);
|
||||||
|
|
||||||
|
this.debug = config.getBoolean("debug", false);
|
||||||
|
this.sendPlayerMessage = config.getBoolean("jei-sync.send-player-message", true);
|
||||||
|
this.brandCheckDelayTicks = Math.max(0, config.getInt("jei-sync.brand-check-delay-ticks", 20));
|
||||||
|
this.adapter = loadAdapter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
|
if (adapter == null) {
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().warning("当前服务端版本没有可用的 JEI 配方同步适配器。");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Player player = event.getPlayer();
|
||||||
|
plugin.getServer().getScheduler().runTaskLater(plugin, () -> detectAndSync(player), brandCheckDelayTicks);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void detectAndSync(Player player) {
|
||||||
|
if (!player.isOnline()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String clientBrand = player.getClientBrandName();
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("JEI 客户端检测: player=" + player.getName()
|
||||||
|
+ ", brand=" + (clientBrand == null || clientBrand.isBlank() ? "unknown" : clientBrand)
|
||||||
|
+ ", delayTicks=" + brandCheckDelayTicks);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientBrand == null || clientBrand.isEmpty()) {
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("跳过 " + player.getName() + ":客户端品牌为空");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String brandLower = clientBrand.toLowerCase(Locale.ROOT);
|
||||||
|
if (brandLower.contains("fabric")) {
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("检测到 Fabric 客户端,开始发送配方同步...");
|
||||||
|
}
|
||||||
|
sendPlayerMessage(player, "Fabric");
|
||||||
|
sendFabricRecipeSync(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (brandLower.contains("neoforge") || brandLower.contains("forge")) {
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("检测到 NeoForge/Forge 客户端,开始发送配方同步...");
|
||||||
|
}
|
||||||
|
sendPlayerMessage(player, "NeoForge");
|
||||||
|
sendNeoForgeRecipeSync(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("跳过 " + player.getName() + ":不支持的客户端类型 '" + clientBrand + "'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendPlayerMessage(Player player, String clientType) {
|
||||||
|
if (!sendPlayerMessage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String messageKey;
|
||||||
|
if (clientType.equalsIgnoreCase("fabric")) {
|
||||||
|
messageKey = "messages.jei-sync-fabric";
|
||||||
|
} else if (clientType.equalsIgnoreCase("neoforge")) {
|
||||||
|
messageKey = "messages.jei-sync-neoforge";
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedComponent(messageKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendFabricRecipeSync(Player player) {
|
||||||
|
try {
|
||||||
|
adapter.sendFabricRecipeSync(player, plugin.getLogger(), debug);
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("发送 Fabric 配方同步失败: " + e.getMessage());
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().log(Level.WARNING, "Fabric 配方同步异常详情", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendNeoForgeRecipeSync(Player player) {
|
||||||
|
try {
|
||||||
|
adapter.sendNeoForgeRecipeSync(player, plugin.getLogger(), debug);
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("发送 NeoForge 配方同步失败: " + e.getMessage());
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().log(Level.WARNING, "NeoForge 配方同步异常详情", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JeiRecipeSyncAdapter loadAdapter() {
|
||||||
|
String versionKey = plugin.getServer().getBukkitVersion().split("-")[0]
|
||||||
|
.replace('.', '_');
|
||||||
|
String className = "cn.infstar.essentialsC.v" + versionKey + ".jei.JeiRecipeSyncAdapterImpl";
|
||||||
|
try {
|
||||||
|
Class<?> adapterClass = Class.forName(className);
|
||||||
|
Object instance = adapterClass.getDeclaredConstructor().newInstance();
|
||||||
|
if (instance instanceof JeiRecipeSyncAdapter jeiRecipeSyncAdapter) {
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().info("已加载 JEI 配方同步适配器: " + className);
|
||||||
|
}
|
||||||
|
return jeiRecipeSyncAdapter;
|
||||||
|
}
|
||||||
|
plugin.getLogger().warning("JEI 配方同步适配器类型无效: " + className);
|
||||||
|
} catch (ReflectiveOperationException | LinkageError e) {
|
||||||
|
if (WARNED_UNSUPPORTED_VERSIONS.add(versionKey)) {
|
||||||
|
plugin.getLogger().warning("当前 Paper 版本 " + plugin.getServer().getBukkitVersion()
|
||||||
|
+ " 没有可用的 JEI 配方同步适配器;仅 JEI 同步功能已停用。");
|
||||||
|
}
|
||||||
|
if (debug) {
|
||||||
|
plugin.getLogger().warning("加载 JEI 配方同步适配器失败: " + className + " (" + e.getMessage() + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package cn.infstar.essentialsC.listeners;
|
|||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.commands.MobDropCommand;
|
import cn.infstar.essentialsC.commands.MobDropCommand;
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
@@ -18,6 +19,7 @@ public class MobDropMenuListener implements Listener {
|
|||||||
|
|
||||||
public MobDropMenuListener(EssentialsC plugin) {
|
public MobDropMenuListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
@@ -38,12 +40,6 @@ public class MobDropMenuListener implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.getRawSlot() == MobDropCommand.getEndermanSlot()) {
|
if (event.getRawSlot() == MobDropCommand.getEndermanSlot()) {
|
||||||
if (!player.hasPermission("essentialsc.mobdrops.enderman")) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.no-permission",
|
|
||||||
Map.of("permission", "essentialsc.mobdrops.enderman")));
|
|
||||||
player.closeInventory();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
toggleEndermanDrops(player);
|
toggleEndermanDrops(player);
|
||||||
Bukkit.getScheduler().runTaskLater(plugin, () -> MobDropCommand.openMobDropMenu(plugin, player), 2L);
|
Bukkit.getScheduler().runTaskLater(plugin, () -> MobDropCommand.openMobDropMenu(plugin, player), 2L);
|
||||||
}
|
}
|
||||||
@@ -52,10 +48,13 @@ public class MobDropMenuListener implements Listener {
|
|||||||
private void toggleEndermanDrops(Player player) {
|
private void toggleEndermanDrops(Player player) {
|
||||||
FileConfiguration config = plugin.getConfig();
|
FileConfiguration config = plugin.getConfig();
|
||||||
boolean newValue = !config.getBoolean("mob-drops.enderman.allow-drops", true);
|
boolean newValue = !config.getBoolean("mob-drops.enderman.allow-drops", true);
|
||||||
if (!plugin.getFeatureConfigManager().updateMainConfigValue(
|
config.set("mob-drops.enderman.allow-drops", newValue);
|
||||||
"mob-drops.enderman.allow-drops", newValue)) {
|
|
||||||
|
try {
|
||||||
|
AtomicYamlWriter.save(config, plugin.getDataFolder().toPath().resolve("config.yml").toFile());
|
||||||
|
} catch (Exception e) {
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.mobdrop-save-failed",
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.mobdrop-save-failed",
|
||||||
Map.of("error", "无法写入 config.yml")));
|
Map.of("error", e.getMessage())));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
package cn.infstar.essentialsC.listeners;
|
package cn.infstar.essentialsC.listeners;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import net.kyori.adventure.text.Component;
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.NamespacedKey;
|
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.block.ShulkerBox;
|
import org.bukkit.block.ShulkerBox;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
@@ -12,18 +10,13 @@ import org.bukkit.event.EventHandler;
|
|||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.block.Action;
|
import org.bukkit.event.block.Action;
|
||||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
|
||||||
import org.bukkit.event.inventory.ClickType;
|
import org.bukkit.event.inventory.ClickType;
|
||||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||||
import org.bukkit.event.inventory.InventoryType;
|
|
||||||
import org.bukkit.event.player.PlayerDropItemEvent;
|
|
||||||
import org.bukkit.event.player.PlayerInteractEvent;
|
import org.bukkit.event.player.PlayerInteractEvent;
|
||||||
import org.bukkit.event.player.PlayerJoinEvent;
|
|
||||||
import org.bukkit.event.player.PlayerKickEvent;
|
import org.bukkit.event.player.PlayerKickEvent;
|
||||||
import org.bukkit.event.player.PlayerQuitEvent;
|
import org.bukkit.event.player.PlayerQuitEvent;
|
||||||
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
|
|
||||||
import org.bukkit.event.server.PluginDisableEvent;
|
import org.bukkit.event.server.PluginDisableEvent;
|
||||||
import org.bukkit.inventory.EquipmentSlot;
|
import org.bukkit.inventory.EquipmentSlot;
|
||||||
import org.bukkit.inventory.Inventory;
|
import org.bukkit.inventory.Inventory;
|
||||||
@@ -33,20 +26,18 @@ import org.bukkit.inventory.ItemStack;
|
|||||||
import org.bukkit.inventory.PlayerInventory;
|
import org.bukkit.inventory.PlayerInventory;
|
||||||
import org.bukkit.inventory.meta.BlockStateMeta;
|
import org.bukkit.inventory.meta.BlockStateMeta;
|
||||||
import org.bukkit.inventory.meta.ItemMeta;
|
import org.bukkit.inventory.meta.ItemMeta;
|
||||||
import org.bukkit.persistence.PersistentDataType;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class ShulkerBoxListener implements Listener {
|
public class ShulkerBoxListener implements Listener {
|
||||||
|
|
||||||
private static final int SHULKER_SIZE = 27;
|
private static final int SHULKER_SIZE = 27;
|
||||||
private static final int OFF_HAND_SLOT = 40;
|
|
||||||
|
|
||||||
private static final Set<Material> SHULKER_BOX_MATERIALS = Set.of(
|
private static final Set<Material> SHULKER_BOX_MATERIALS = Set.of(
|
||||||
Material.SHULKER_BOX,
|
Material.SHULKER_BOX,
|
||||||
@@ -69,44 +60,35 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
);
|
);
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final NamespacedKey sessionKey;
|
|
||||||
private final Map<UUID, OpenShulkerSession> openShulkerBoxes = new HashMap<>();
|
private final Map<UUID, OpenShulkerSession> openShulkerBoxes = new HashMap<>();
|
||||||
|
|
||||||
private static final class ShulkerBoxHolder implements InventoryHolder {
|
private static final class ShulkerBoxHolder implements InventoryHolder {
|
||||||
private final Inventory inventory;
|
private final Inventory inventory;
|
||||||
|
|
||||||
private ShulkerBoxHolder(Component title) {
|
private ShulkerBoxHolder(Component title) {
|
||||||
this.inventory = Bukkit.createInventory(this, InventoryType.SHULKER_BOX, title);
|
this.inventory = Bukkit.createInventory(this, SHULKER_SIZE, title);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Inventory getInventory() {
|
public Inventory getInventory() {
|
||||||
return inventory;
|
return this.inventory;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class OpenShulkerSession {
|
private static final class OpenShulkerSession {
|
||||||
private final String token;
|
private final ItemStack sourceItem;
|
||||||
private final Inventory inventory;
|
private final EquipmentSlot sourceHand;
|
||||||
private final int preferredSlot;
|
private final int preferredSlot;
|
||||||
private boolean syncScheduled;
|
|
||||||
|
|
||||||
private OpenShulkerSession(String token, Inventory inventory, int preferredSlot) {
|
private OpenShulkerSession(ItemStack sourceItem, EquipmentSlot sourceHand, int preferredSlot) {
|
||||||
this.token = token;
|
this.sourceItem = sourceItem;
|
||||||
this.inventory = inventory;
|
this.sourceHand = sourceHand;
|
||||||
this.preferredSlot = preferredSlot;
|
this.preferredSlot = preferredSlot;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record LocatedSource(ItemStack item, Consumer<ItemStack> save) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public ShulkerBoxListener(EssentialsC plugin) {
|
public ShulkerBoxListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.sessionKey = new NamespacedKey(plugin, "open_shulker_session");
|
|
||||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
|
||||||
clearStaleSessionTokens(player);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
@EventHandler(priority = EventPriority.HIGHEST)
|
||||||
@@ -120,10 +102,6 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.useItemInHand() == org.bukkit.event.Event.Result.DENY) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (openShulkerBoxes.containsKey(player.getUniqueId())) {
|
if (openShulkerBoxes.containsKey(player.getUniqueId())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -133,15 +111,21 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
if (!isShulkerBox(sourceItem)) {
|
if (!isShulkerBox(sourceItem)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
|
|
||||||
event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
|
|
||||||
|
|
||||||
if (sourceItem.getAmount() != 1) {
|
if (sourceItem.getAmount() != 1) {
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-unstack-first"));
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-unstack-first"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!(sourceItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
|
||||||
|
event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
|
||||||
|
|
||||||
ItemStack sourceSnapshot = sourceItem.clone();
|
ItemStack sourceSnapshot = sourceItem.clone();
|
||||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
||||||
if (!player.isOnline() || openShulkerBoxes.containsKey(player.getUniqueId())) {
|
if (!player.isOnline() || openShulkerBoxes.containsKey(player.getUniqueId())) {
|
||||||
@@ -153,7 +137,7 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
openShulkerBox(player, hand, currentItem);
|
openShulkerBox(player, hand, sourceSnapshot, shulkerBox);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,33 +147,14 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
InventoryView view = event.getView();
|
||||||
if (session == null || event.getView().getTopInventory() != session.inventory) {
|
Inventory topInventory = view.getTopInventory();
|
||||||
|
if (!(topInventory.getHolder(false) instanceof ShulkerBoxHolder)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasSessionToken(event.getCurrentItem(), session.token)
|
int topSize = topInventory.getSize();
|
||||||
|| hasSessionToken(event.getCursor(), session.token)) {
|
boolean clickTopInventory = event.getRawSlot() >= 0 && event.getRawSlot() < topSize;
|
||||||
event.setCancelled(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.getClick() == ClickType.NUMBER_KEY) {
|
|
||||||
ItemStack hotbarItem = player.getInventory().getItem(event.getHotbarButton());
|
|
||||||
if (hasSessionToken(hotbarItem, session.token)) {
|
|
||||||
event.setCancelled(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.getClick() == ClickType.SWAP_OFFHAND
|
|
||||||
&& hasSessionToken(player.getInventory().getItemInOffHand(), session.token)) {
|
|
||||||
event.setCancelled(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
int topSize = session.inventory.getSize();
|
|
||||||
boolean clickTopInventory = ShulkerBoxSessionPolicy.isTopSlot(event.getRawSlot(), topSize);
|
|
||||||
|
|
||||||
if (clickTopInventory && isShulkerBox(event.getCursor())) {
|
if (clickTopInventory && isShulkerBox(event.getCursor())) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
@@ -206,46 +171,43 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (clickTopInventory && event.getClick() == ClickType.SWAP_OFFHAND
|
if (clickTopInventory && event.getClick() == ClickType.SWAP_OFFHAND) {
|
||||||
&& isShulkerBox(player.getInventory().getItemInOffHand())) {
|
ItemStack offHandItem = player.getInventory().getItemInOffHand();
|
||||||
|
if (isShulkerBox(offHandItem)) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
sendNestedMessage(player);
|
sendNestedMessage(player);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (event.isShiftClick() && isShulkerBox(event.getCurrentItem())) {
|
if (event.isShiftClick() && isShulkerBox(event.getCurrentItem())) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
sendNestedMessage(player);
|
sendNestedMessage(player);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduleSynchronization(player, session);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
public void onInventoryDrag(InventoryDragEvent event) {
|
public void onInventoryDrag(InventoryDragEvent event) {
|
||||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
InventoryView view = event.getView();
|
||||||
|
Inventory topInventory = view.getTopInventory();
|
||||||
|
if (!(topInventory.getHolder(false) instanceof ShulkerBoxHolder)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
if (!isShulkerBox(event.getOldCursor())) {
|
||||||
if (session == null || event.getView().getTopInventory() != session.inventory) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasSessionToken(event.getOldCursor(), session.token)) {
|
int topSize = topInventory.getSize();
|
||||||
event.setCancelled(true);
|
for (int rawSlot : event.getRawSlots()) {
|
||||||
return;
|
if (rawSlot >= 0 && rawSlot < topSize) {
|
||||||
}
|
|
||||||
|
|
||||||
if (isShulkerBox(event.getOldCursor())
|
|
||||||
&& ShulkerBoxSessionPolicy.touchesTopInventory(event.getRawSlots(), session.inventory.getSize())) {
|
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
|
if (event.getWhoClicked() instanceof Player player) {
|
||||||
sendNestedMessage(player);
|
sendNestedMessage(player);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
scheduleSynchronization(player, session);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
@@ -259,436 +221,111 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
|
||||||
public void onPlayerDropItem(PlayerDropItemEvent event) {
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(event.getPlayer().getUniqueId());
|
|
||||||
if (session != null && hasSessionToken(event.getItemDrop().getItemStack(), session.token)) {
|
|
||||||
event.setCancelled(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
|
||||||
public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) {
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(event.getPlayer().getUniqueId());
|
|
||||||
if (session == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasSessionToken(event.getMainHandItem(), session.token)
|
|
||||||
|| hasSessionToken(event.getOffHandItem(), session.token)) {
|
|
||||||
event.setCancelled(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
|
||||||
public void onPlayerDeath(PlayerDeathEvent event) {
|
|
||||||
Player player = event.getPlayer();
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.remove(player.getUniqueId());
|
|
||||||
if (session == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean saved;
|
|
||||||
if (event.getKeepInventory()) {
|
|
||||||
saved = writeSessionToPlayer(player, session, true);
|
|
||||||
} else {
|
|
||||||
saved = writeSessionToDrops(event.getDrops(), session);
|
|
||||||
if (!saved) {
|
|
||||||
saved = writeSessionToPlayer(player, session, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!saved) {
|
|
||||||
handleLostSource(player, session, "玩家死亡时未找到唯一的源物品");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
commitCurrentSession(event.getPlayer());
|
Player player = event.getPlayer();
|
||||||
|
commitOpenShulker(player, player.getOpenInventory().getTopInventory());
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerKick(PlayerKickEvent event) {
|
public void onPlayerKick(PlayerKickEvent event) {
|
||||||
commitCurrentSession(event.getPlayer());
|
Player player = event.getPlayer();
|
||||||
}
|
commitOpenShulker(player, player.getOpenInventory().getTopInventory());
|
||||||
|
|
||||||
@EventHandler
|
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
|
||||||
if (!openShulkerBoxes.containsKey(event.getPlayer().getUniqueId())) {
|
|
||||||
clearStaleSessionTokens(event.getPlayer());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPluginDisable(PluginDisableEvent event) {
|
public void onPluginDisable(PluginDisableEvent event) {
|
||||||
if (event.getPlugin() == plugin) {
|
if (event.getPlugin() != plugin) {
|
||||||
shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
|
||||||
for (UUID playerId : List.copyOf(openShulkerBoxes.keySet())) {
|
|
||||||
Player player = Bukkit.getPlayer(playerId);
|
|
||||||
if (player == null) {
|
|
||||||
openShulkerBoxes.remove(playerId);
|
|
||||||
plugin.getLogger().warning("潜影盒会话关闭失败: 玩家 " + playerId + " 已离线。");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(playerId);
|
|
||||||
boolean viewingSession = session != null && player.getOpenInventory().getTopInventory() == session.inventory;
|
|
||||||
commitCurrentSession(player);
|
|
||||||
if (viewingSession) {
|
|
||||||
player.closeInventory();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void openShulkerBox(Player player, EquipmentSlot hand, ItemStack sourceItem) {
|
|
||||||
if (!(sourceItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)
|
|
||||||
|| !(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
|
||||||
sendOpenFailedMessage(player);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String token = UUID.randomUUID().toString();
|
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||||
ItemStack taggedSource = sourceItem.clone();
|
commitOpenShulker(player, player.getOpenInventory().getTopInventory());
|
||||||
setSessionToken(taggedSource, token);
|
|
||||||
setItemInHand(player, hand, taggedSource);
|
|
||||||
|
|
||||||
ShulkerBoxHolder holder;
|
|
||||||
try {
|
|
||||||
holder = new ShulkerBoxHolder(resolveTitle(sourceItem));
|
|
||||||
holder.getInventory().setContents(cloneContents(shulkerBox.getInventory().getContents()));
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
clearTokenFromPlayer(player, token);
|
|
||||||
plugin.getLogger().warning("打开潜影盒失败: " + exception.getMessage());
|
|
||||||
sendOpenFailedMessage(player);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
int preferredSlot = hand == EquipmentSlot.HAND ? player.getInventory().getHeldItemSlot() : OFF_HAND_SLOT;
|
|
||||||
OpenShulkerSession session = new OpenShulkerSession(token, holder.getInventory(), preferredSlot);
|
|
||||||
openShulkerBoxes.put(player.getUniqueId(), session);
|
|
||||||
|
|
||||||
try {
|
|
||||||
InventoryView openedView = player.openInventory(session.inventory);
|
|
||||||
if (openedView == null
|
|
||||||
|| openedView.getTopInventory() != session.inventory
|
|
||||||
|| player.getOpenInventory().getTopInventory() != session.inventory) {
|
|
||||||
rollbackFailedOpen(player, session);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
plugin.getLogger().warning("打开潜影盒失败: " + exception.getMessage());
|
|
||||||
rollbackFailedOpen(player, session);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
player.playSound(player.getLocation(), Sound.BLOCK_SHULKER_BOX_OPEN, 0.8F, 1.0F);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void rollbackFailedOpen(Player player, OpenShulkerSession session) {
|
|
||||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
|
||||||
clearTokenFromPlayer(player, session.token);
|
|
||||||
sendOpenFailedMessage(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void scheduleSynchronization(Player player, OpenShulkerSession session) {
|
|
||||||
if (session.syncScheduled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
session.syncScheduled = true;
|
|
||||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
|
||||||
session.syncScheduled = false;
|
|
||||||
if (openShulkerBoxes.get(player.getUniqueId()) != session) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!writeSessionToPlayer(player, session, false)) {
|
|
||||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
|
||||||
handleLostSource(player, session, "同步期间未找到唯一的源物品");
|
|
||||||
if (player.getOpenInventory().getTopInventory() == session.inventory) {
|
|
||||||
player.closeInventory();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void commitCurrentSession(Player player) {
|
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
|
||||||
if (session != null) {
|
|
||||||
commitOpenShulker(player, session.inventory);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean commitOpenShulker(Player player, Inventory inventory) {
|
private boolean commitOpenShulker(Player player, Inventory inventory) {
|
||||||
OpenShulkerSession session = openShulkerBoxes.get(player.getUniqueId());
|
if (!(inventory.getHolder(false) instanceof ShulkerBoxHolder)) {
|
||||||
if (session == null || session.inventory != inventory) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
openShulkerBoxes.remove(player.getUniqueId(), session);
|
OpenShulkerSession session = openShulkerBoxes.remove(player.getUniqueId());
|
||||||
boolean saved = writeSessionToPlayer(player, session, true);
|
if (session == null) {
|
||||||
if (!saved) {
|
|
||||||
handleLostSource(player, session, "关闭期间未找到唯一的源物品");
|
|
||||||
}
|
|
||||||
return saved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean writeSessionToPlayer(Player player, OpenShulkerSession session, boolean clearToken) {
|
|
||||||
List<LocatedSource> sources = findSources(player, session);
|
|
||||||
if (sources.size() != 1) {
|
|
||||||
clearSessionTokens(sources);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
LocatedSource source = sources.getFirst();
|
ItemStack updatedShulker = session.sourceItem.clone();
|
||||||
if (source.item().getAmount() != 1) {
|
writeInventoryBack(updatedShulker, inventory.getContents());
|
||||||
clearSessionTokens(sources);
|
restoreItemToPlayer(player, session, updatedShulker);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ItemStack updatedItem = source.item().clone();
|
|
||||||
if (!writeInventoryBack(updatedItem, session.inventory.getContents(), clearToken)) {
|
|
||||||
clearSessionTokens(sources);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
source.save().accept(updatedItem);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean writeSessionToDrops(List<ItemStack> drops, OpenShulkerSession session) {
|
private void openShulkerBox(Player player, EquipmentSlot hand, ItemStack sourceItem, ShulkerBox shulkerBox) {
|
||||||
List<Integer> matchingIndexes = new ArrayList<>();
|
removeItemFromHand(player, hand);
|
||||||
for (int index = 0; index < drops.size(); index++) {
|
|
||||||
if (hasSessionToken(drops.get(index), session.token)) {
|
|
||||||
matchingIndexes.add(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matchingIndexes.size() != 1) {
|
ShulkerBoxHolder holder = new ShulkerBoxHolder(resolveTitle(sourceItem));
|
||||||
clearTokensFromDrops(drops, matchingIndexes);
|
holder.getInventory().setContents(cloneContents(shulkerBox.getInventory().getContents()));
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
int sourceIndex = matchingIndexes.getFirst();
|
int preferredSlot = hand == EquipmentSlot.HAND ? player.getInventory().getHeldItemSlot() : -1;
|
||||||
ItemStack sourceItem = drops.get(sourceIndex);
|
openShulkerBoxes.put(player.getUniqueId(), new OpenShulkerSession(sourceItem, hand, preferredSlot));
|
||||||
if (sourceItem.getAmount() != 1) {
|
player.openInventory(holder.getInventory());
|
||||||
clearTokensFromDrops(drops, matchingIndexes);
|
player.playSound(player.getLocation(), Sound.BLOCK_SHULKER_BOX_OPEN, 0.8F, 1.0F);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ItemStack updatedItem = sourceItem.clone();
|
|
||||||
if (!writeInventoryBack(updatedItem, session.inventory.getContents(), true)) {
|
|
||||||
clearTokensFromDrops(drops, matchingIndexes);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
drops.set(sourceIndex, updatedItem);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean writeInventoryBack(ItemStack shulkerItem, ItemStack[] contents, boolean clearToken) {
|
|
||||||
if (containsShulkerBox(contents)) {
|
|
||||||
plugin.getLogger().warning("保存潜影盒内容失败: 虚拟容器中检测到嵌套潜影盒。");
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void writeInventoryBack(ItemStack shulkerItem, ItemStack[] contents) {
|
||||||
if (!(shulkerItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)) {
|
if (!(shulkerItem.getItemMeta() instanceof BlockStateMeta blockStateMeta)) {
|
||||||
plugin.getLogger().warning("保存潜影盒内容失败: 缺少 BlockStateMeta。");
|
plugin.getLogger().warning("保存潜影盒内容失败: 缺少 BlockStateMeta。");
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
if (!(blockStateMeta.getBlockState() instanceof ShulkerBox shulkerBox)) {
|
||||||
plugin.getLogger().warning("保存潜影盒内容失败: 方块状态不是 ShulkerBox。");
|
plugin.getLogger().warning("保存潜影盒内容失败: 方块状态不是 ShulkerBox。");
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
shulkerBox.getInventory().setContents(cloneContents(contents));
|
|
||||||
blockStateMeta.setBlockState(shulkerBox);
|
|
||||||
if (clearToken) {
|
|
||||||
blockStateMeta.getPersistentDataContainer().remove(sessionKey);
|
|
||||||
}
|
|
||||||
shulkerItem.setItemMeta(blockStateMeta);
|
|
||||||
return true;
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
plugin.getLogger().warning("保存潜影盒内容失败: " + exception.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<LocatedSource> findSources(Player player, OpenShulkerSession session) {
|
|
||||||
List<LocatedSource> sources = new ArrayList<>();
|
|
||||||
PlayerInventory inventory = player.getInventory();
|
|
||||||
|
|
||||||
if (session.preferredSlot >= 0 && session.preferredSlot < inventory.getSize()) {
|
|
||||||
addSourceIfMatching(
|
|
||||||
sources,
|
|
||||||
inventory.getItem(session.preferredSlot),
|
|
||||||
item -> inventory.setItem(session.preferredSlot, item),
|
|
||||||
session.token
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
|
||||||
if (slot == session.preferredSlot) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
int inventorySlot = slot;
|
|
||||||
addSourceIfMatching(
|
|
||||||
sources,
|
|
||||||
inventory.getItem(inventorySlot),
|
|
||||||
item -> inventory.setItem(inventorySlot, item),
|
|
||||||
session.token
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
addSourceIfMatching(sources, player.getItemOnCursor(), player::setItemOnCursor, session.token);
|
|
||||||
return sources;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addSourceIfMatching(
|
|
||||||
List<LocatedSource> sources,
|
|
||||||
ItemStack item,
|
|
||||||
Consumer<ItemStack> save,
|
|
||||||
String token
|
|
||||||
) {
|
|
||||||
if (hasSessionToken(item, token)) {
|
|
||||||
sources.add(new LocatedSource(item, save));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearSessionTokens(List<LocatedSource> sources) {
|
|
||||||
for (LocatedSource source : sources) {
|
|
||||||
ItemStack cleanedItem = source.item().clone();
|
|
||||||
clearSessionToken(cleanedItem);
|
|
||||||
source.save().accept(cleanedItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearTokensFromDrops(List<ItemStack> drops, List<Integer> indexes) {
|
|
||||||
for (int index : indexes) {
|
|
||||||
ItemStack cleanedItem = drops.get(index).clone();
|
|
||||||
clearSessionToken(cleanedItem);
|
|
||||||
drops.set(index, cleanedItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearTokenFromPlayer(Player player, String token) {
|
|
||||||
PlayerInventory inventory = player.getInventory();
|
|
||||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
|
||||||
ItemStack item = inventory.getItem(slot);
|
|
||||||
if (!hasSessionToken(item, token)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
ItemStack cleanedItem = item.clone();
|
|
||||||
clearSessionToken(cleanedItem);
|
|
||||||
inventory.setItem(slot, cleanedItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
ItemStack cursor = player.getItemOnCursor();
|
|
||||||
if (hasSessionToken(cursor, token)) {
|
|
||||||
ItemStack cleanedCursor = cursor.clone();
|
|
||||||
clearSessionToken(cleanedCursor);
|
|
||||||
player.setItemOnCursor(cleanedCursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearStaleSessionTokens(Player player) {
|
|
||||||
PlayerInventory inventory = player.getInventory();
|
|
||||||
for (int slot = 0; slot < inventory.getSize(); slot++) {
|
|
||||||
ItemStack item = inventory.getItem(slot);
|
|
||||||
if (!hasAnySessionToken(item)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
ItemStack cleanedItem = item.clone();
|
|
||||||
clearSessionToken(cleanedItem);
|
|
||||||
inventory.setItem(slot, cleanedItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
ItemStack cursor = player.getItemOnCursor();
|
|
||||||
if (hasAnySessionToken(cursor)) {
|
|
||||||
ItemStack cleanedCursor = cursor.clone();
|
|
||||||
clearSessionToken(cleanedCursor);
|
|
||||||
player.setItemOnCursor(cleanedCursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleLostSource(Player player, OpenShulkerSession session, String reason) {
|
|
||||||
clearTokenFromPlayer(player, session.token);
|
|
||||||
plugin.getLogger().warning("潜影盒会话已终止: " + player.getName() + " (" + player.getUniqueId() + ")," + reason + "。");
|
|
||||||
if (player.isOnline()) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-session-invalid"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setSessionToken(ItemStack item, String token) {
|
|
||||||
ItemMeta itemMeta = item.getItemMeta();
|
|
||||||
itemMeta.getPersistentDataContainer().set(sessionKey, PersistentDataType.STRING, token);
|
|
||||||
item.setItemMeta(itemMeta);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearSessionToken(ItemStack item) {
|
|
||||||
ItemMeta itemMeta = item.getItemMeta();
|
|
||||||
if (itemMeta == null) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
itemMeta.getPersistentDataContainer().remove(sessionKey);
|
|
||||||
item.setItemMeta(itemMeta);
|
shulkerBox.getInventory().setContents(cloneContents(contents));
|
||||||
|
blockStateMeta.setBlockState(shulkerBox);
|
||||||
|
shulkerItem.setItemMeta(blockStateMeta);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean hasSessionToken(ItemStack item, String token) {
|
private void restoreItemToPlayer(Player player, OpenShulkerSession session, ItemStack shulkerItem) {
|
||||||
if (!isShulkerBox(item)) {
|
PlayerInventory inventory = player.getInventory();
|
||||||
return false;
|
|
||||||
|
if (session.sourceHand == EquipmentSlot.OFF_HAND) {
|
||||||
|
if (isEmpty(inventory.getItemInOffHand())) {
|
||||||
|
inventory.setItemInOffHand(shulkerItem);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
ItemMeta itemMeta = item.getItemMeta();
|
} else if (session.preferredSlot >= 0 && isEmpty(inventory.getItem(session.preferredSlot))) {
|
||||||
if (itemMeta == null) {
|
inventory.setItem(session.preferredSlot, shulkerItem);
|
||||||
return false;
|
return;
|
||||||
}
|
|
||||||
String storedToken = itemMeta.getPersistentDataContainer().get(sessionKey, PersistentDataType.STRING);
|
|
||||||
return token.equals(storedToken);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean hasAnySessionToken(ItemStack item) {
|
Map<Integer, ItemStack> leftovers = inventory.addItem(shulkerItem);
|
||||||
if (!isShulkerBox(item)) {
|
for (ItemStack leftover : leftovers.values()) {
|
||||||
return false;
|
player.getWorld().dropItemNaturally(player.getLocation(), leftover);
|
||||||
}
|
}
|
||||||
ItemMeta itemMeta = item.getItemMeta();
|
|
||||||
return itemMeta != null && itemMeta.getPersistentDataContainer().has(sessionKey, PersistentDataType.STRING);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ItemStack[] cloneContents(ItemStack[] contents) {
|
private ItemStack[] cloneContents(ItemStack[] contents) {
|
||||||
ItemStack[] copied = new ItemStack[SHULKER_SIZE];
|
ItemStack[] copied = new ItemStack[SHULKER_SIZE];
|
||||||
for (int index = 0; index < SHULKER_SIZE && index < contents.length; index++) {
|
for (int i = 0; i < SHULKER_SIZE && i < contents.length; i++) {
|
||||||
copied[index] = contents[index] == null ? null : contents[index].clone();
|
copied[i] = contents[i] == null ? null : contents[i].clone();
|
||||||
}
|
}
|
||||||
return copied;
|
return copied;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean containsShulkerBox(ItemStack[] contents) {
|
|
||||||
for (ItemStack item : contents) {
|
|
||||||
if (isShulkerBox(item)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ItemStack getItemFromHand(Player player, EquipmentSlot hand) {
|
private ItemStack getItemFromHand(Player player, EquipmentSlot hand) {
|
||||||
return hand == EquipmentSlot.OFF_HAND
|
return hand == EquipmentSlot.OFF_HAND
|
||||||
? player.getInventory().getItemInOffHand()
|
? player.getInventory().getItemInOffHand()
|
||||||
: player.getInventory().getItemInMainHand();
|
: player.getInventory().getItemInMainHand();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setItemInHand(Player player, EquipmentSlot hand, ItemStack item) {
|
private void removeItemFromHand(Player player, EquipmentSlot hand) {
|
||||||
if (hand == EquipmentSlot.OFF_HAND) {
|
if (hand == EquipmentSlot.OFF_HAND) {
|
||||||
player.getInventory().setItemInOffHand(item);
|
player.getInventory().setItemInOffHand(null);
|
||||||
} else {
|
} else {
|
||||||
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), item);
|
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -699,6 +336,7 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
if (displayName != null) {
|
if (displayName != null) {
|
||||||
return displayName;
|
return displayName;
|
||||||
}
|
}
|
||||||
|
return LegacyComponentSerializer.legacySection().deserialize(itemMeta.getDisplayName());
|
||||||
}
|
}
|
||||||
|
|
||||||
return Component.translatable(shulkerBox.getType().getItemTranslationKey());
|
return Component.translatable(shulkerBox.getType().getItemTranslationKey());
|
||||||
@@ -708,14 +346,14 @@ public class ShulkerBoxListener implements Listener {
|
|||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-nested"));
|
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-nested"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendOpenFailedMessage(Player player) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.shulkerbox-open-failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isShulkerBox(ItemStack item) {
|
private boolean isShulkerBox(ItemStack item) {
|
||||||
return item != null && !item.getType().isAir() && SHULKER_BOX_MATERIALS.contains(item.getType());
|
return item != null && !item.getType().isAir() && SHULKER_BOX_MATERIALS.contains(item.getType());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isEmpty(ItemStack item) {
|
||||||
|
return item == null || item.getType().isAir();
|
||||||
|
}
|
||||||
|
|
||||||
private boolean isSameShulkerItem(ItemStack currentItem, ItemStack sourceSnapshot) {
|
private boolean isSameShulkerItem(ItemStack currentItem, ItemStack sourceSnapshot) {
|
||||||
if (!isShulkerBox(currentItem) || sourceSnapshot == null) {
|
if (!isShulkerBox(currentItem) || sourceSnapshot == null) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.listeners;
|
|
||||||
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
final class ShulkerBoxSessionPolicy {
|
|
||||||
|
|
||||||
private ShulkerBoxSessionPolicy() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean isTopSlot(int rawSlot, int topInventorySize) {
|
|
||||||
return rawSlot >= 0 && rawSlot < topInventorySize;
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean touchesTopInventory(Set<Integer> rawSlots, int topInventorySize) {
|
|
||||||
return rawSlots.stream().anyMatch(rawSlot -> isTopSlot(rawSlot, topInventorySize));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,17 +9,10 @@ import org.bukkit.event.player.PlayerJoinEvent;
|
|||||||
import org.bukkit.event.player.PlayerQuitEvent;
|
import org.bukkit.event.player.PlayerQuitEvent;
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
import org.bukkit.scheduler.BukkitTask;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public final class VanishListener implements Listener {
|
public final class VanishListener implements Listener {
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final BukkitTask permissionTask;
|
private final BukkitTask permissionTask;
|
||||||
private final Map<UUID, Boolean> observerSeePermissions = new HashMap<>();
|
|
||||||
|
|
||||||
public VanishListener(EssentialsC plugin) {
|
public VanishListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
@@ -30,7 +23,6 @@ public final class VanishListener implements Listener {
|
|||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
Player player = event.getPlayer();
|
Player player = event.getPlayer();
|
||||||
observerSeePermissions.put(player.getUniqueId(), player.hasPermission(VanishCommand.SEE_PERMISSION));
|
|
||||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
||||||
VanishCommand.restoreVisibility(plugin, player, false);
|
VanishCommand.restoreVisibility(plugin, player, false);
|
||||||
}
|
}
|
||||||
@@ -43,7 +35,6 @@ public final class VanishListener implements Listener {
|
|||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
observerSeePermissions.remove(event.getPlayer().getUniqueId());
|
|
||||||
Player player = event.getPlayer();
|
Player player = event.getPlayer();
|
||||||
if (VanishCommand.isVanished(player)) {
|
if (VanishCommand.isVanished(player)) {
|
||||||
event.quitMessage(null);
|
event.quitMessage(null);
|
||||||
@@ -55,34 +46,10 @@ public final class VanishListener implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void checkPermissions() {
|
private void checkPermissions() {
|
||||||
Set<UUID> onlinePlayers = new HashSet<>();
|
|
||||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||||
onlinePlayers.add(player.getUniqueId());
|
|
||||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
||||||
VanishCommand.restoreVisibility(plugin, player, true);
|
VanishCommand.restoreVisibility(plugin, player, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
observerSeePermissions.keySet().removeIf(uuid -> !onlinePlayers.contains(uuid));
|
|
||||||
|
|
||||||
for (Player observer : plugin.getServer().getOnlinePlayers()) {
|
|
||||||
boolean canSeeVanished = observer.hasPermission(VanishCommand.SEE_PERMISSION);
|
|
||||||
Boolean previous = observerSeePermissions.put(observer.getUniqueId(), canSeeVanished);
|
|
||||||
if (previous == null || previous != canSeeVanished) {
|
|
||||||
refreshObserverVisibility(observer, canSeeVanished);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void refreshObserverVisibility(Player observer, boolean canSeeVanished) {
|
|
||||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
|
||||||
if (observer.equals(player) || !VanishCommand.isVanished(player)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (canSeeVanished) {
|
|
||||||
observer.showPlayer(plugin, player);
|
|
||||||
} else {
|
|
||||||
observer.hidePlayer(plugin, player);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package cn.infstar.essentialsC.maintenance;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import cn.infstar.essentialsC.ModuleManager;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.event.EventHandler;
|
||||||
|
import org.bukkit.event.Listener;
|
||||||
|
import org.bukkit.event.player.PlayerLoginEvent;
|
||||||
|
import org.bukkit.event.player.PlayerJoinEvent;
|
||||||
|
import org.bukkit.event.player.PlayerQuitEvent;
|
||||||
|
import org.bukkit.event.server.ServerListPingEvent;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public final class MaintenanceListener implements Listener {
|
||||||
|
|
||||||
|
private final EssentialsC plugin;
|
||||||
|
|
||||||
|
public MaintenanceListener(EssentialsC plugin) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onServerListPing(ServerListPingEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)
|
||||||
|
|| maintenanceManager == null
|
||||||
|
|| !maintenanceManager.isEnabled()
|
||||||
|
|| !maintenanceManager.isMotdEnabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.setMotd(maintenanceManager.getMotd());
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onPlayerLogin(PlayerLoginEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)
|
||||||
|
|| maintenanceManager == null
|
||||||
|
|| !maintenanceManager.isEnabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maintenanceManager.canJoin(event.getPlayer())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, maintenanceManager.getKickMessage());
|
||||||
|
notifyBlockedLogin(event, maintenanceManager);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE) || maintenanceManager == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
maintenanceManager.addBossBarPlayer(event.getPlayer());
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (maintenanceManager != null) {
|
||||||
|
maintenanceManager.removeBossBarPlayer(event.getPlayer());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyBlockedLogin(PlayerLoginEvent event, MaintenanceManager maintenanceManager) {
|
||||||
|
if (!maintenanceManager.isNotifyEnabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String address = EssentialsC.getLangManager().getString("maintenance.status.address-hidden");
|
||||||
|
if (maintenanceManager.shouldIncludeAddressInNotification()) {
|
||||||
|
InetAddress inetAddress = event.getAddress();
|
||||||
|
if (inetAddress != null) {
|
||||||
|
address = inetAddress.getHostAddress();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String message = EssentialsC.getLangManager().getPrefixedString("maintenance.messages.login-blocked",
|
||||||
|
Map.of(
|
||||||
|
"player", event.getPlayer().getName(),
|
||||||
|
"uuid", event.getPlayer().getUniqueId().toString(),
|
||||||
|
"address", address
|
||||||
|
));
|
||||||
|
|
||||||
|
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||||
|
if (player.hasPermission(maintenanceManager.getNotifyPermission())) {
|
||||||
|
player.sendMessage(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
package cn.infstar.essentialsC.maintenance;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
|
import org.bukkit.ChatColor;
|
||||||
|
import org.bukkit.boss.BarColor;
|
||||||
|
import org.bukkit.boss.BarStyle;
|
||||||
|
import org.bukkit.boss.BossBar;
|
||||||
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public final class MaintenanceManager {
|
||||||
|
|
||||||
|
private static final int CURRENT_CONFIG_VERSION = 1;
|
||||||
|
|
||||||
|
private final EssentialsC plugin;
|
||||||
|
private final File configFile;
|
||||||
|
private FileConfiguration config;
|
||||||
|
private BossBar bossBar;
|
||||||
|
|
||||||
|
public MaintenanceManager(EssentialsC plugin) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
this.configFile = new File(plugin.getDataFolder(), "maintenance.yml");
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reload() {
|
||||||
|
if (!configFile.exists()) {
|
||||||
|
plugin.saveResource("maintenance.yml", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
config = YamlConfiguration.loadConfiguration(configFile);
|
||||||
|
config.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
||||||
|
config.addDefault("enabled", false);
|
||||||
|
config.addDefault("bypass-permission", "essentialsc.maintenance.bypass");
|
||||||
|
config.addDefault("notify.enabled", true);
|
||||||
|
config.addDefault("notify.permission", "essentialsc.maintenance.notify");
|
||||||
|
config.addDefault("notify.include-address", false);
|
||||||
|
config.addDefault("whitelist.uuids", List.of());
|
||||||
|
config.addDefault("whitelist.names", List.of());
|
||||||
|
config.addDefault("motd.enabled", true);
|
||||||
|
config.addDefault("motd.lines", List.of("&c服务器维护中", "&7请稍后再试"));
|
||||||
|
config.addDefault("kick-message", List.of("&c服务器正在维护", "&7请稍后再进入"));
|
||||||
|
config.addDefault("bossbar.enabled", true);
|
||||||
|
config.addDefault("bossbar.title", "&c服务器正在维护");
|
||||||
|
config.addDefault("bossbar.color", "RED");
|
||||||
|
config.addDefault("bossbar.style", "SOLID");
|
||||||
|
config.addDefault("bossbar.progress", 1.0D);
|
||||||
|
config.options().copyDefaults(true);
|
||||||
|
refreshBossBar();
|
||||||
|
if (isEnabled()) {
|
||||||
|
kickUnauthorizedPlayers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return config.getBoolean("enabled", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEnabled(boolean enabled) {
|
||||||
|
config.set("enabled", enabled);
|
||||||
|
save();
|
||||||
|
refreshBossBar();
|
||||||
|
if (enabled) {
|
||||||
|
kickUnauthorizedPlayers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBypassPermission() {
|
||||||
|
return config.getString("bypass-permission", "essentialsc.maintenance.bypass");
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isNotifyEnabled() {
|
||||||
|
return config.getBoolean("notify.enabled", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getNotifyPermission() {
|
||||||
|
return config.getString("notify.permission", "essentialsc.maintenance.notify");
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean shouldIncludeAddressInNotification() {
|
||||||
|
return config.getBoolean("notify.include-address", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean canJoin(Player player) {
|
||||||
|
return player != null && (player.hasPermission(getBypassPermission()) || isWhitelisted(player));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isWhitelisted(Player player) {
|
||||||
|
if (player == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return getWhitelistUuids().contains(player.getUniqueId().toString().toLowerCase(Locale.ROOT))
|
||||||
|
|| getWhitelistNames().contains(normalizeName(player.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean addWhitelistEntry(String input) {
|
||||||
|
String normalized = normalizeEntry(input);
|
||||||
|
if (normalized.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
UUID uuid = parseUuid(normalized);
|
||||||
|
if (uuid != null) {
|
||||||
|
return addWhitelistUuid(uuid.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
Player onlinePlayer = Bukkit.getPlayerExact(normalized);
|
||||||
|
if (onlinePlayer != null) {
|
||||||
|
return addWhitelistUuid(onlinePlayer.getUniqueId().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return addWhitelistName(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean removeWhitelistEntry(String input) {
|
||||||
|
String normalized = normalizeEntry(input);
|
||||||
|
if (normalized.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
UUID uuid = parseUuid(normalized);
|
||||||
|
if (uuid != null) {
|
||||||
|
return removeWhitelistUuid(uuid.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
Player onlinePlayer = Bukkit.getPlayerExact(normalized);
|
||||||
|
if (onlinePlayer != null && removeWhitelistUuid(onlinePlayer.getUniqueId().toString())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return removeWhitelistName(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getWhitelistEntries() {
|
||||||
|
List<String> entries = new ArrayList<>();
|
||||||
|
entries.addAll(getWhitelistNames());
|
||||||
|
entries.addAll(getWhitelistUuids());
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWhitelistCount() {
|
||||||
|
return getWhitelistEntries().size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isMotdEnabled() {
|
||||||
|
return config.getBoolean("motd.enabled", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMotd() {
|
||||||
|
return colorizeLines(config.getStringList("motd.lines"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKickMessage() {
|
||||||
|
return colorizeLines(config.getStringList("kick-message"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void refreshBossBar() {
|
||||||
|
clearBossBar();
|
||||||
|
if (!isEnabled() || !isBossBarEnabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bossBar = plugin.getServer().createBossBar(
|
||||||
|
colorize(config.getString("bossbar.title", "&c服务器正在维护")),
|
||||||
|
readBossBarColor(),
|
||||||
|
readBossBarStyle()
|
||||||
|
);
|
||||||
|
bossBar.setProgress(readBossBarProgress());
|
||||||
|
bossBar.setVisible(true);
|
||||||
|
|
||||||
|
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||||
|
addBossBarPlayer(player);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addBossBarPlayer(Player player) {
|
||||||
|
if (bossBar == null || player == null || !player.isOnline()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bossBar.addPlayer(player);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeBossBarPlayer(Player player) {
|
||||||
|
if (bossBar != null && player != null) {
|
||||||
|
bossBar.removePlayer(player);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void kickUnauthorizedPlayers() {
|
||||||
|
String message = getKickMessage();
|
||||||
|
for (Player player : List.copyOf(plugin.getServer().getOnlinePlayers())) {
|
||||||
|
if (!canJoin(player)) {
|
||||||
|
player.kickPlayer(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
clearBossBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void clearBossBar() {
|
||||||
|
if (bossBar == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bossBar.removeAll();
|
||||||
|
bossBar = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isBossBarEnabled() {
|
||||||
|
return config.getBoolean("bossbar.enabled", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BarColor readBossBarColor() {
|
||||||
|
try {
|
||||||
|
return BarColor.valueOf(config.getString("bossbar.color", "RED").toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
return BarColor.RED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BarStyle readBossBarStyle() {
|
||||||
|
try {
|
||||||
|
return BarStyle.valueOf(config.getString("bossbar.style", "SOLID").toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
return BarStyle.SOLID;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private double readBossBarProgress() {
|
||||||
|
double progress = config.getDouble("bossbar.progress", 1.0D);
|
||||||
|
if (!Double.isFinite(progress)) {
|
||||||
|
return 1.0D;
|
||||||
|
}
|
||||||
|
return Math.max(0.0D, Math.min(1.0D, progress));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean addWhitelistUuid(String uuid) {
|
||||||
|
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean addWhitelistName(String name) {
|
||||||
|
return updateWhitelist("whitelist.names", normalizeName(name), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean removeWhitelistUuid(String uuid) {
|
||||||
|
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean removeWhitelistName(String name) {
|
||||||
|
return updateWhitelist("whitelist.names", normalizeName(name), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean updateWhitelist(String path, String value, boolean add) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> entries = path.endsWith(".names") ? getWhitelistNames() : getWhitelistUuids();
|
||||||
|
boolean changed;
|
||||||
|
if (add) {
|
||||||
|
changed = entries.add(value);
|
||||||
|
} else {
|
||||||
|
changed = entries.remove(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
|
config.set(path, new ArrayList<>(entries));
|
||||||
|
save();
|
||||||
|
refreshBossBar();
|
||||||
|
if (isEnabled()) {
|
||||||
|
kickUnauthorizedPlayers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> getWhitelistUuids() {
|
||||||
|
Set<String> entries = new LinkedHashSet<>();
|
||||||
|
for (String value : config.getStringList("whitelist.uuids")) {
|
||||||
|
String normalized = normalizeEntry(value).toLowerCase(Locale.ROOT);
|
||||||
|
if (!normalized.isEmpty()) {
|
||||||
|
entries.add(normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> getWhitelistNames() {
|
||||||
|
Set<String> entries = new LinkedHashSet<>();
|
||||||
|
for (String value : config.getStringList("whitelist.names")) {
|
||||||
|
String normalized = normalizeName(value);
|
||||||
|
if (!normalized.isEmpty()) {
|
||||||
|
entries.add(normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private UUID parseUuid(String input) {
|
||||||
|
try {
|
||||||
|
return UUID.fromString(input);
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeEntry(String input) {
|
||||||
|
return input == null ? "" : input.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeName(String input) {
|
||||||
|
return normalizeEntry(input).toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String colorizeLines(List<String> lines) {
|
||||||
|
if (lines == null || lines.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return String.join("\n", lines.stream()
|
||||||
|
.map(this::colorize)
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String colorize(String text) {
|
||||||
|
return ChatColor.translateAlternateColorCodes('&', text == null ? "" : text);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void save() {
|
||||||
|
try {
|
||||||
|
AtomicYamlWriter.save(config, configFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("保存 maintenance.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.player;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import org.bukkit.GameMode;
|
|
||||||
import org.bukkit.NamespacedKey;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.EventHandler;
|
|
||||||
import org.bukkit.event.Listener;
|
|
||||||
import org.bukkit.event.player.PlayerJoinEvent;
|
|
||||||
import org.bukkit.persistence.PersistentDataContainer;
|
|
||||||
import org.bukkit.persistence.PersistentDataType;
|
|
||||||
import org.bukkit.potion.PotionEffect;
|
|
||||||
import org.bukkit.potion.PotionEffectType;
|
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
|
||||||
|
|
||||||
public final class PlayerStateManager implements Listener {
|
|
||||||
|
|
||||||
public static final String FLY_PERMISSION = "essentialsc.command.fly";
|
|
||||||
public static final String NIGHT_VISION_PERMISSION = "essentialsc.command.nightvision";
|
|
||||||
public static final String GLOW_PERMISSION = "essentialsc.command.glow";
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final NamespacedKey flyEnabledKey;
|
|
||||||
private final NamespacedKey flyPreviousAllowKey;
|
|
||||||
private final NamespacedKey flyPreviousFlyingKey;
|
|
||||||
private final NamespacedKey nightVisionEnabledKey;
|
|
||||||
private final NamespacedKey glowEnabledKey;
|
|
||||||
private final BukkitTask permissionTask;
|
|
||||||
|
|
||||||
public PlayerStateManager(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.flyEnabledKey = new NamespacedKey(plugin, "fly_enabled");
|
|
||||||
this.flyPreviousAllowKey = new NamespacedKey(plugin, "fly_previous_allow");
|
|
||||||
this.flyPreviousFlyingKey = new NamespacedKey(plugin, "fly_previous_flying");
|
|
||||||
this.nightVisionEnabledKey = new NamespacedKey(plugin, "nightvision_enabled");
|
|
||||||
this.glowEnabledKey = new NamespacedKey(plugin, "glow_enabled");
|
|
||||||
this.permissionTask = plugin.getServer().getScheduler()
|
|
||||||
.runTaskTimer(plugin, this::reconcileOnlinePlayers, 40L, 40L);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isFlyEnabled(Player player) {
|
|
||||||
return isMarked(player, flyEnabledKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void enableFly(Player player) {
|
|
||||||
if (isFlyEnabled(player)) {
|
|
||||||
player.setAllowFlight(true);
|
|
||||||
player.setFlying(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
PersistentDataContainer data = player.getPersistentDataContainer();
|
|
||||||
setBoolean(data, flyPreviousAllowKey, player.getAllowFlight());
|
|
||||||
setBoolean(data, flyPreviousFlyingKey, player.isFlying());
|
|
||||||
setBoolean(data, flyEnabledKey, true);
|
|
||||||
player.setAllowFlight(true);
|
|
||||||
player.setFlying(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void disableFly(Player player) {
|
|
||||||
PersistentDataContainer data = player.getPersistentDataContainer();
|
|
||||||
if (!isMarked(data, flyEnabledKey)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean previousAllow = getBoolean(data, flyPreviousAllowKey);
|
|
||||||
boolean previousFlying = getBoolean(data, flyPreviousFlyingKey);
|
|
||||||
clearFlyMarkers(data);
|
|
||||||
|
|
||||||
boolean allowFlight = previousAllow || hasGameModeFlight(player);
|
|
||||||
player.setFlying(previousFlying && allowFlight);
|
|
||||||
player.setAllowFlight(allowFlight);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isNightVisionEnabled(Player player) {
|
|
||||||
return isMarked(player, nightVisionEnabledKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void enableNightVision(Player player) {
|
|
||||||
if (!player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
|
|
||||||
player.addPotionEffect(new PotionEffect(
|
|
||||||
PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false, false));
|
|
||||||
setBoolean(player.getPersistentDataContainer(), nightVisionEnabledKey, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void disableNightVision(Player player) {
|
|
||||||
if (!isNightVisionEnabled(player)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
|
|
||||||
player.getPersistentDataContainer().remove(nightVisionEnabledKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isGlowEnabled(Player player) {
|
|
||||||
return isMarked(player, glowEnabledKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void enableGlow(Player player) {
|
|
||||||
if (!player.isGlowing()) {
|
|
||||||
player.setGlowing(true);
|
|
||||||
setBoolean(player.getPersistentDataContainer(), glowEnabledKey, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void disableGlow(Player player) {
|
|
||||||
if (!isGlowEnabled(player)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
player.setGlowing(false);
|
|
||||||
player.getPersistentDataContainer().remove(glowEnabledKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler
|
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
|
||||||
plugin.getServer().getScheduler().runTask(plugin, () -> reconcilePlayer(event.getPlayer(), false));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
|
||||||
permissionTask.cancel();
|
|
||||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
|
||||||
releaseOwnedStates(player, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void reconcileOnlinePlayers() {
|
|
||||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
|
||||||
reconcilePlayer(player, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void reconcilePlayer(Player player, boolean notify) {
|
|
||||||
if (isFlyEnabled(player)) {
|
|
||||||
if (!player.hasPermission(FLY_PERMISSION)) {
|
|
||||||
disableFly(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.fly-permission-removed", notify);
|
|
||||||
} else if (!player.getAllowFlight()) {
|
|
||||||
player.setAllowFlight(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isNightVisionEnabled(player)) {
|
|
||||||
if (!player.hasPermission(NIGHT_VISION_PERMISSION)) {
|
|
||||||
disableNightVision(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.nightvision-permission-removed", notify);
|
|
||||||
} else if (!player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
|
|
||||||
player.addPotionEffect(new PotionEffect(
|
|
||||||
PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false, false));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isGlowEnabled(player)) {
|
|
||||||
if (!player.hasPermission(GLOW_PERMISSION)) {
|
|
||||||
disableGlow(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.glow-permission-removed", notify);
|
|
||||||
} else if (!player.isGlowing()) {
|
|
||||||
player.setGlowing(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void releaseOwnedStates(Player player, boolean notify) {
|
|
||||||
if (isFlyEnabled(player)) {
|
|
||||||
disableFly(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.fly-permission-removed", notify);
|
|
||||||
}
|
|
||||||
if (isNightVisionEnabled(player)) {
|
|
||||||
disableNightVision(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.nightvision-permission-removed", notify);
|
|
||||||
}
|
|
||||||
if (isGlowEnabled(player)) {
|
|
||||||
disableGlow(player);
|
|
||||||
notifyPermissionRemoval(player, "messages.glow-permission-removed", notify);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void notifyPermissionRemoval(Player player, String path, boolean notify) {
|
|
||||||
if (notify) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isMarked(Player player, NamespacedKey key) {
|
|
||||||
return isMarked(player.getPersistentDataContainer(), key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isMarked(PersistentDataContainer data, NamespacedKey key) {
|
|
||||||
Byte value = data.get(key, PersistentDataType.BYTE);
|
|
||||||
return value != null && value == (byte) 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean getBoolean(PersistentDataContainer data, NamespacedKey key) {
|
|
||||||
return isMarked(data, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setBoolean(PersistentDataContainer data, NamespacedKey key, boolean value) {
|
|
||||||
data.set(key, PersistentDataType.BYTE, value ? (byte) 1 : (byte) 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearFlyMarkers(PersistentDataContainer data) {
|
|
||||||
data.remove(flyEnabledKey);
|
|
||||||
data.remove(flyPreviousAllowKey);
|
|
||||||
data.remove(flyPreviousFlyingKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean hasGameModeFlight(Player player) {
|
|
||||||
return player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.infstar.essentialsC.skinbridge;
|
package cn.infstar.essentialsC.skinbridge;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import com.destroystokyo.paper.profile.ProfileProperty;
|
import com.destroystokyo.paper.profile.ProfileProperty;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
@@ -9,19 +10,21 @@ import com.google.gson.JsonParser;
|
|||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
import org.bukkit.configuration.ConfigurationSection;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.player.PlayerJoinEvent;
|
import org.bukkit.event.player.PlayerJoinEvent;
|
||||||
import org.bukkit.event.player.PlayerQuitEvent;
|
import org.bukkit.event.player.PlayerQuitEvent;
|
||||||
import org.bukkit.scheduler.BukkitRunnable;
|
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
import java.net.http.HttpResponse;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
@@ -34,9 +37,6 @@ import java.util.UUID;
|
|||||||
import java.util.concurrent.ArrayBlockingQueue;
|
import java.util.concurrent.ArrayBlockingQueue;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.Future;
|
|
||||||
import java.util.concurrent.RejectedExecutionException;
|
import java.util.concurrent.RejectedExecutionException;
|
||||||
import java.util.concurrent.ThreadFactory;
|
import java.util.concurrent.ThreadFactory;
|
||||||
import java.util.concurrent.ThreadPoolExecutor;
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
@@ -51,19 +51,13 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
private final ThreadPoolExecutor executor;
|
private final ThreadPoolExecutor executor;
|
||||||
private final SkinCacheStore cacheStore;
|
private final File generatedCacheFile;
|
||||||
private final ConcurrentMap<UUID, CachedLookup> cache = new ConcurrentHashMap<>();
|
private final ConcurrentMap<UUID, CachedLookup> cache = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<SkinCacheStore.Key, SkinCacheStore.Entry> generatedSkinCache = new ConcurrentHashMap<>();
|
private final ConcurrentMap<SkinCacheKey, GeneratedCacheEntry> generatedSkinCache = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<UUID, Long> pendingLookups = new ConcurrentHashMap<>();
|
private final ConcurrentMap<UUID, Long> pendingLookups = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<UUID, BukkitRunnable> scheduledLookups = new ConcurrentHashMap<>();
|
|
||||||
private final ConcurrentMap<LookupKey, Future<?>> runningLookups = new ConcurrentHashMap<>();
|
|
||||||
private final ConcurrentMap<UUID, Long> forceRefreshCooldowns = new ConcurrentHashMap<>();
|
private final ConcurrentMap<UUID, Long> forceRefreshCooldowns = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<UUID, String> loginSkinUrls = new ConcurrentHashMap<>();
|
private final ConcurrentMap<UUID, String> loginSkinUrls = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<SkinCacheStore.Key, CompletableFuture<GeneratedSkin>> pendingGenerations = new ConcurrentHashMap<>();
|
|
||||||
private final AtomicLong configurationGeneration = new AtomicLong();
|
private final AtomicLong configurationGeneration = new AtomicLong();
|
||||||
private BukkitTask generatedCacheSaveTask;
|
|
||||||
private boolean generatedCacheDirty;
|
|
||||||
private volatile boolean shuttingDown;
|
|
||||||
|
|
||||||
private volatile List<SkinProvider> providers = List.of();
|
private volatile List<SkinProvider> providers = List.of();
|
||||||
private volatile SkinBridgeGateway gateway;
|
private volatile SkinBridgeGateway gateway;
|
||||||
@@ -72,7 +66,6 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
private volatile boolean logDetectionResults;
|
private volatile boolean logDetectionResults;
|
||||||
private volatile int requestTimeoutSeconds;
|
private volatile int requestTimeoutSeconds;
|
||||||
private volatile int cacheMinutes;
|
private volatile int cacheMinutes;
|
||||||
private volatile int maxGeneratedCacheEntries;
|
|
||||||
private volatile int forceRefreshCooldownSeconds;
|
private volatile int forceRefreshCooldownSeconds;
|
||||||
private volatile boolean requireCurrentTextureMatch;
|
private volatile boolean requireCurrentTextureMatch;
|
||||||
private volatile long joinDelayTicks;
|
private volatile long joinDelayTicks;
|
||||||
@@ -81,7 +74,7 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
|
|
||||||
public SkinBridgeManager(EssentialsC plugin) {
|
public SkinBridgeManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.cacheStore = new SkinCacheStore(plugin);
|
this.generatedCacheFile = new File(plugin.getDataFolder(), "skin-cache.yml");
|
||||||
this.httpClient = HttpClient.newBuilder()
|
this.httpClient = HttpClient.newBuilder()
|
||||||
.connectTimeout(Duration.ofSeconds(5))
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
.followRedirects(HttpClient.Redirect.NEVER)
|
.followRedirects(HttpClient.Redirect.NEVER)
|
||||||
@@ -101,10 +94,6 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
configurationGeneration.incrementAndGet();
|
configurationGeneration.incrementAndGet();
|
||||||
cancelScheduledLookups();
|
|
||||||
cancelRunningLookups();
|
|
||||||
pendingLookups.clear();
|
|
||||||
pendingGenerations.clear();
|
|
||||||
FileConfiguration config = plugin.getConfig();
|
FileConfiguration config = plugin.getConfig();
|
||||||
|
|
||||||
debug = plugin.getConfig().getBoolean("debug", false);
|
debug = plugin.getConfig().getBoolean("debug", false);
|
||||||
@@ -118,7 +107,6 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
long minimumSubmitIntervalMillis = clamp(
|
long minimumSubmitIntervalMillis = clamp(
|
||||||
config.getLong("skin-bridge.mineskin.minimum-submit-interval-millis", 1000L), 0L, 10000L);
|
config.getLong("skin-bridge.mineskin.minimum-submit-interval-millis", 1000L), 0L, 10000L);
|
||||||
cacheMinutes = clamp(config.getInt("skin-bridge.cache-minutes", 120), 5, 10080);
|
cacheMinutes = clamp(config.getInt("skin-bridge.cache-minutes", 120), 5, 10080);
|
||||||
maxGeneratedCacheEntries = clamp(config.getInt("skin-bridge.max-generated-cache-entries", 500), 10, 10_000);
|
|
||||||
forceRefreshCooldownSeconds = clamp(config.getInt("skin-bridge.force-refresh-cooldown-seconds", 30), 0, 3600);
|
forceRefreshCooldownSeconds = clamp(config.getInt("skin-bridge.force-refresh-cooldown-seconds", 30), 0, 3600);
|
||||||
requireCurrentTextureMatch = config.getBoolean("skin-bridge.require-current-texture-match", true);
|
requireCurrentTextureMatch = config.getBoolean("skin-bridge.require-current-texture-match", true);
|
||||||
joinDelayTicks = clamp(config.getLong("skin-bridge.join-delay-ticks", 20L), 0, 200);
|
joinDelayTicks = clamp(config.getLong("skin-bridge.join-delay-ticks", 20L), 0, 200);
|
||||||
@@ -135,17 +123,12 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
shuttingDown = true;
|
|
||||||
configurationGeneration.incrementAndGet();
|
configurationGeneration.incrementAndGet();
|
||||||
cancelScheduledLookups();
|
|
||||||
cancelRunningLookups();
|
|
||||||
executor.shutdownNow();
|
executor.shutdownNow();
|
||||||
cancelGeneratedCacheSave();
|
|
||||||
saveGeneratedSkinCache();
|
saveGeneratedSkinCache();
|
||||||
cache.clear();
|
cache.clear();
|
||||||
generatedSkinCache.clear();
|
generatedSkinCache.clear();
|
||||||
pendingLookups.clear();
|
pendingLookups.clear();
|
||||||
pendingGenerations.clear();
|
|
||||||
forceRefreshCooldowns.clear();
|
forceRefreshCooldowns.clear();
|
||||||
loginSkinUrls.clear();
|
loginSkinUrls.clear();
|
||||||
}
|
}
|
||||||
@@ -162,11 +145,7 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
UUID playerId = event.getPlayer().getUniqueId();
|
loginSkinUrls.remove(event.getPlayer().getUniqueId());
|
||||||
loginSkinUrls.remove(playerId);
|
|
||||||
pendingLookups.remove(playerId);
|
|
||||||
cancelScheduledLookup(playerId);
|
|
||||||
cancelRunningLookup(playerId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public SyncResult queueSync(Player player, boolean force) {
|
public SyncResult queueSync(Player player, boolean force) {
|
||||||
@@ -221,18 +200,8 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
String loginSkinUrl = loginSkinUrls.computeIfAbsent(playerId,
|
String loginSkinUrl = loginSkinUrls.computeIfAbsent(playerId,
|
||||||
ignored -> getCurrentSkinUrl(player).orElse(""));
|
ignored -> getCurrentSkinUrl(player).orElse(""));
|
||||||
String currentSkinUrl = loginSkinUrl.isEmpty() ? null : loginSkinUrl;
|
String currentSkinUrl = loginSkinUrl.isEmpty() ? null : loginSkinUrl;
|
||||||
BukkitRunnable scheduledLookup = new BukkitRunnable() {
|
Bukkit.getScheduler().runTaskLater(plugin,
|
||||||
@Override
|
() -> startLookup(playerId, playerName, currentSkinUrl, lookupGeneration), joinDelayTicks);
|
||||||
public void run() {
|
|
||||||
scheduledLookups.remove(playerId, this);
|
|
||||||
startLookup(playerId, playerName, currentSkinUrl, lookupGeneration);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
BukkitRunnable previousLookup = scheduledLookups.put(playerId, scheduledLookup);
|
|
||||||
if (previousLookup != null) {
|
|
||||||
previousLookup.cancel();
|
|
||||||
}
|
|
||||||
scheduledLookup.runTaskLater(plugin, joinDelayTicks);
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.detecting", Map.of());
|
sendPlayerNotification(playerId, "skin-bridge.notifications.detecting", Map.of());
|
||||||
return SyncResult.QUEUED;
|
return SyncResult.QUEUED;
|
||||||
}
|
}
|
||||||
@@ -272,18 +241,15 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void startLookup(UUID playerId, String playerName, String currentSkinUrl, long lookupGeneration) {
|
private void startLookup(UUID playerId, String playerName, String currentSkinUrl, long lookupGeneration) {
|
||||||
Player player = Bukkit.getPlayer(playerId);
|
if (executor.isShutdown() || lookupGeneration != configurationGeneration.get()) {
|
||||||
if (executor.isShutdown() || lookupGeneration != configurationGeneration.get()
|
|
||||||
|| !isLookupActive(playerId, lookupGeneration) || player == null || !player.isOnline()) {
|
|
||||||
pendingLookups.remove(playerId, lookupGeneration);
|
pendingLookups.remove(playerId, lookupGeneration);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
LookupKey lookupKey = new LookupKey(playerId, lookupGeneration);
|
|
||||||
try {
|
try {
|
||||||
Future<?> lookupTask = executor.submit(() -> {
|
executor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
CachedLookup resolved = resolve(playerId, playerName, currentSkinUrl);
|
CachedLookup resolved = resolve(playerId, playerName, currentSkinUrl);
|
||||||
if (lookupGeneration != configurationGeneration.get() || !isLookupActive(playerId, lookupGeneration)) {
|
if (lookupGeneration != configurationGeneration.get()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
cache.put(playerId, resolved);
|
cache.put(playerId, resolved);
|
||||||
@@ -296,9 +262,6 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
if (!isLookupActive(playerId, lookupGeneration) || exception instanceof InterruptedException) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
plugin.getLogger().warning("SkinBridge 查询 " + playerName + " 的皮肤资料失败: " + exception.getMessage());
|
plugin.getLogger().warning("SkinBridge 查询 " + playerName + " 的皮肤资料失败: " + exception.getMessage());
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -306,15 +269,8 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
pendingLookups.remove(playerId, lookupGeneration);
|
pendingLookups.remove(playerId, lookupGeneration);
|
||||||
runningLookups.remove(lookupKey);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
runningLookups.put(lookupKey, lookupTask);
|
|
||||||
if (!isLookupActive(playerId, lookupGeneration)) {
|
|
||||||
runningLookups.remove(lookupKey, lookupTask);
|
|
||||||
lookupTask.cancel(true);
|
|
||||||
executor.purge();
|
|
||||||
}
|
|
||||||
} catch (RejectedExecutionException exception) {
|
} catch (RejectedExecutionException exception) {
|
||||||
pendingLookups.remove(playerId, lookupGeneration);
|
pendingLookups.remove(playerId, lookupGeneration);
|
||||||
plugin.getLogger().warning("SkinBridge 查询队列拒绝了玩家任务: " + playerName);
|
plugin.getLogger().warning("SkinBridge 查询队列拒绝了玩家任务: " + playerName);
|
||||||
@@ -368,8 +324,18 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
if (logDetectionResults) {
|
if (logDetectionResults) {
|
||||||
plugin.getLogger().info("SkinBridge 已识别玩家 " + playerName + " 的皮肤来源: " + provider.name());
|
plugin.getLogger().info("SkinBridge 已识别玩家 " + playerName + " 的皮肤来源: " + provider.name());
|
||||||
}
|
}
|
||||||
SkinCacheStore.Key cacheKey = new SkinCacheStore.Key(matchedProfile.skinUrl(), matchedProfile.model());
|
SkinCacheKey cacheKey = new SkinCacheKey(matchedProfile.skinUrl(), matchedProfile.model());
|
||||||
GeneratedSkin generatedSkin = getOrGenerateSkin(cacheKey, currentGateway);
|
GeneratedCacheEntry generatedEntry = generatedSkinCache.get(cacheKey);
|
||||||
|
GeneratedSkin generatedSkin;
|
||||||
|
if (generatedEntry != null && !generatedEntry.hasExpired()) {
|
||||||
|
generatedSkin = generatedEntry.skin();
|
||||||
|
} else {
|
||||||
|
generatedSkinCache.remove(cacheKey);
|
||||||
|
generatedSkin = currentGateway.generateSkin(matchedProfile.skinUrl(), matchedProfile.model());
|
||||||
|
generatedSkinCache.put(cacheKey, new GeneratedCacheEntry(generatedSkin,
|
||||||
|
System.currentTimeMillis() + Duration.ofMinutes(cacheMinutes).toMillis()));
|
||||||
|
saveGeneratedSkinCache();
|
||||||
|
}
|
||||||
return cached(provider.name(), generatedSkin, State.EXTERNAL);
|
return cached(provider.name(), generatedSkin, State.EXTERNAL);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,7 +350,7 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
HttpRequest request = HttpRequest.newBuilder(requestUri)
|
HttpRequest request = HttpRequest.newBuilder(requestUri)
|
||||||
.timeout(Duration.ofSeconds(requestTimeoutSeconds))
|
.timeout(Duration.ofSeconds(requestTimeoutSeconds))
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.header("User-Agent", "EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge")
|
.header("User-Agent", "EssentialsC/" + plugin.getDescription().getVersion() + " SkinBridge")
|
||||||
.GET()
|
.GET()
|
||||||
.build();
|
.build();
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||||
@@ -481,150 +447,60 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void loadGeneratedSkinCache() {
|
private void loadGeneratedSkinCache() {
|
||||||
generatedSkinCache.putAll(cacheStore.load());
|
if (!generatedCacheFile.exists()) {
|
||||||
trimGeneratedSkinCache();
|
return;
|
||||||
|
}
|
||||||
|
FileConfiguration config = YamlConfiguration.loadConfiguration(generatedCacheFile);
|
||||||
|
ConfigurationSection entries = config.getConfigurationSection("entries");
|
||||||
|
if (entries == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
for (String id : entries.getKeys(false)) {
|
||||||
|
String path = "entries." + id;
|
||||||
|
try {
|
||||||
|
String skinUrl = config.getString(path + ".skin-url", "");
|
||||||
|
SkinModel model = SkinModel.valueOf(config.getString(path + ".model", "CLASSIC"));
|
||||||
|
long expiresAt = config.getLong(path + ".expires-at", 0L);
|
||||||
|
String value = config.getString(path + ".value", "");
|
||||||
|
String signature = config.getString(path + ".signature", "");
|
||||||
|
if (expiresAt > now && !skinUrl.isBlank() && !value.isBlank() && !signature.isBlank()) {
|
||||||
|
generatedSkinCache.put(new SkinCacheKey(skinUrl, model),
|
||||||
|
new GeneratedCacheEntry(new GeneratedSkin(value, signature), expiresAt));
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
plugin.getLogger().warning("忽略无效的 SkinBridge 缓存记录: " + id);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized void saveGeneratedSkinCache() {
|
private synchronized void saveGeneratedSkinCache() {
|
||||||
if (!generatedCacheDirty) {
|
FileConfiguration config = new YamlConfiguration();
|
||||||
return;
|
|
||||||
}
|
|
||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
||||||
trimGeneratedSkinCache();
|
generatedSkinCache.forEach((key, entry) -> {
|
||||||
if (cacheStore.save(generatedSkinCache)) {
|
String path = "entries." + cacheId(key);
|
||||||
generatedCacheDirty = false;
|
config.set(path + ".skin-url", key.skinUrl());
|
||||||
} else if (!shuttingDown) {
|
config.set(path + ".model", key.model().name());
|
||||||
scheduleGeneratedCacheSave();
|
config.set(path + ".expires-at", entry.expiresAtMillis());
|
||||||
}
|
config.set(path + ".value", entry.skin().value());
|
||||||
}
|
config.set(path + ".signature", entry.skin().signature());
|
||||||
|
});
|
||||||
private GeneratedSkin getOrGenerateSkin(SkinCacheStore.Key cacheKey, SkinBridgeGateway currentGateway) throws Exception {
|
|
||||||
SkinCacheStore.Entry cachedEntry = generatedSkinCache.get(cacheKey);
|
|
||||||
if (cachedEntry != null && !cachedEntry.hasExpired()) {
|
|
||||||
return cachedEntry.skin();
|
|
||||||
}
|
|
||||||
if (cachedEntry != null) {
|
|
||||||
generatedSkinCache.remove(cacheKey, cachedEntry);
|
|
||||||
}
|
|
||||||
|
|
||||||
CompletableFuture<GeneratedSkin> created = new CompletableFuture<>();
|
|
||||||
CompletableFuture<GeneratedSkin> running = pendingGenerations.putIfAbsent(cacheKey, created);
|
|
||||||
if (running != null) {
|
|
||||||
return awaitGeneratedSkin(running);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
GeneratedSkin generated = currentGateway.generateSkin(cacheKey.skinUrl(), cacheKey.model());
|
AtomicYamlWriter.save(config, generatedCacheFile);
|
||||||
cacheGeneratedSkin(cacheKey, generated);
|
|
||||||
created.complete(generated);
|
|
||||||
return generated;
|
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
created.completeExceptionally(exception);
|
plugin.getLogger().warning("保存 skin-cache.yml 失败: " + exception.getMessage());
|
||||||
throw exception;
|
|
||||||
} catch (Error error) {
|
|
||||||
created.completeExceptionally(error);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
pendingGenerations.remove(cacheKey, created);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private GeneratedSkin awaitGeneratedSkin(CompletableFuture<GeneratedSkin> running) throws Exception {
|
private String cacheId(SkinCacheKey key) {
|
||||||
try {
|
try {
|
||||||
return running.get();
|
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
} catch (InterruptedException exception) {
|
byte[] hash = digest.digest((key.skinUrl() + "\n" + key.model().name()).getBytes(StandardCharsets.UTF_8));
|
||||||
Thread.currentThread().interrupt();
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
|
||||||
throw exception;
|
} catch (NoSuchAlgorithmException exception) {
|
||||||
} catch (ExecutionException exception) {
|
throw new IllegalStateException("当前 Java 环境不支持 SHA-256。", exception);
|
||||||
Throwable cause = exception.getCause();
|
|
||||||
if (cause instanceof Exception nested) {
|
|
||||||
throw nested;
|
|
||||||
}
|
}
|
||||||
if (cause instanceof Error error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("MineSkin 生成任务失败。", cause);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void cacheGeneratedSkin(SkinCacheStore.Key cacheKey, GeneratedSkin generatedSkin) {
|
|
||||||
if (shuttingDown) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
generatedSkinCache.put(cacheKey, new SkinCacheStore.Entry(generatedSkin,
|
|
||||||
System.currentTimeMillis() + Duration.ofMinutes(cacheMinutes).toMillis()));
|
|
||||||
trimGeneratedSkinCache();
|
|
||||||
generatedCacheDirty = true;
|
|
||||||
scheduleGeneratedCacheSave();
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void scheduleGeneratedCacheSave() {
|
|
||||||
if (shuttingDown || generatedCacheSaveTask != null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
generatedCacheSaveTask = Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
|
|
||||||
synchronized (this) {
|
|
||||||
generatedCacheSaveTask = null;
|
|
||||||
}
|
|
||||||
saveGeneratedSkinCache();
|
|
||||||
}, 100L);
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void cancelGeneratedCacheSave() {
|
|
||||||
if (generatedCacheSaveTask != null) {
|
|
||||||
generatedCacheSaveTask.cancel();
|
|
||||||
generatedCacheSaveTask = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void trimGeneratedSkinCache() {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
|
||||||
int excessEntries = generatedSkinCache.size() - maxGeneratedCacheEntries;
|
|
||||||
if (excessEntries <= 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
generatedSkinCache.entrySet().stream()
|
|
||||||
.sorted(Comparator.comparingLong(entry -> entry.getValue().expiresAtMillis()))
|
|
||||||
.limit(excessEntries)
|
|
||||||
.map(Map.Entry::getKey)
|
|
||||||
.forEach(generatedSkinCache::remove);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isLookupActive(UUID playerId, long lookupGeneration) {
|
|
||||||
return Long.valueOf(lookupGeneration).equals(pendingLookups.get(playerId));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cancelScheduledLookup(UUID playerId) {
|
|
||||||
BukkitRunnable scheduledLookup = scheduledLookups.remove(playerId);
|
|
||||||
if (scheduledLookup != null) {
|
|
||||||
scheduledLookup.cancel();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cancelScheduledLookups() {
|
|
||||||
for (UUID playerId : List.copyOf(scheduledLookups.keySet())) {
|
|
||||||
cancelScheduledLookup(playerId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cancelRunningLookup(UUID playerId) {
|
|
||||||
runningLookups.forEach((lookupKey, lookupTask) -> {
|
|
||||||
if (lookupKey.playerId().equals(playerId) && runningLookups.remove(lookupKey, lookupTask)) {
|
|
||||||
lookupTask.cancel(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
executor.purge();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cancelRunningLookups() {
|
|
||||||
runningLookups.forEach((lookupKey, lookupTask) -> {
|
|
||||||
if (runningLookups.remove(lookupKey, lookupTask)) {
|
|
||||||
lookupTask.cancel(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
executor.purge();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<SkinProvider> loadProviders(FileConfiguration config) {
|
private List<SkinProvider> loadProviders(FileConfiguration config) {
|
||||||
@@ -674,7 +550,7 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
try {
|
try {
|
||||||
return new MineSkinGateway(httpClient, endpoint, apiKey, visibility, timeoutSeconds,
|
return new MineSkinGateway(httpClient, endpoint, apiKey, visibility, timeoutSeconds,
|
||||||
minimumSubmitIntervalMillis,
|
minimumSubmitIntervalMillis,
|
||||||
"EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge");
|
"EssentialsC/" + plugin.getDescription().getVersion() + " SkinBridge");
|
||||||
} catch (Exception | LinkageError exception) {
|
} catch (Exception | LinkageError exception) {
|
||||||
plugin.getLogger().warning("加载 MineSkin SkinBridge 适配器失败: " + exception.getMessage());
|
plugin.getLogger().warning("加载 MineSkin SkinBridge 适配器失败: " + exception.getMessage());
|
||||||
return null;
|
return null;
|
||||||
@@ -776,7 +652,13 @@ public final class SkinBridgeManager implements Listener {
|
|||||||
private record ProviderProfile(String skinUrl, SkinModel model) {
|
private record ProviderProfile(String skinUrl, SkinModel model) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private record LookupKey(UUID playerId, long generation) {
|
private record SkinCacheKey(String skinUrl, SkinModel model) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private record GeneratedCacheEntry(GeneratedSkin skin, long expiresAtMillis) {
|
||||||
|
private boolean hasExpired() {
|
||||||
|
return System.currentTimeMillis() >= expiresAtMillis;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record CachedLookup(String providerId, GeneratedSkin skin, State state, long expiresAtMillis) {
|
private record CachedLookup(String providerId, GeneratedSkin skin, State state, long expiresAtMillis) {
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.skinbridge;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
final class SkinCacheStore {
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final File cacheFile;
|
|
||||||
|
|
||||||
SkinCacheStore(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.cacheFile = new File(plugin.getDataFolder(), "skin-cache.yml");
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<Key, Entry> load() {
|
|
||||||
Map<Key, Entry> loaded = new HashMap<>();
|
|
||||||
if (!cacheFile.exists()) {
|
|
||||||
return loaded;
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration config = YamlConfiguration.loadConfiguration(cacheFile);
|
|
||||||
ConfigurationSection entries = config.getConfigurationSection("entries");
|
|
||||||
if (entries == null) {
|
|
||||||
return loaded;
|
|
||||||
}
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
for (String id : entries.getKeys(false)) {
|
|
||||||
String path = "entries." + id;
|
|
||||||
try {
|
|
||||||
String skinUrl = config.getString(path + ".skin-url", "");
|
|
||||||
SkinModel model = SkinModel.valueOf(config.getString(path + ".model", "CLASSIC"));
|
|
||||||
long expiresAt = config.getLong(path + ".expires-at", 0L);
|
|
||||||
String value = config.getString(path + ".value", "");
|
|
||||||
String signature = config.getString(path + ".signature", "");
|
|
||||||
if (expiresAt > now && !skinUrl.isBlank() && !value.isBlank() && !signature.isBlank()) {
|
|
||||||
loaded.put(new Key(skinUrl, model),
|
|
||||||
new Entry(new GeneratedSkin(value, signature), expiresAt));
|
|
||||||
}
|
|
||||||
} catch (IllegalArgumentException exception) {
|
|
||||||
plugin.getLogger().warning("忽略无效的 SkinBridge 缓存记录: " + id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return loaded;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean save(Map<Key, Entry> entries) {
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
entries.forEach((key, entry) -> {
|
|
||||||
String path = "entries." + cacheId(key);
|
|
||||||
config.set(path + ".skin-url", key.skinUrl());
|
|
||||||
config.set(path + ".model", key.model().name());
|
|
||||||
config.set(path + ".expires-at", entry.expiresAtMillis());
|
|
||||||
config.set(path + ".value", entry.skin().value());
|
|
||||||
config.set(path + ".signature", entry.skin().signature());
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(config, cacheFile);
|
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
plugin.getLogger().warning("保存 skin-cache.yml 失败: " + exception.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String cacheId(Key key) {
|
|
||||||
try {
|
|
||||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
|
||||||
byte[] hash = digest.digest((key.skinUrl() + "\n" + key.model().name())
|
|
||||||
.getBytes(StandardCharsets.UTF_8));
|
|
||||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
|
|
||||||
} catch (NoSuchAlgorithmException exception) {
|
|
||||||
throw new IllegalStateException("当前 Java 环境不支持 SHA-256。", exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
record Key(String skinUrl, SkinModel model) {
|
|
||||||
}
|
|
||||||
|
|
||||||
record Entry(GeneratedSkin skin, long expiresAtMillis) {
|
|
||||||
boolean hasExpired() {
|
|
||||||
return System.currentTimeMillis() >= expiresAtMillis;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,9 +8,12 @@ import cn.infstar.essentialsC.api.event.TeleportRequestSendEvent;
|
|||||||
import cn.infstar.essentialsC.api.event.TeleportWarmupCancelledEvent;
|
import cn.infstar.essentialsC.api.event.TeleportWarmupCancelledEvent;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportWarmupEvent;
|
import cn.infstar.essentialsC.api.event.TeleportWarmupEvent;
|
||||||
import cn.infstar.essentialsC.commands.VanishCommand;
|
import cn.infstar.essentialsC.commands.VanishCommand;
|
||||||
|
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
||||||
import net.kyori.adventure.title.Title;
|
import net.kyori.adventure.title.Title;
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.Location;
|
import org.bukkit.Location;
|
||||||
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@@ -22,6 +25,7 @@ import org.bukkit.event.player.PlayerTeleportEvent;
|
|||||||
import org.bukkit.permissions.PermissionAttachmentInfo;
|
import org.bukkit.permissions.PermissionAttachmentInfo;
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
import org.bukkit.scheduler.BukkitTask;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayDeque;
|
import java.util.ArrayDeque;
|
||||||
@@ -53,7 +57,8 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
private final Set<UUID> warmupDamagedPlayers = new HashSet<>();
|
private final Set<UUID> warmupDamagedPlayers = new HashSet<>();
|
||||||
private final Set<UUID> invulnerablePlayers = new HashSet<>();
|
private final Set<UUID> invulnerablePlayers = new HashSet<>();
|
||||||
private final Set<UUID> ignoringRequests = new HashSet<>();
|
private final Set<UUID> ignoringRequests = new HashSet<>();
|
||||||
private final TeleportStateStore stateStore;
|
private final File ignoreFile;
|
||||||
|
private final File cooldownFile;
|
||||||
private BukkitTask cleanupTask;
|
private BukkitTask cleanupTask;
|
||||||
|
|
||||||
private int timeoutSeconds;
|
private int timeoutSeconds;
|
||||||
@@ -77,11 +82,10 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
|
|
||||||
public TeleportRequestManager(EssentialsC plugin) {
|
public TeleportRequestManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.stateStore = new TeleportStateStore(plugin);
|
this.ignoreFile = new File(plugin.getDataFolder(), "teleport-ignore.yml");
|
||||||
|
this.cooldownFile = new File(plugin.getDataFolder(), "teleport-cooldowns.yml");
|
||||||
reload();
|
reload();
|
||||||
TeleportStateStore.CooldownState cooldownState = stateStore.loadCooldowns();
|
loadCooldowns();
|
||||||
sendCooldowns.putAll(cooldownState.send());
|
|
||||||
acceptCooldowns.putAll(cooldownState.accept());
|
|
||||||
cleanupTask = Bukkit.getScheduler().runTaskTimer(plugin, this::cleanupExpiredState, 1200L, 1200L);
|
cleanupTask = Bukkit.getScheduler().runTaskTimer(plugin, this::cleanupExpiredState, 1200L, 1200L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,8 +131,7 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
warmupSound = plugin.getConfig().getString("tpa.sounds.warmup", "block.note_block.banjo");
|
warmupSound = plugin.getConfig().getString("tpa.sounds.warmup", "block.note_block.banjo");
|
||||||
cancelSound = plugin.getConfig().getString("tpa.sounds.cancelled", "entity.item.break");
|
cancelSound = plugin.getConfig().getString("tpa.sounds.cancelled", "entity.item.break");
|
||||||
completeSound = plugin.getConfig().getString("tpa.sounds.complete", "entity.enderman.teleport");
|
completeSound = plugin.getConfig().getString("tpa.sounds.complete", "entity.enderman.teleport");
|
||||||
ignoringRequests.clear();
|
loadIgnoringRequests();
|
||||||
ignoringRequests.addAll(stateStore.loadIgnoringRequests());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
@@ -136,13 +139,13 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
cleanupTask.cancel();
|
cleanupTask.cancel();
|
||||||
cleanupTask = null;
|
cleanupTask = null;
|
||||||
}
|
}
|
||||||
stateStore.saveCooldowns(sendCooldowns, acceptCooldowns);
|
saveCooldowns();
|
||||||
requests.clear();
|
requests.clear();
|
||||||
sendCooldowns.clear();
|
sendCooldowns.clear();
|
||||||
acceptCooldowns.clear();
|
acceptCooldowns.clear();
|
||||||
cancelAllWarmups();
|
cancelAllWarmups();
|
||||||
clearAllInvulnerability();
|
clearAllInvulnerability();
|
||||||
stateStore.saveIgnoringRequests(ignoringRequests);
|
saveIgnoringRequests();
|
||||||
}
|
}
|
||||||
|
|
||||||
public CreateRequestResult createRequest(Player requester, Player target, TeleportRequest.Type type) {
|
public CreateRequestResult createRequest(Player requester, Player target, TeleportRequest.Type type) {
|
||||||
@@ -227,24 +230,24 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getIncomingRequesterNames(Player target, String partial) {
|
public List<String> getIncomingRequesterNames(Player target, String partial) {
|
||||||
String partialLower = partial == null ? "" : partial.toLowerCase(Locale.ROOT);
|
String partialLower = partial == null ? "" : partial.toLowerCase();
|
||||||
return requests.getOrDefault(target.getUniqueId(), new ArrayDeque<>()).stream()
|
return requests.getOrDefault(target.getUniqueId(), new ArrayDeque<>()).stream()
|
||||||
.filter(request -> !request.hasExpired())
|
.filter(request -> !request.hasExpired())
|
||||||
.map(TeleportRequest::requesterName)
|
.map(TeleportRequest::requesterName)
|
||||||
.filter(name -> name.toLowerCase(Locale.ROOT).startsWith(partialLower))
|
.filter(name -> name.toLowerCase().startsWith(partialLower))
|
||||||
.distinct()
|
.distinct()
|
||||||
.sorted(String.CASE_INSENSITIVE_ORDER)
|
.sorted(String.CASE_INSENSITIVE_ORDER)
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getOutgoingTargetNames(Player requester, String partial) {
|
public List<String> getOutgoingTargetNames(Player requester, String partial) {
|
||||||
String partialLower = partial == null ? "" : partial.toLowerCase(Locale.ROOT);
|
String partialLower = partial == null ? "" : partial.toLowerCase();
|
||||||
return requests.values().stream()
|
return requests.values().stream()
|
||||||
.flatMap(Deque::stream)
|
.flatMap(Deque::stream)
|
||||||
.filter(request -> request.requesterId().equals(requester.getUniqueId()))
|
.filter(request -> request.requesterId().equals(requester.getUniqueId()))
|
||||||
.filter(request -> !request.hasExpired())
|
.filter(request -> !request.hasExpired())
|
||||||
.map(TeleportRequest::targetName)
|
.map(TeleportRequest::targetName)
|
||||||
.filter(name -> name.toLowerCase(Locale.ROOT).startsWith(partialLower))
|
.filter(name -> name.toLowerCase().startsWith(partialLower))
|
||||||
.distinct()
|
.distinct()
|
||||||
.sorted(String.CASE_INSENSITIVE_ORDER)
|
.sorted(String.CASE_INSENSITIVE_ORDER)
|
||||||
.toList();
|
.toList();
|
||||||
@@ -332,10 +335,16 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isVanished(Player player) {
|
public boolean isVanished(Player player) {
|
||||||
return VanishCommand.isVanished(player);
|
if (VanishCommand.isVanished(player)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return player.hasMetadata("vanished") && player.getMetadata("vanished").stream()
|
||||||
|
.map(metadata -> metadata.asBoolean())
|
||||||
|
.findFirst()
|
||||||
|
.orElse(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ToggleIgnoreResult toggleIgnoringRequests(Player player) {
|
public boolean toggleIgnoringRequests(Player player) {
|
||||||
UUID uuid = player.getUniqueId();
|
UUID uuid = player.getUniqueId();
|
||||||
boolean nowIgnoring;
|
boolean nowIgnoring;
|
||||||
if (ignoringRequests.contains(uuid)) {
|
if (ignoringRequests.contains(uuid)) {
|
||||||
@@ -345,15 +354,8 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
ignoringRequests.add(uuid);
|
ignoringRequests.add(uuid);
|
||||||
nowIgnoring = true;
|
nowIgnoring = true;
|
||||||
}
|
}
|
||||||
if (!stateStore.saveIgnoringRequests(ignoringRequests)) {
|
saveIgnoringRequests();
|
||||||
if (nowIgnoring) {
|
return nowIgnoring;
|
||||||
ignoringRequests.remove(uuid);
|
|
||||||
} else {
|
|
||||||
ignoringRequests.add(uuid);
|
|
||||||
}
|
|
||||||
return ToggleIgnoreResult.SAVE_FAILED;
|
|
||||||
}
|
|
||||||
return nowIgnoring ? ToggleIgnoreResult.ENABLED : ToggleIgnoreResult.DISABLED;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void playRequestReceivedSound(Player player) {
|
public void playRequestReceivedSound(Player player) {
|
||||||
@@ -393,11 +395,11 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return exactMatch;
|
return exactMatch;
|
||||||
}
|
}
|
||||||
|
|
||||||
String playerNameLower = playerName.toLowerCase(Locale.ROOT);
|
String playerNameLower = playerName.toLowerCase();
|
||||||
return Bukkit.getOnlinePlayers().stream()
|
return Bukkit.getOnlinePlayers().stream()
|
||||||
.map(Player.class::cast)
|
.map(Player.class::cast)
|
||||||
.filter(filter)
|
.filter(filter)
|
||||||
.filter(player -> player.getName().toLowerCase(Locale.ROOT).startsWith(playerNameLower))
|
.filter(player -> player.getName().toLowerCase().startsWith(playerNameLower))
|
||||||
.findFirst();
|
.findFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -748,7 +750,7 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
placeholders.put("requester", request.requesterName());
|
placeholders.put("requester", request.requesterName());
|
||||||
placeholders.put("target", request.targetName());
|
placeholders.put("target", request.targetName());
|
||||||
placeholders.put("seconds", String.valueOf(timeoutSeconds));
|
placeholders.put("seconds", String.valueOf(timeoutSeconds));
|
||||||
placeholders.put("type", request.type().name().toLowerCase(Locale.ROOT));
|
placeholders.put("type", request.type().name().toLowerCase());
|
||||||
return placeholders;
|
return placeholders;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -813,13 +815,89 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
sendCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
sendCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
||||||
acceptCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
acceptCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
||||||
stateStore.saveCooldowns(sendCooldowns, acceptCooldowns);
|
saveCooldowns();
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum ToggleIgnoreResult {
|
private void loadCooldowns() {
|
||||||
ENABLED,
|
if (!cooldownFile.exists()) {
|
||||||
DISABLED,
|
return;
|
||||||
SAVE_FAILED
|
}
|
||||||
|
FileConfiguration cooldownConfig = YamlConfiguration.loadConfiguration(cooldownFile);
|
||||||
|
loadCooldownMap(cooldownConfig, "send", sendCooldowns);
|
||||||
|
loadCooldownMap(cooldownConfig, "accept", acceptCooldowns);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void loadCooldownMap(FileConfiguration config, String path, Map<UUID, Long> destination) {
|
||||||
|
if (!config.isConfigurationSection(path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
for (String key : config.getConfigurationSection(path).getKeys(false)) {
|
||||||
|
try {
|
||||||
|
UUID uuid = UUID.fromString(key);
|
||||||
|
long expiresAt = config.getLong(path + "." + key, 0L);
|
||||||
|
if (expiresAt > now) {
|
||||||
|
destination.put(uuid, expiresAt);
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
plugin.getLogger().warning("忽略无效的 TPA 冷却记录 UUID: " + key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveCooldowns() {
|
||||||
|
FileConfiguration cooldownConfig = new YamlConfiguration();
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
saveCooldownMap(cooldownConfig, "send", sendCooldowns, now);
|
||||||
|
saveCooldownMap(cooldownConfig, "accept", acceptCooldowns, now);
|
||||||
|
try {
|
||||||
|
AtomicYamlWriter.save(cooldownConfig, cooldownFile);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
plugin.getLogger().warning("保存 teleport-cooldowns.yml 失败: " + exception.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveCooldownMap(FileConfiguration config, String path, Map<UUID, Long> source, long now) {
|
||||||
|
source.forEach((uuid, expiresAt) -> {
|
||||||
|
if (expiresAt > now) {
|
||||||
|
config.set(path + "." + uuid, expiresAt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void loadIgnoringRequests() {
|
||||||
|
ignoringRequests.clear();
|
||||||
|
if (!ignoreFile.exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileConfiguration ignoreConfig = YamlConfiguration.loadConfiguration(ignoreFile);
|
||||||
|
if (!ignoreConfig.isConfigurationSection("ignored")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String key : ignoreConfig.getConfigurationSection("ignored").getKeys(false)) {
|
||||||
|
if (!ignoreConfig.getBoolean("ignored." + key, false)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ignoringRequests.add(UUID.fromString(key));
|
||||||
|
} catch (IllegalArgumentException ignored) {
|
||||||
|
plugin.getLogger().warning("忽略无效的 TPA 忽略记录 UUID: " + key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveIgnoringRequests() {
|
||||||
|
FileConfiguration ignoreConfig = new YamlConfiguration();
|
||||||
|
for (UUID uuid : ignoringRequests) {
|
||||||
|
ignoreConfig.set("ignored." + uuid, true);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
AtomicYamlWriter.save(ignoreConfig, ignoreFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("保存 teleport-ignore.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum CreateRequestStatus {
|
public enum CreateRequestStatus {
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.teleport;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
final class TeleportStateStore {
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final File cooldownFile;
|
|
||||||
private final File ignoreFile;
|
|
||||||
private boolean cooldownWritable = true;
|
|
||||||
private boolean ignoreWritable = true;
|
|
||||||
|
|
||||||
TeleportStateStore(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.cooldownFile = new File(plugin.getDataFolder(), "teleport-cooldowns.yml");
|
|
||||||
this.ignoreFile = new File(plugin.getDataFolder(), "teleport-ignore.yml");
|
|
||||||
}
|
|
||||||
|
|
||||||
CooldownState loadCooldowns() {
|
|
||||||
Map<UUID, Long> send = new HashMap<>();
|
|
||||||
Map<UUID, Long> accept = new HashMap<>();
|
|
||||||
if (!cooldownFile.exists()) {
|
|
||||||
return new CooldownState(send, accept);
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
try {
|
|
||||||
config.load(cooldownFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
cooldownWritable = false;
|
|
||||||
plugin.getLogger().severe("加载 teleport-cooldowns.yml 失败,已禁止覆盖原文件: "
|
|
||||||
+ exception.getMessage());
|
|
||||||
return new CooldownState(send, accept);
|
|
||||||
}
|
|
||||||
loadCooldownMap(config, "send", send);
|
|
||||||
loadCooldownMap(config, "accept", accept);
|
|
||||||
return new CooldownState(send, accept);
|
|
||||||
}
|
|
||||||
|
|
||||||
void saveCooldowns(Map<UUID, Long> send, Map<UUID, Long> accept) {
|
|
||||||
if (!cooldownWritable) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
saveCooldownMap(config, "send", send, now);
|
|
||||||
saveCooldownMap(config, "accept", accept, now);
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(config, cooldownFile);
|
|
||||||
} catch (Exception exception) {
|
|
||||||
plugin.getLogger().warning("保存 teleport-cooldowns.yml 失败: " + exception.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<UUID> loadIgnoringRequests() {
|
|
||||||
Set<UUID> ignoredPlayers = new HashSet<>();
|
|
||||||
if (!ignoreFile.exists()) {
|
|
||||||
return ignoredPlayers;
|
|
||||||
}
|
|
||||||
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
try {
|
|
||||||
config.load(ignoreFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
ignoreWritable = false;
|
|
||||||
plugin.getLogger().severe("加载 teleport-ignore.yml 失败,已禁止覆盖原文件: "
|
|
||||||
+ exception.getMessage());
|
|
||||||
return ignoredPlayers;
|
|
||||||
}
|
|
||||||
ConfigurationSection ignored = config.getConfigurationSection("ignored");
|
|
||||||
if (ignored == null) {
|
|
||||||
return ignoredPlayers;
|
|
||||||
}
|
|
||||||
for (String key : ignored.getKeys(false)) {
|
|
||||||
if (!ignored.getBoolean(key, false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
ignoredPlayers.add(UUID.fromString(key));
|
|
||||||
} catch (IllegalArgumentException exception) {
|
|
||||||
plugin.getLogger().warning("忽略无效的 TPA 忽略记录 UUID: " + key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ignoredPlayers;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean saveIgnoringRequests(Set<UUID> ignoredPlayers) {
|
|
||||||
if (!ignoreWritable) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
YamlConfiguration config = new YamlConfiguration();
|
|
||||||
for (UUID playerId : ignoredPlayers) {
|
|
||||||
config.set("ignored." + playerId, true);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(config, ignoreFile);
|
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
plugin.getLogger().warning("保存 teleport-ignore.yml 失败: " + exception.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadCooldownMap(YamlConfiguration config, String path, Map<UUID, Long> destination) {
|
|
||||||
ConfigurationSection section = config.getConfigurationSection(path);
|
|
||||||
if (section == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
for (String key : section.getKeys(false)) {
|
|
||||||
try {
|
|
||||||
UUID playerId = UUID.fromString(key);
|
|
||||||
long expiresAt = section.getLong(key, 0L);
|
|
||||||
if (expiresAt > now) {
|
|
||||||
destination.put(playerId, expiresAt);
|
|
||||||
}
|
|
||||||
} catch (IllegalArgumentException exception) {
|
|
||||||
plugin.getLogger().warning("忽略无效的 TPA 冷却记录 UUID: " + key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void saveCooldownMap(YamlConfiguration config, String path, Map<UUID, Long> source, long now) {
|
|
||||||
source.forEach((playerId, expiresAt) -> {
|
|
||||||
if (expiresAt > now) {
|
|
||||||
config.set(path + "." + playerId, expiresAt);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
record CooldownState(Map<UUID, Long> send, Map<UUID, Long> accept) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
package cn.infstar.essentialsC.tpsbar;
|
package cn.infstar.essentialsC.tpsbar;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
|
||||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
|
import org.bukkit.ChatColor;
|
||||||
import org.bukkit.boss.BarColor;
|
import org.bukkit.boss.BarColor;
|
||||||
import org.bukkit.boss.BarStyle;
|
import org.bukkit.boss.BarStyle;
|
||||||
import org.bukkit.boss.BossBar;
|
import org.bukkit.boss.BossBar;
|
||||||
@@ -27,8 +26,6 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public final class TpsBarManager implements Listener, TpsBarService {
|
public final class TpsBarManager implements Listener, TpsBarService {
|
||||||
|
|
||||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
|
||||||
private static final PlainTextComponentSerializer PLAIN_TEXT = PlainTextComponentSerializer.plainText();
|
|
||||||
private static final double MAX_TPS = 20.0D;
|
private static final double MAX_TPS = 20.0D;
|
||||||
private static final int UPDATE_INTERVAL_TICKS = 20;
|
private static final int UPDATE_INTERVAL_TICKS = 20;
|
||||||
private static final BarStyle BAR_STYLE = BarStyle.SEGMENTED_20;
|
private static final BarStyle BAR_STYLE = BarStyle.SEGMENTED_20;
|
||||||
@@ -285,11 +282,11 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String buildTitle(double tps, double mspt, int ping) {
|
private String buildTitle(double tps, double mspt, int ping) {
|
||||||
return applyPlaceholders(titleFormat, Map.of(
|
return ChatColor.translateAlternateColorCodes('&', applyPlaceholders(titleFormat, Map.of(
|
||||||
"tps_1m", formatDouble(tps),
|
"tps_1m", formatDouble(tps),
|
||||||
"mspt", formatDouble(mspt),
|
"mspt", formatDouble(mspt),
|
||||||
"ping", Integer.toString(ping)
|
"ping", Integer.toString(ping)
|
||||||
));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private BarColor resolveBarColor(double tps, double mspt, int ping) {
|
private BarColor resolveBarColor(double tps, double mspt, int ping) {
|
||||||
@@ -320,7 +317,7 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String prefixed(String message) {
|
private String prefixed(String message) {
|
||||||
return EssentialsC.getLangManager().getPrefix() + message;
|
return EssentialsC.getLangManager().getPrefix() + ChatColor.translateAlternateColorCodes('&', message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String applyPlaceholders(String text, Map<String, String> placeholders) {
|
private String applyPlaceholders(String text, Map<String, String> placeholders) {
|
||||||
@@ -332,7 +329,7 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String stripColor(String message) {
|
private String stripColor(String message) {
|
||||||
return PLAIN_TEXT.serialize(LEGACY_SECTION.deserialize(message == null ? "" : message));
|
return ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', message));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String formatDouble(double value) {
|
private String formatDouble(double value) {
|
||||||
|
|||||||
@@ -22,11 +22,7 @@ public final class AtomicYamlWriter {
|
|||||||
Files.createDirectories(parent);
|
Files.createDirectories(parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
String temporaryPrefix = targetFile.getName();
|
Path temporary = Files.createTempFile(parent, targetFile.getName(), ".tmp");
|
||||||
if (temporaryPrefix.length() < 3) {
|
|
||||||
temporaryPrefix = (temporaryPrefix + "___").substring(0, 3);
|
|
||||||
}
|
|
||||||
Path temporary = Files.createTempFile(parent, temporaryPrefix, ".tmp");
|
|
||||||
try {
|
try {
|
||||||
Files.writeString(temporary, configuration.saveToString(), StandardCharsets.UTF_8);
|
Files.writeString(temporary, configuration.saveToString(), StandardCharsets.UTF_8);
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# EssentialsC 主配置
|
# EssentialsC 主配置
|
||||||
# 其他配置:modules.yml、blocks-menu.yml
|
# 其他配置:modules.yml、maintenance.yml、blocks-menu.yml
|
||||||
# 消息与颜色:lang/<语言>.yml
|
# 消息与颜色:lang/<语言>.yml
|
||||||
# 修改后使用 /essc reload 重载;命令注册状态发生变化时建议重启服务器。
|
# 修改后使用 /essc reload 重载;命令注册状态发生变化时建议重启服务器。
|
||||||
|
|
||||||
@@ -17,17 +17,23 @@ admin-mode:
|
|||||||
actionbar:
|
actionbar:
|
||||||
interval-ticks: 40
|
interval-ticks: 40
|
||||||
|
|
||||||
|
# JEI 配方同步修复;是否加载由 modules.yml 控制。
|
||||||
|
jei-sync:
|
||||||
|
# 玩家加入后延迟多少 tick 检测客户端品牌。
|
||||||
|
brand-check-delay-ticks: 20
|
||||||
|
send-player-message: true
|
||||||
|
|
||||||
# 生物掉落
|
# 生物掉落
|
||||||
mob-drops:
|
mob-drops:
|
||||||
enderman:
|
enderman:
|
||||||
# 控制该生物死亡时是否掉落物品(经验值正常掉落);当前仅支持末影人。
|
# 允许末影人掉落搬运的方块。
|
||||||
allow-drops: true
|
allow-drops: true
|
||||||
|
|
||||||
# TPA 传送请求
|
# TPA 传送请求,行为参考 HuskHomes。
|
||||||
tpa:
|
tpa:
|
||||||
# 请求有效时间,单位为秒。
|
# 请求有效时间,单位为秒。
|
||||||
timeout-seconds: 60
|
timeout-seconds: 60
|
||||||
# 每名接收者最多保留的待处理请求数;超出时移除最早请求。
|
# 每名接收者最多保留的待处理请求数;参考 EssentialsX,超出时移除最早请求。
|
||||||
max-pending-requests: 5
|
max-pending-requests: 5
|
||||||
|
|
||||||
# 位置规则
|
# 位置规则
|
||||||
@@ -73,8 +79,6 @@ skin-bridge:
|
|||||||
join-delay-ticks: 20
|
join-delay-ticks: 20
|
||||||
# 检测结果与生成皮肤的内存缓存时间,单位为分钟。
|
# 检测结果与生成皮肤的内存缓存时间,单位为分钟。
|
||||||
cache-minutes: 120
|
cache-minutes: 120
|
||||||
# 持久化 MineSkin 纹理缓存的最大条目数,超出时优先清理最早过期的记录。
|
|
||||||
max-generated-cache-entries: 500
|
|
||||||
# 强制刷新同一玩家皮肤的冷却时间,单位为秒。
|
# 强制刷新同一玩家皮肤的冷却时间,单位为秒。
|
||||||
force-refresh-cooldown-seconds: 30
|
force-refresh-cooldown-seconds: 30
|
||||||
# 仅当 Provider 纹理与玩家登录时携带的纹理一致时,才确认其来自该皮肤站。
|
# 仅当 Provider 纹理与玩家登录时携带的纹理一致时,才确认其来自该皮肤站。
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
# English language file
|
# English language file
|
||||||
# MiniMessage format with green success, red errors, and gray details.
|
# HuskHomes-inspired style: MiniMessage, green success, red errors, gray details.
|
||||||
|
|
||||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
prefix: ''
|
||||||
|
|
||||||
messages:
|
messages:
|
||||||
no-permission: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to use this command.</#FF7E5E> <gray>Required: {permission}</gray>'
|
no-permission: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to use this command.</#FF7E5E> <gray>Required: {permission}</gray>'
|
||||||
player-only: '<#FF3300>Error:</#FF3300> <#FF7E5E>This command can only be run by players.</#FF7E5E>'
|
player-only: '<#FF3300>Error:</#FF3300> <#FF7E5E>This command can only be run by players.</#FF7E5E>'
|
||||||
console-name: 'Console'
|
|
||||||
config-reloaded: '<#00FB9A>Configuration reloaded.</#00FB9A>'
|
config-reloaded: '<#00FB9A>Configuration reloaded.</#00FB9A>'
|
||||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
||||||
paper-version: '<gray>Running on Paper {version}</gray>'
|
paper-version: '<gray>Running on Paper {version}</gray>'
|
||||||
@@ -21,18 +20,14 @@ messages:
|
|||||||
suicide-message: '<#FF7E5E>{player} died by suicide.</#FF7E5E>'
|
suicide-message: '<#FF7E5E>{player} died by suicide.</#FF7E5E>'
|
||||||
fly-enabled: '<#00FB9A>Flight mode enabled.</#00FB9A>'
|
fly-enabled: '<#00FB9A>Flight mode enabled.</#00FB9A>'
|
||||||
fly-disabled: '<#FF7E5E>Flight mode disabled.</#FF7E5E>'
|
fly-disabled: '<#FF7E5E>Flight mode disabled.</#FF7E5E>'
|
||||||
fly-permission-removed: '<#FF7E5E>Your flight permission was removed, so flight mode was disabled.</#FF7E5E>'
|
|
||||||
nightvision-enabled: '<#00FB9A>Night vision enabled.</#00FB9A>'
|
nightvision-enabled: '<#00FB9A>Night vision enabled.</#00FB9A>'
|
||||||
nightvision-disabled: '<#FF7E5E>Night vision disabled.</#FF7E5E>'
|
nightvision-disabled: '<#FF7E5E>Night vision disabled.</#FF7E5E>'
|
||||||
nightvision-permission-removed: '<#FF7E5E>Your night vision permission was removed, so night vision was disabled.</#FF7E5E>'
|
|
||||||
nightvision-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /nightvision [on|off|toggle]</#FF7E5E>'
|
nightvision-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /nightvision [on|off|toggle]</#FF7E5E>'
|
||||||
glow-enabled: '<#00FB9A>Glowing enabled.</#00FB9A>'
|
glow-enabled: '<#00FB9A>Glowing enabled.</#00FB9A>'
|
||||||
glow-disabled: '<#FF7E5E>Glowing disabled.</#FF7E5E>'
|
glow-disabled: '<#FF7E5E>Glowing disabled.</#FF7E5E>'
|
||||||
glow-permission-removed: '<#FF7E5E>Your glowing permission was removed, so glowing was disabled.</#FF7E5E>'
|
|
||||||
glow-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /glow [on|off|toggle]</#FF7E5E>'
|
glow-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /glow [on|off|toggle]</#FF7E5E>'
|
||||||
vanish-enabled: '<#00FB9A>You are now vanished.</#00FB9A>'
|
vanish-enabled: '<#00FB9A>You are now vanished.</#00FB9A>'
|
||||||
vanish-disabled: '<#FF7E5E>You are no longer vanished.</#FF7E5E>'
|
vanish-disabled: '<#FF7E5E>You are no longer vanished.</#FF7E5E>'
|
||||||
vanish-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save vanish state; no changes were applied.</#FF7E5E>'
|
|
||||||
vanish-permission-removed: '<#FFC43B>Your vanish permission was removed, so vanish mode was disabled.</#FFC43B>'
|
vanish-permission-removed: '<#FFC43B>Your vanish permission was removed, so vanish mode was disabled.</#FFC43B>'
|
||||||
seen-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
seen-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
||||||
seen-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
seen-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
||||||
@@ -50,11 +45,9 @@ messages:
|
|||||||
heal-self: '<#00FB9A>Your health and hunger have been restored.</#00FB9A>'
|
heal-self: '<#00FB9A>Your health and hunger have been restored.</#00FB9A>'
|
||||||
heal-other: '<#00FB9A>You healed <bold>{player}</bold>.</#00FB9A>'
|
heal-other: '<#00FB9A>You healed <bold>{player}</bold>.</#00FB9A>'
|
||||||
heal-by-other: '<#00FB9A>You were healed by <bold>{admin}</bold>.</#00FB9A>'
|
heal-by-other: '<#00FB9A>You were healed by <bold>{admin}</bold>.</#00FB9A>'
|
||||||
heal-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /heal [player]</#FF7E5E>'
|
|
||||||
feed-self: '<#00FB9A>Your hunger has been restored.</#00FB9A>'
|
feed-self: '<#00FB9A>Your hunger has been restored.</#00FB9A>'
|
||||||
feed-other: '<#00FB9A>You fed <bold>{player}</bold>.</#00FB9A>'
|
feed-other: '<#00FB9A>You fed <bold>{player}</bold>.</#00FB9A>'
|
||||||
feed-by-other: '<#00FB9A>You were fed by <bold>{admin}</bold>.</#00FB9A>'
|
feed-by-other: '<#00FB9A>You were fed by <bold>{admin}</bold>.</#00FB9A>'
|
||||||
feed-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /feed [player]</#FF7E5E>'
|
|
||||||
repair-hand-success: '<#00FB9A>Repaired the item in your hand.</#00FB9A>'
|
repair-hand-success: '<#00FB9A>Repaired the item in your hand.</#00FB9A>'
|
||||||
repair-all-success: '<#00FB9A>Repaired <bold>{count}</bold> item(s).</#00FB9A>'
|
repair-all-success: '<#00FB9A>Repaired <bold>{count}</bold> item(s).</#00FB9A>'
|
||||||
repair-not-damaged: '<#FF3300>Error:</#FF3300> <#FF7E5E>This item is not damaged.</#FF7E5E>'
|
repair-not-damaged: '<#FF3300>Error:</#FF3300> <#FF7E5E>This item is not damaged.</#FF7E5E>'
|
||||||
@@ -66,8 +59,9 @@ messages:
|
|||||||
mobdrop-toggled: '<#00FB9A>Enderman drops are now {status}.</#00FB9A>'
|
mobdrop-toggled: '<#00FB9A>Enderman drops are now {status}.</#00FB9A>'
|
||||||
shulkerbox-nested: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot put a shulker box inside another shulker box.</#FF7E5E>'
|
shulkerbox-nested: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot put a shulker box inside another shulker box.</#FF7E5E>'
|
||||||
shulkerbox-unstack-first: '<#FF3300>Error:</#FF3300> <#FF7E5E>Please unstack the shulker box before quick opening it.</#FF7E5E>'
|
shulkerbox-unstack-first: '<#FF3300>Error:</#FF3300> <#FF7E5E>Please unstack the shulker box before quick opening it.</#FF7E5E>'
|
||||||
shulkerbox-open-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to open the shulker box. Please try again.</#FF7E5E>'
|
jei-sync-fabric: '<#00FB9A>Synchronizing recipes for your <bold>Fabric</bold> client…</#00FB9A>'
|
||||||
shulkerbox-session-invalid: '<#FF3300>Error:</#FF3300> <#FF7E5E>The shulker box session became invalid. Saving was stopped to prevent item duplication.</#FF7E5E>'
|
jei-sync-neoforge: '<#00FB9A>Synchronizing recipes for your <bold>NeoForge</bold> client…</#00FB9A>'
|
||||||
|
|
||||||
help:
|
help:
|
||||||
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>Command Help</gray>'
|
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>Command Help</gray>'
|
||||||
version: '<gray>Plugin version: <white>{version}</white></gray>'
|
version: '<gray>Plugin version: <white>{version}</white></gray>'
|
||||||
@@ -76,8 +70,6 @@ help:
|
|||||||
footer: '<gray>Each command requires the corresponding permission.</gray>'
|
footer: '<gray>Each command requires the corresponding permission.</gray>'
|
||||||
|
|
||||||
commands:
|
commands:
|
||||||
reload: '<white>/essc reload</white> <gray>- Reload plugin configuration</gray>'
|
|
||||||
version: '<white>/essc version</white> <gray>- View plugin and server versions</gray>'
|
|
||||||
workbench: '<white>/workbench</white> <gray>- Open a crafting table</gray>'
|
workbench: '<white>/workbench</white> <gray>- Open a crafting table</gray>'
|
||||||
anvil: '<white>/anvil</white> <gray>- Open an anvil</gray>'
|
anvil: '<white>/anvil</white> <gray>- Open an anvil</gray>'
|
||||||
enchantingtable: '<white>/enchantingtable</white> <gray>- Open an enchanting table</gray>'
|
enchantingtable: '<white>/enchantingtable</white> <gray>- Open an enchanting table</gray>'
|
||||||
@@ -93,10 +85,10 @@ help:
|
|||||||
fly: '<white>/fly</white> <gray>- Toggle flight mode</gray>'
|
fly: '<white>/fly</white> <gray>- Toggle flight mode</gray>'
|
||||||
nightvision: '<white>/nightvision</white> <gray>- Toggle night vision</gray>'
|
nightvision: '<white>/nightvision</white> <gray>- Toggle night vision</gray>'
|
||||||
glow: '<white>/glow</white> <gray>- Toggle glowing</gray>'
|
glow: '<white>/glow</white> <gray>- Toggle glowing</gray>'
|
||||||
heal: '<white>/heal [player]</white> <gray>- Restore health and hunger</gray>'
|
heal: '<white>/heal</white> <gray>- Restore health and hunger</gray>'
|
||||||
vanish: '<white>/vanish</white> <gray>- Toggle vanish mode</gray>'
|
vanish: '<white>/vanish</white> <gray>- Toggle vanish mode</gray>'
|
||||||
seen: '<white>/seen [player]</white> <gray>- View player information</gray>'
|
seen: '<white>/seen</white> <gray>- View player information</gray>'
|
||||||
feed: '<white>/feed [player]</white> <gray>- Restore hunger</gray>'
|
feed: '<white>/feed</white> <gray>- Restore hunger</gray>'
|
||||||
repair: '<white>/repair</white> <gray>- Repair held or all items</gray>'
|
repair: '<white>/repair</white> <gray>- Repair held or all items</gray>'
|
||||||
tpa: '<white>/tpa [player]</white> <gray>- Request to teleport to a player</gray>'
|
tpa: '<white>/tpa [player]</white> <gray>- Request to teleport to a player</gray>'
|
||||||
tpahere: '<white>/tpahere [player]</white> <gray>- Request a player teleport to you</gray>'
|
tpahere: '<white>/tpahere [player]</white> <gray>- Request a player teleport to you</gray>'
|
||||||
@@ -107,6 +99,7 @@ help:
|
|||||||
skin: '<white>/essc skin [status|refresh] [player]</white> <gray>- View or refresh SkinBridge status</gray>'
|
skin: '<white>/essc skin [status|refresh] [player]</white> <gray>- View or refresh SkinBridge status</gray>'
|
||||||
admin: '<white>/essc admin</white> <gray>- Toggle admin mode</gray>'
|
admin: '<white>/essc admin</white> <gray>- Toggle admin mode</gray>'
|
||||||
tpsbar: '<white>/tpsbar [player]</white> <gray>- Toggle TPS boss bar</gray>'
|
tpsbar: '<white>/tpsbar [player]</white> <gray>- Toggle TPS boss bar</gray>'
|
||||||
|
maintenance: '<white>/maintenance [on|off|status|reload|add|remove|list]</white> <gray>- Manage maintenance mode</gray>'
|
||||||
|
|
||||||
tpa:
|
tpa:
|
||||||
messages:
|
messages:
|
||||||
@@ -145,7 +138,6 @@ tpa:
|
|||||||
teleport-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Teleportation could not be completed. Please try again.</#FF7E5E>'
|
teleport-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Teleportation could not be completed. Please try again.</#FF7E5E>'
|
||||||
ignore-enabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>ignoring</#00FB9A></bold> <#00FB9A>incoming teleport requests.</#00FB9A>'
|
ignore-enabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>ignoring</#00FB9A></bold> <#00FB9A>incoming teleport requests.</#00FB9A>'
|
||||||
ignore-disabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>listening</#00FB9A></bold> <#00FB9A>to incoming teleport requests.</#00FB9A>'
|
ignore-disabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>listening</#00FB9A></bold> <#00FB9A>to incoming teleport requests.</#00FB9A>'
|
||||||
ignore-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save the teleport request ignore state; no changes were applied.</#FF7E5E>'
|
|
||||||
ignore-notification: '<gray>You are currently ignoring teleport requests.</gray>'
|
ignore-notification: '<gray>You are currently ignoring teleport requests.</gray>'
|
||||||
tpaall-sent: '<#00FB9A>You sent a teleport request to every player asking them to teleport to you.</#00FB9A>'
|
tpaall-sent: '<#00FB9A>You sent a teleport request to every player asking them to teleport to you.</#00FB9A>'
|
||||||
tpaall-no-targets: '<#FF3300>Error:</#FF3300> <#FF7E5E>There are no other players online.</#FF7E5E>'
|
tpaall-no-targets: '<#FF3300>Error:</#FF3300> <#FF7E5E>There are no other players online.</#FF7E5E>'
|
||||||
@@ -258,3 +250,24 @@ mobdrops-menu:
|
|||||||
name: '<#00FB9A>Enderman Drops</#00FB9A>'
|
name: '<#00FB9A>Enderman Drops</#00FB9A>'
|
||||||
status: '<gray>Current status: {status}</gray>'
|
status: '<gray>Current status: {status}</gray>'
|
||||||
toggle: '<gray>Click to toggle</gray>'
|
toggle: '<gray>Click to toggle</gray>'
|
||||||
|
|
||||||
|
maintenance:
|
||||||
|
status:
|
||||||
|
enabled: '<#FF7E5E>Enabled</#FF7E5E>'
|
||||||
|
disabled: '<#00FB9A>Disabled</#00FB9A>'
|
||||||
|
address-hidden: 'hidden'
|
||||||
|
messages:
|
||||||
|
enabled: '<#00FB9A>Maintenance mode enabled.</#00FB9A>'
|
||||||
|
disabled: '<#FF7E5E>Maintenance mode disabled.</#FF7E5E>'
|
||||||
|
reloaded: '<#00FB9A>Maintenance configuration reloaded.</#00FB9A>'
|
||||||
|
status: '<gray>Maintenance mode status: {status} | Whitelist: <white>{whitelist_count}</white></gray>'
|
||||||
|
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance [on|off|status|reload|add|remove|list]</#FF7E5E>'
|
||||||
|
add-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance add [player|uuid]</#FF7E5E>'
|
||||||
|
remove-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance remove [player|uuid]</#FF7E5E>'
|
||||||
|
whitelist-added: '<#00FB9A>Added {player} to the maintenance whitelist.</#00FB9A>'
|
||||||
|
whitelist-removed: '<#00FB9A>Removed {player} from the maintenance whitelist.</#00FB9A>'
|
||||||
|
whitelist-exists: '<#FFC43B>{player} is already on the maintenance whitelist.</#FFC43B>'
|
||||||
|
whitelist-missing: '<#FF3300>Error:</#FF3300> <#FF7E5E>{player} is not on the maintenance whitelist.</#FF7E5E>'
|
||||||
|
whitelist-empty: '<gray>The maintenance whitelist is empty.</gray>'
|
||||||
|
whitelist-list: '<gray>Maintenance whitelist ({count}): <white>{entries}</white></gray>'
|
||||||
|
login-blocked: '<#FFC43B>{player} was blocked by maintenance mode.</#FFC43B> <gray>UUID: {uuid} | IP: {address}</gray>'
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
# 简体中文语言文件
|
# 简体中文语言文件
|
||||||
# 支持 MiniMessage 格式,默认使用绿色成功、红色错误和灰色说明。
|
# 文本风格参考 HuskHomes:MiniMessage、绿色成功、红色错误、灰色说明。
|
||||||
|
|
||||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
prefix: ''
|
||||||
|
|
||||||
messages:
|
messages:
|
||||||
no-permission: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限执行此命令.</#FF7E5E> <gray>需要权限: {permission}</gray>'
|
no-permission: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限执行此命令.</#FF7E5E> <gray>需要权限: {permission}</gray>'
|
||||||
player-only: '<#FF3300>错误:</#FF3300> <#FF7E5E>此命令只能由玩家执行.</#FF7E5E>'
|
player-only: '<#FF3300>错误:</#FF3300> <#FF7E5E>此命令只能由玩家执行.</#FF7E5E>'
|
||||||
console-name: '控制台'
|
|
||||||
config-reloaded: '<#00FB9A>配置已重载.</#00FB9A>'
|
config-reloaded: '<#00FB9A>配置已重载.</#00FB9A>'
|
||||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
||||||
paper-version: '<gray>当前运行于 Paper {version}</gray>'
|
paper-version: '<gray>当前运行于 Paper {version}</gray>'
|
||||||
@@ -21,18 +20,14 @@ messages:
|
|||||||
suicide-message: '<#FF7E5E>{player} 自杀了.</#FF7E5E>'
|
suicide-message: '<#FF7E5E>{player} 自杀了.</#FF7E5E>'
|
||||||
fly-enabled: '<#00FB9A>飞行模式已开启.</#00FB9A>'
|
fly-enabled: '<#00FB9A>飞行模式已开启.</#00FB9A>'
|
||||||
fly-disabled: '<#FF7E5E>飞行模式已关闭.</#FF7E5E>'
|
fly-disabled: '<#FF7E5E>飞行模式已关闭.</#FF7E5E>'
|
||||||
fly-permission-removed: '<#FF7E5E>你的飞行权限已被移除,飞行模式已关闭.</#FF7E5E>'
|
|
||||||
nightvision-enabled: '<#00FB9A>夜视已开启.</#00FB9A>'
|
nightvision-enabled: '<#00FB9A>夜视已开启.</#00FB9A>'
|
||||||
nightvision-disabled: '<#FF7E5E>夜视已关闭.</#FF7E5E>'
|
nightvision-disabled: '<#FF7E5E>夜视已关闭.</#FF7E5E>'
|
||||||
nightvision-permission-removed: '<#FF7E5E>你的夜视权限已被移除,夜视已关闭.</#FF7E5E>'
|
|
||||||
nightvision-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /nightvision [on|off|toggle]</#FF7E5E>'
|
nightvision-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /nightvision [on|off|toggle]</#FF7E5E>'
|
||||||
glow-enabled: '<#00FB9A>发光已开启.</#00FB9A>'
|
glow-enabled: '<#00FB9A>发光已开启.</#00FB9A>'
|
||||||
glow-disabled: '<#FF7E5E>发光已关闭.</#FF7E5E>'
|
glow-disabled: '<#FF7E5E>发光已关闭.</#FF7E5E>'
|
||||||
glow-permission-removed: '<#FF7E5E>你的发光权限已被移除,发光已关闭.</#FF7E5E>'
|
|
||||||
glow-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /glow [on|off|toggle]</#FF7E5E>'
|
glow-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /glow [on|off|toggle]</#FF7E5E>'
|
||||||
vanish-enabled: '<#00FB9A>你已进入隐身模式.</#00FB9A>'
|
vanish-enabled: '<#00FB9A>你已进入隐身模式.</#00FB9A>'
|
||||||
vanish-disabled: '<#FF7E5E>你已退出隐身模式.</#FF7E5E>'
|
vanish-disabled: '<#FF7E5E>你已退出隐身模式.</#FF7E5E>'
|
||||||
vanish-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存隐身状态,本次操作未生效.</#FF7E5E>'
|
|
||||||
vanish-permission-removed: '<#FFC43B>你的隐身权限已被移除,隐身模式已自动关闭.</#FFC43B>'
|
vanish-permission-removed: '<#FFC43B>你的隐身权限已被移除,隐身模式已自动关闭.</#FFC43B>'
|
||||||
seen-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
seen-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
||||||
seen-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
seen-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
||||||
@@ -50,11 +45,9 @@ messages:
|
|||||||
heal-self: '<#00FB9A>你的生命值和饥饿值已恢复.</#00FB9A>'
|
heal-self: '<#00FB9A>你的生命值和饥饿值已恢复.</#00FB9A>'
|
||||||
heal-other: '<#00FB9A>你已治疗玩家 <bold>{player}</bold>.</#00FB9A>'
|
heal-other: '<#00FB9A>你已治疗玩家 <bold>{player}</bold>.</#00FB9A>'
|
||||||
heal-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 治疗了你.</#00FB9A>'
|
heal-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 治疗了你.</#00FB9A>'
|
||||||
heal-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /heal [玩家]</#FF7E5E>'
|
|
||||||
feed-self: '<#00FB9A>你的饥饿值已恢复.</#00FB9A>'
|
feed-self: '<#00FB9A>你的饥饿值已恢复.</#00FB9A>'
|
||||||
feed-other: '<#00FB9A>你已喂饱玩家 <bold>{player}</bold>.</#00FB9A>'
|
feed-other: '<#00FB9A>你已喂饱玩家 <bold>{player}</bold>.</#00FB9A>'
|
||||||
feed-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 喂饱了你.</#00FB9A>'
|
feed-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 喂饱了你.</#00FB9A>'
|
||||||
feed-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /feed [玩家]</#FF7E5E>'
|
|
||||||
repair-hand-success: '<#00FB9A>手中物品已修复.</#00FB9A>'
|
repair-hand-success: '<#00FB9A>手中物品已修复.</#00FB9A>'
|
||||||
repair-all-success: '<#00FB9A>已修复 <bold>{count}</bold> 个物品.</#00FB9A>'
|
repair-all-success: '<#00FB9A>已修复 <bold>{count}</bold> 个物品.</#00FB9A>'
|
||||||
repair-not-damaged: '<#FF3300>错误:</#FF3300> <#FF7E5E>该物品没有损坏.</#FF7E5E>'
|
repair-not-damaged: '<#FF3300>错误:</#FF3300> <#FF7E5E>该物品没有损坏.</#FF7E5E>'
|
||||||
@@ -66,8 +59,9 @@ messages:
|
|||||||
mobdrop-toggled: '<#00FB9A>末影人掉落已切换为 {status}.</#00FB9A>'
|
mobdrop-toggled: '<#00FB9A>末影人掉落已切换为 {status}.</#00FB9A>'
|
||||||
shulkerbox-nested: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能将潜影盒放入另一个潜影盒.</#FF7E5E>'
|
shulkerbox-nested: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能将潜影盒放入另一个潜影盒.</#FF7E5E>'
|
||||||
shulkerbox-unstack-first: '<#FF3300>错误:</#FF3300> <#FF7E5E>请先将潜影盒拆分为单个后再快捷打开.</#FF7E5E>'
|
shulkerbox-unstack-first: '<#FF3300>错误:</#FF3300> <#FF7E5E>请先将潜影盒拆分为单个后再快捷打开.</#FF7E5E>'
|
||||||
shulkerbox-open-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒打开失败,请稍后重试.</#FF7E5E>'
|
jei-sync-fabric: '<#00FB9A>正在为 <bold>Fabric</bold> 客户端同步配方…</#00FB9A>'
|
||||||
shulkerbox-session-invalid: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒会话异常,已停止保存以避免物品复制.</#FF7E5E>'
|
jei-sync-neoforge: '<#00FB9A>正在为 <bold>NeoForge</bold> 客户端同步配方…</#00FB9A>'
|
||||||
|
|
||||||
help:
|
help:
|
||||||
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>命令帮助</gray>'
|
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>命令帮助</gray>'
|
||||||
version: '<gray>插件版本: <white>{version}</white></gray>'
|
version: '<gray>插件版本: <white>{version}</white></gray>'
|
||||||
@@ -76,8 +70,6 @@ help:
|
|||||||
footer: '<gray>每个命令都需要对应权限.</gray>'
|
footer: '<gray>每个命令都需要对应权限.</gray>'
|
||||||
|
|
||||||
commands:
|
commands:
|
||||||
reload: '<white>/essc reload</white> <gray>- 重载插件配置</gray>'
|
|
||||||
version: '<white>/essc version</white> <gray>- 查看插件与服务端版本</gray>'
|
|
||||||
workbench: '<white>/workbench</white> <gray>- 打开工作台</gray>'
|
workbench: '<white>/workbench</white> <gray>- 打开工作台</gray>'
|
||||||
anvil: '<white>/anvil</white> <gray>- 打开铁砧</gray>'
|
anvil: '<white>/anvil</white> <gray>- 打开铁砧</gray>'
|
||||||
enchantingtable: '<white>/enchantingtable</white> <gray>- 打开附魔台</gray>'
|
enchantingtable: '<white>/enchantingtable</white> <gray>- 打开附魔台</gray>'
|
||||||
@@ -93,10 +85,10 @@ help:
|
|||||||
fly: '<white>/fly</white> <gray>- 切换飞行模式</gray>'
|
fly: '<white>/fly</white> <gray>- 切换飞行模式</gray>'
|
||||||
nightvision: '<white>/nightvision</white> <gray>- 切换夜视</gray>'
|
nightvision: '<white>/nightvision</white> <gray>- 切换夜视</gray>'
|
||||||
glow: '<white>/glow</white> <gray>- 切换发光</gray>'
|
glow: '<white>/glow</white> <gray>- 切换发光</gray>'
|
||||||
heal: '<white>/heal [玩家]</white> <gray>- 恢复生命值和饥饿值</gray>'
|
heal: '<white>/heal</white> <gray>- 恢复生命值和饥饿值</gray>'
|
||||||
vanish: '<white>/vanish</white> <gray>- 切换隐身模式</gray>'
|
vanish: '<white>/vanish</white> <gray>- 切换隐身模式</gray>'
|
||||||
seen: '<white>/seen [玩家]</white> <gray>- 查看玩家信息</gray>'
|
seen: '<white>/seen</white> <gray>- 查看玩家信息</gray>'
|
||||||
feed: '<white>/feed [玩家]</white> <gray>- 恢复饥饿值</gray>'
|
feed: '<white>/feed</white> <gray>- 恢复饥饿值</gray>'
|
||||||
repair: '<white>/repair</white> <gray>- 修复手中或全部物品</gray>'
|
repair: '<white>/repair</white> <gray>- 修复手中或全部物品</gray>'
|
||||||
tpa: '<white>/tpa [玩家]</white> <gray>- 请求传送到玩家身边</gray>'
|
tpa: '<white>/tpa [玩家]</white> <gray>- 请求传送到玩家身边</gray>'
|
||||||
tpahere: '<white>/tpahere [玩家]</white> <gray>- 请求玩家传送到你身边</gray>'
|
tpahere: '<white>/tpahere [玩家]</white> <gray>- 请求玩家传送到你身边</gray>'
|
||||||
@@ -107,6 +99,7 @@ help:
|
|||||||
skin: '<white>/essc skin [status|refresh] [玩家]</white> <gray>- 查看或刷新皮肤桥接状态</gray>'
|
skin: '<white>/essc skin [status|refresh] [玩家]</white> <gray>- 查看或刷新皮肤桥接状态</gray>'
|
||||||
admin: '<white>/essc admin</white> <gray>- 切换管理模式</gray>'
|
admin: '<white>/essc admin</white> <gray>- 切换管理模式</gray>'
|
||||||
tpsbar: '<white>/tpsbar [玩家]</white> <gray>- 切换 TPS 状态栏</gray>'
|
tpsbar: '<white>/tpsbar [玩家]</white> <gray>- 切换 TPS 状态栏</gray>'
|
||||||
|
maintenance: '<white>/maintenance [on|off|status|reload|add|remove|list]</white> <gray>- 管理维护模式</gray>'
|
||||||
|
|
||||||
tpa:
|
tpa:
|
||||||
messages:
|
messages:
|
||||||
@@ -145,7 +138,6 @@ tpa:
|
|||||||
teleport-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法完成传送,请稍后重试</#FF7E5E>'
|
teleport-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法完成传送,请稍后重试</#FF7E5E>'
|
||||||
ignore-enabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>忽略</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
ignore-enabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>忽略</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
||||||
ignore-disabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>恢复接收</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
ignore-disabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>恢复接收</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
||||||
ignore-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存传送请求忽略状态,本次操作未生效.</#FF7E5E>'
|
|
||||||
ignore-notification: '<gray>你当前正在忽略传送请求.</gray>'
|
ignore-notification: '<gray>你当前正在忽略传送请求.</gray>'
|
||||||
tpaall-sent: '<#00FB9A>你已向所有玩家发送传送请求,请求他们传送到你的位置</#00FB9A>'
|
tpaall-sent: '<#00FB9A>你已向所有玩家发送传送请求,请求他们传送到你的位置</#00FB9A>'
|
||||||
tpaall-no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>当前没有其他在线玩家.</#FF7E5E>'
|
tpaall-no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>当前没有其他在线玩家.</#FF7E5E>'
|
||||||
@@ -258,3 +250,24 @@ mobdrops-menu:
|
|||||||
name: '<#00FB9A>末影人掉落</#00FB9A>'
|
name: '<#00FB9A>末影人掉落</#00FB9A>'
|
||||||
status: '<gray>当前状态: {status}</gray>'
|
status: '<gray>当前状态: {status}</gray>'
|
||||||
toggle: '<gray>点击切换</gray>'
|
toggle: '<gray>点击切换</gray>'
|
||||||
|
|
||||||
|
maintenance:
|
||||||
|
status:
|
||||||
|
enabled: '<#FF7E5E>开启</#FF7E5E>'
|
||||||
|
disabled: '<#00FB9A>关闭</#00FB9A>'
|
||||||
|
address-hidden: '已隐藏'
|
||||||
|
messages:
|
||||||
|
enabled: '<#00FB9A>维护模式已开启.</#00FB9A>'
|
||||||
|
disabled: '<#FF7E5E>维护模式已关闭.</#FF7E5E>'
|
||||||
|
reloaded: '<#00FB9A>维护模式配置已重载.</#00FB9A>'
|
||||||
|
status: '<gray>维护模式当前状态: {status} | 白名单: <white>{whitelist_count}</white></gray>'
|
||||||
|
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance [on|off|status|reload|add|remove|list]</#FF7E5E>'
|
||||||
|
add-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance add [玩家|UUID]</#FF7E5E>'
|
||||||
|
remove-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance remove [玩家|UUID]</#FF7E5E>'
|
||||||
|
whitelist-added: '<#00FB9A>已将 {player} 加入维护白名单.</#00FB9A>'
|
||||||
|
whitelist-removed: '<#00FB9A>已将 {player} 移出维护白名单.</#00FB9A>'
|
||||||
|
whitelist-exists: '<#FFC43B>{player} 已在维护白名单中.</#FFC43B>'
|
||||||
|
whitelist-missing: '<#FF3300>错误:</#FF3300> <#FF7E5E>{player} 不在维护白名单中.</#FF7E5E>'
|
||||||
|
whitelist-empty: '<gray>维护白名单为空.</gray>'
|
||||||
|
whitelist-list: '<gray>维护白名单 ({count}): <white>{entries}</white></gray>'
|
||||||
|
login-blocked: '<#FFC43B>{player} 被维护模式拦截.</#FFC43B> <gray>UUID: {uuid} | IP: {address}</gray>'
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# EssentialsC 维护模式配置
|
||||||
|
|
||||||
|
config-version: 1
|
||||||
|
|
||||||
|
# 是否开启维护模式。
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
# 拥有该权限的玩家可以在维护模式下进入服务器。
|
||||||
|
bypass-permission: "essentialsc.maintenance.bypass"
|
||||||
|
|
||||||
|
notify:
|
||||||
|
# 玩家因维护模式被拒绝进入时,是否通知在线管理员。
|
||||||
|
enabled: true
|
||||||
|
# 拥有该权限的在线玩家会收到拦截通知。
|
||||||
|
permission: "essentialsc.maintenance.notify"
|
||||||
|
# 是否在通知中显示玩家 IP 地址;出于隐私考虑默认关闭。
|
||||||
|
include-address: false
|
||||||
|
|
||||||
|
whitelist:
|
||||||
|
# 这些 UUID 可以在维护模式下进入服务器。
|
||||||
|
uuids: []
|
||||||
|
# 这些玩家名可以在维护模式下进入服务器。大小写不敏感。
|
||||||
|
names: []
|
||||||
|
|
||||||
|
motd:
|
||||||
|
# 维护模式开启时是否替换服务器列表 MOTD。
|
||||||
|
enabled: true
|
||||||
|
lines:
|
||||||
|
- "&c服务器维护中"
|
||||||
|
- "&7请稍后再试"
|
||||||
|
|
||||||
|
kick-message:
|
||||||
|
- "&c服务器正在维护"
|
||||||
|
- "&7请稍后再进入"
|
||||||
|
|
||||||
|
bossbar:
|
||||||
|
# 维护模式开启时是否向所有在线玩家显示 BossBar。
|
||||||
|
enabled: true
|
||||||
|
title: "&c服务器正在维护"
|
||||||
|
# 可选值:PINK / BLUE / RED / GREEN / YELLOW / PURPLE / WHITE
|
||||||
|
color: RED
|
||||||
|
# 可选值:SOLID / SEGMENTED_6 / SEGMENTED_10 / SEGMENTED_12 / SEGMENTED_20
|
||||||
|
style: SOLID
|
||||||
|
# 进度范围:0.0 - 1.0
|
||||||
|
progress: 1.0
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# EssentialsC 模块配置
|
# EssentialsC 模块配置
|
||||||
#
|
#
|
||||||
# modules.yml 用于控制功能模块是否在运行时加载。
|
# modules.yml 用于控制功能模块是否在运行时加载。
|
||||||
# 各功能的详细设置位于 config.yml 与 blocks-menu.yml。
|
# 各功能的详细设置位于 config.yml、maintenance.yml 与 blocks-menu.yml。
|
||||||
#
|
#
|
||||||
# 修改模块开关后可使用 /essc reload 刷新运行期服务和监听器。
|
# 修改模块开关后可使用 /essc reload 刷新运行期服务和监听器。
|
||||||
# 直连命令的完整热增删仍建议通过重启服务器完成。
|
# 直连命令的完整热增删仍建议通过重启服务器完成。
|
||||||
@@ -18,9 +18,15 @@ modules:
|
|||||||
tpsbar:
|
tpsbar:
|
||||||
# 插件版 TPSBar。检测到服务端原生命令时会自动避免冲突。
|
# 插件版 TPSBar。检测到服务端原生命令时会自动避免冲突。
|
||||||
enabled: true
|
enabled: true
|
||||||
|
jei-sync:
|
||||||
|
# Fabric / NeoForge JEI 配方同步兼容修复。
|
||||||
|
enabled: true
|
||||||
mob-drops:
|
mob-drops:
|
||||||
# 末影人掉落控制菜单和监听器;具体掉落状态可在游戏内切换。
|
# 末影人掉落控制菜单和监听器;具体掉落状态可在游戏内切换。
|
||||||
enabled: false
|
enabled: false
|
||||||
|
maintenance:
|
||||||
|
# 维护模式。开启维护后可替换 MOTD,并阻止无绕过权限的玩家进入。
|
||||||
|
enabled: true
|
||||||
skin-bridge:
|
skin-bridge:
|
||||||
# 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
# 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
name: EssentialsC
|
name: EssentialsC
|
||||||
description: 高版本基础工具箱
|
description: 适用于 Paper 服务端的轻量基础功能插件。
|
||||||
version: ${version}
|
version: ${version}
|
||||||
|
|
||||||
main: cn.infstar.essentialsC.EssentialsC
|
main: cn.infstar.essentialsC.EssentialsC
|
||||||
@@ -119,6 +119,9 @@ permissions:
|
|||||||
essentialsc.command.tpsbar.others:
|
essentialsc.command.tpsbar.others:
|
||||||
description: 允许为其他玩家切换 /tpsbar
|
description: 允许为其他玩家切换 /tpsbar
|
||||||
default: op
|
default: op
|
||||||
|
essentialsc.command.maintenance:
|
||||||
|
description: 允许管理维护模式
|
||||||
|
default: op
|
||||||
essentialsc.command.skin:
|
essentialsc.command.skin:
|
||||||
description: 允许使用 SkinBridge 管理命令
|
description: 允许使用 SkinBridge 管理命令
|
||||||
default: op
|
default: op
|
||||||
@@ -135,11 +138,17 @@ permissions:
|
|||||||
essentialsc.command.skin.others:
|
essentialsc.command.skin.others:
|
||||||
description: 允许查看或刷新其他玩家的皮肤
|
description: 允许查看或刷新其他玩家的皮肤
|
||||||
default: op
|
default: op
|
||||||
|
essentialsc.maintenance.bypass:
|
||||||
|
description: 允许在维护模式下进入服务器
|
||||||
|
default: op
|
||||||
|
essentialsc.maintenance.notify:
|
||||||
|
description: 允许接收维护模式拦截通知
|
||||||
|
default: op
|
||||||
essentialsc.shulkerbox.open:
|
essentialsc.shulkerbox.open:
|
||||||
description: 允许通过 Shift+右键快捷打开潜影盒
|
description: 允许通过 Shift+右键快捷打开潜影盒
|
||||||
default: op
|
default: op
|
||||||
essentialsc.mobdrops.enderman:
|
essentialsc.mobdrops.enderman:
|
||||||
description: 允许控制末影人死亡时是否掉落物品
|
description: 允许控制末影人掉落方块
|
||||||
default: op
|
default: op
|
||||||
essentialsc.*:
|
essentialsc.*:
|
||||||
description: 授予 EssentialsC 的全部权限
|
description: 授予 EssentialsC 的全部权限
|
||||||
@@ -181,9 +190,12 @@ permissions:
|
|||||||
essentialsc.command.reload: true
|
essentialsc.command.reload: true
|
||||||
essentialsc.command.tpsbar: true
|
essentialsc.command.tpsbar: true
|
||||||
essentialsc.command.tpsbar.others: true
|
essentialsc.command.tpsbar.others: true
|
||||||
|
essentialsc.command.maintenance: true
|
||||||
essentialsc.command.skin: true
|
essentialsc.command.skin: true
|
||||||
essentialsc.command.skin.status: true
|
essentialsc.command.skin.status: true
|
||||||
essentialsc.command.skin.refresh: true
|
essentialsc.command.skin.refresh: true
|
||||||
essentialsc.command.skin.others: true
|
essentialsc.command.skin.others: true
|
||||||
|
essentialsc.maintenance.bypass: true
|
||||||
|
essentialsc.maintenance.notify: true
|
||||||
essentialsc.shulkerbox.open: true
|
essentialsc.shulkerbox.open: true
|
||||||
essentialsc.mobdrops.enderman: true
|
essentialsc.mobdrops.enderman: true
|
||||||
|
|||||||
@@ -3,19 +3,13 @@ package cn.infstar.essentialsC;
|
|||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
import org.junit.jupiter.params.provider.ValueSource;
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
|
||||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class ConfigurationResourcesTest {
|
class ConfigurationResourcesTest {
|
||||||
|
|
||||||
@@ -23,6 +17,7 @@ class ConfigurationResourcesTest {
|
|||||||
@ValueSource(strings = {
|
@ValueSource(strings = {
|
||||||
"config.yml",
|
"config.yml",
|
||||||
"modules.yml",
|
"modules.yml",
|
||||||
|
"maintenance.yml",
|
||||||
"blocks-menu.yml",
|
"blocks-menu.yml",
|
||||||
"paper-plugin.yml",
|
"paper-plugin.yml",
|
||||||
"lang/zh_CN.yml",
|
"lang/zh_CN.yml",
|
||||||
@@ -37,75 +32,10 @@ class ConfigurationResourcesTest {
|
|||||||
if (resourcePath.equals("config.yml")) {
|
if (resourcePath.equals("config.yml")) {
|
||||||
assertEquals(2, configuration.getInt("config-version"));
|
assertEquals(2, configuration.getInt("config-version"));
|
||||||
assertEquals(5, configuration.getInt("tpa.max-pending-requests"));
|
assertEquals(5, configuration.getInt("tpa.max-pending-requests"));
|
||||||
assertEquals(500, configuration.getInt("skin-bridge.max-generated-cache-entries"));
|
|
||||||
assertTrue(configuration.getString("skin-bridge.mineskin.api-key", "").isBlank());
|
|
||||||
}
|
}
|
||||||
if (resourcePath.equals("paper-plugin.yml")) {
|
if (resourcePath.equals("paper-plugin.yml")) {
|
||||||
assertEquals("1.21.11", configuration.getString("api-version"));
|
assertEquals("1.21.11", configuration.getString("api-version"));
|
||||||
}
|
}
|
||||||
if (resourcePath.startsWith("lang/")) {
|
|
||||||
assertTrue(!configuration.getString("prefix", "").isBlank());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void bundledLanguagesContainTheSameKeys() throws Exception {
|
|
||||||
YamlConfiguration chinese = loadResource("lang/zh_CN.yml");
|
|
||||||
YamlConfiguration english = loadResource("lang/en_US.yml");
|
|
||||||
|
|
||||||
assertEquals(chinese.getKeys(true), english.getKeys(true));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void retiredJeiFeatureIsAbsentFromResources() throws Exception {
|
|
||||||
assertFalse(loadResource("config.yml").contains("jei-sync", true));
|
|
||||||
assertFalse(loadResource("modules.yml").contains("modules.jei-sync", true));
|
|
||||||
assertFalse(loadResource("lang/zh_CN.yml").contains("messages.jei-sync-fabric", true));
|
|
||||||
assertFalse(loadResource("lang/zh_CN.yml").contains("messages.jei-sync-neoforge", true));
|
|
||||||
assertFalse(loadResource("lang/en_US.yml").contains("messages.jei-sync-fabric", true));
|
|
||||||
assertFalse(loadResource("lang/en_US.yml").contains("messages.jei-sync-neoforge", true));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void retiredMaintenanceFeatureIsAbsentFromResources() throws Exception {
|
|
||||||
assertNull(getClass().getClassLoader().getResource("maintenance.yml"));
|
|
||||||
assertFalse(loadResource("modules.yml").contains("modules.maintenance", true));
|
|
||||||
assertFalse(loadResource("paper-plugin.yml").contains("dependencies.server.LuckPerms", true));
|
|
||||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.command.maintenance", true));
|
|
||||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.maintenance.bypass", true));
|
|
||||||
assertFalse(loadResource("paper-plugin.yml").contains("permissions.essentialsc.maintenance.notify", true));
|
|
||||||
assertFalse(loadResource("lang/zh_CN.yml").contains("maintenance", true));
|
|
||||||
assertFalse(loadResource("lang/en_US.yml").contains("maintenance", true));
|
|
||||||
assertNull(cn.infstar.essentialsC.commands.CommandRegistry.resolveCommandName("maintenance"));
|
|
||||||
assertNull(cn.infstar.essentialsC.commands.CommandRegistry.resolveCommandName("maint"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void miniMessageTagNamesAreNormalized() {
|
|
||||||
assertEquals("<gray>文本</gray>", LangManager.normalizeMiniMessageTags("<GRAY>文本</GRAY>"));
|
|
||||||
assertEquals("\\<GRAY>", LangManager.normalizeMiniMessageTags("\\<GRAY>"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void legacyFormattingCanBeNestedInMiniMessage() {
|
|
||||||
String message = LangManager.applyPlaceholders(
|
|
||||||
"<gray>维护状态: {status}</gray>",
|
|
||||||
java.util.Map.of("status", "§a开启")
|
|
||||||
);
|
|
||||||
String rendered = PlainTextComponentSerializer.plainText().serialize(
|
|
||||||
MiniMessage.miniMessage().deserialize(message)
|
|
||||||
);
|
|
||||||
|
|
||||||
assertEquals("维护状态: 开启", rendered);
|
|
||||||
}
|
|
||||||
|
|
||||||
private YamlConfiguration loadResource(String resourcePath) throws Exception {
|
|
||||||
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath)) {
|
|
||||||
assertNotNull(input, resourcePath);
|
|
||||||
YamlConfiguration configuration = new YamlConfiguration();
|
|
||||||
configuration.load(new InputStreamReader(input, StandardCharsets.UTF_8));
|
|
||||||
return configuration;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.admin;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
|
||||||
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class AdminModeStoreTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
Path temporaryDirectory;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void migratesLegacyPlayersIntoIndependentFiles() throws Exception {
|
|
||||||
UUID playerId = UUID.randomUUID();
|
|
||||||
Path legacyFile = temporaryDirectory.resolve("admin-mode.yml");
|
|
||||||
YamlConfiguration legacy = new YamlConfiguration();
|
|
||||||
legacy.set("players." + playerId + ".active", true);
|
|
||||||
legacy.set("players." + playerId + ".normal.level", 27);
|
|
||||||
AtomicYamlWriter.save(legacy, legacyFile.toFile());
|
|
||||||
|
|
||||||
AdminModeStore store = new AdminModeStore(
|
|
||||||
temporaryDirectory.resolve("admin-mode").toFile(), legacyFile.toFile(), Logger.getAnonymousLogger());
|
|
||||||
|
|
||||||
YamlConfiguration migrated = store.load(playerId);
|
|
||||||
assertNotNull(migrated);
|
|
||||||
assertTrue(migrated.getBoolean("active"));
|
|
||||||
assertEquals(27, migrated.getInt("normal.level"));
|
|
||||||
assertTrue(Files.exists(temporaryDirectory.resolve("admin-mode").resolve(playerId + ".yml")));
|
|
||||||
assertFalse(Files.exists(legacyFile));
|
|
||||||
try (var backups = Files.list(temporaryDirectory)) {
|
|
||||||
assertTrue(backups.anyMatch(path -> path.getFileName().toString().startsWith("admin-mode.legacy-")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.listeners;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class ShulkerBoxSessionPolicyTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void identifiesOnlySlotsInsideTopInventory() {
|
|
||||||
assertFalse(ShulkerBoxSessionPolicy.isTopSlot(-999, 27));
|
|
||||||
assertTrue(ShulkerBoxSessionPolicy.isTopSlot(0, 27));
|
|
||||||
assertTrue(ShulkerBoxSessionPolicy.isTopSlot(26, 27));
|
|
||||||
assertFalse(ShulkerBoxSessionPolicy.isTopSlot(27, 27));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void detectsDragsThatTouchTopInventory() {
|
|
||||||
assertTrue(ShulkerBoxSessionPolicy.touchesTopInventory(Set.of(5, 30), 27));
|
|
||||||
assertFalse(ShulkerBoxSessionPolicy.touchesTopInventory(Set.of(27, 35), 27));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.util;
|
|
||||||
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class AtomicYamlWriterTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
Path temporaryDirectory;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void createsParentDirectoriesAndWritesUtf8Yaml() throws Exception {
|
|
||||||
Path target = temporaryDirectory.resolve("nested/data.yml");
|
|
||||||
YamlConfiguration configuration = new YamlConfiguration();
|
|
||||||
configuration.set("message", "中文内容");
|
|
||||||
|
|
||||||
AtomicYamlWriter.save(configuration, target.toFile());
|
|
||||||
|
|
||||||
assertTrue(Files.exists(target));
|
|
||||||
assertTrue(Files.readString(target, StandardCharsets.UTF_8).contains("中文内容"));
|
|
||||||
try (var files = Files.list(target.getParent())) {
|
|
||||||
assertFalse(files.anyMatch(path -> path.getFileName().toString().endsWith(".tmp")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void replacesExistingYamlWithoutRetainingOldValues() throws Exception {
|
|
||||||
Path target = temporaryDirectory.resolve("state.yml");
|
|
||||||
YamlConfiguration initial = new YamlConfiguration();
|
|
||||||
initial.set("old-value", true);
|
|
||||||
AtomicYamlWriter.save(initial, target.toFile());
|
|
||||||
|
|
||||||
YamlConfiguration replacement = new YamlConfiguration();
|
|
||||||
replacement.set("new-value", 42);
|
|
||||||
AtomicYamlWriter.save(replacement, target.toFile());
|
|
||||||
|
|
||||||
YamlConfiguration loaded = YamlConfiguration.loadConfiguration(target.toFile());
|
|
||||||
assertFalse(loaded.contains("old-value"));
|
|
||||||
assertEquals(42, loaded.getInt("new-value"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void supportsShortTargetFileNames() throws Exception {
|
|
||||||
Path target = temporaryDirectory.resolve("x");
|
|
||||||
YamlConfiguration configuration = new YamlConfiguration();
|
|
||||||
configuration.set("written", true);
|
|
||||||
|
|
||||||
AtomicYamlWriter.save(configuration, target.toFile());
|
|
||||||
|
|
||||||
assertTrue(YamlConfiguration.loadConfiguration(target.toFile()).getBoolean("written"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preservesParsedChineseComments() throws Exception {
|
|
||||||
Path target = temporaryDirectory.resolve("commented.yml");
|
|
||||||
YamlConfiguration configuration = new YamlConfiguration();
|
|
||||||
configuration.options().parseComments(true);
|
|
||||||
configuration.loadFromString("# 中文配置注释\nenabled: false\n");
|
|
||||||
configuration.set("enabled", true);
|
|
||||||
|
|
||||||
AtomicYamlWriter.save(configuration, target.toFile());
|
|
||||||
|
|
||||||
String saved = Files.readString(target, StandardCharsets.UTF_8);
|
|
||||||
assertTrue(saved.contains("# 中文配置注释"));
|
|
||||||
assertTrue(saved.contains("enabled: true"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'io.papermc.paperweight.userdev'
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven {
|
||||||
|
name = 'papermc'
|
||||||
|
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
api project(':compat-api')
|
||||||
|
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
|
||||||
|
}
|
||||||
|
|
||||||
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
}
|
||||||
+239
@@ -0,0 +1,239 @@
|
|||||||
|
package cn.infstar.essentialsC.v1_21_11.jei;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
|
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
|
||||||
|
import net.minecraft.network.protocol.common.custom.DiscardedPayload;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeMap;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||||
|
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 Fabric 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
|
|
||||||
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
|
if (!seen.add(serializer)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!recipes.isEmpty()) {
|
||||||
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = new FabricRecipeSyncPayload(list);
|
||||||
|
if (debug) {
|
||||||
|
logger.info("Fabric 配方条目数: " + list.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getFabricCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 Fabric 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 NeoForge 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> allRecipeTypes =
|
||||||
|
BuiltInRegistries.RECIPE_TYPE.stream().toList();
|
||||||
|
if (debug) {
|
||||||
|
logger.info("NeoForge 配方类型数: " + allRecipeTypes.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
.map(FabricRecipeSyncPayload::new, FabricRecipeSyncPayload::entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private NeoForgeRecipeSyncPayload createNeoForgePayload(
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
RecipeMap recipeMap
|
||||||
|
) {
|
||||||
|
var recipeTypeSet = new java.util.HashSet<>(recipeTypes);
|
||||||
|
if (recipeTypeSet.isEmpty()) {
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, java.util.List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
var recipeSubset = recipeMap.values().stream()
|
||||||
|
.filter(h -> recipeTypeSet.contains(h.value().getType()))
|
||||||
|
.toList();
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, recipeSubset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, NeoForgeRecipeSyncPayload> getNeoForgeStreamCodec() {
|
||||||
|
return net.minecraft.network.codec.StreamCodec.composite(
|
||||||
|
net.minecraft.network.codec.ByteBufCodecs.registry(net.minecraft.core.registries.Registries.RECIPE_TYPE)
|
||||||
|
.apply(net.minecraft.network.codec.ByteBufCodecs.collection(java.util.HashSet::new)),
|
||||||
|
NeoForgeRecipeSyncPayload::recipeTypes,
|
||||||
|
RecipeHolder.STREAM_CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list()),
|
||||||
|
NeoForgeRecipeSyncPayload::recipes,
|
||||||
|
NeoForgeRecipeSyncPayload::new
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
private static class FabricRecipeEntry {
|
||||||
|
final Object serializer;
|
||||||
|
final List<RecipeHolder<?>> recipes;
|
||||||
|
|
||||||
|
FabricRecipeEntry(Object serializer, List<RecipeHolder<?>> recipes) {
|
||||||
|
this.serializer = serializer;
|
||||||
|
this.recipes = recipes;
|
||||||
|
}
|
||||||
|
|
||||||
|
static final net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeEntry> CODEC =
|
||||||
|
net.minecraft.network.codec.StreamCodec.ofMember(
|
||||||
|
FabricRecipeEntry::write,
|
||||||
|
FabricRecipeEntry::read
|
||||||
|
);
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static FabricRecipeEntry read(RegistryFriendlyByteBuf buf) {
|
||||||
|
Identifier recipeSerializerId = buf.readIdentifier();
|
||||||
|
RecipeSerializer<?> recipeSerializer = BuiltInRegistries.RECIPE_SERIALIZER.getValue(recipeSerializerId);
|
||||||
|
|
||||||
|
if (recipeSerializer == null) {
|
||||||
|
throw new RuntimeException("Tried syncing unsupported packet serializer '" + recipeSerializerId + "'!");
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = buf.readVarInt();
|
||||||
|
var list = new ArrayList<RecipeHolder<?>>();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
net.minecraft.resources.ResourceKey<net.minecraft.world.item.crafting.Recipe<?>> id =
|
||||||
|
buf.readResourceKey(net.minecraft.core.registries.Registries.RECIPE);
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = recipeSerializer.getClass().getMethod("streamCodec");
|
||||||
|
var streamCodec = streamCodecMethod.invoke(recipeSerializer);
|
||||||
|
net.minecraft.world.item.crafting.Recipe<?> recipe =
|
||||||
|
((net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>) streamCodec)
|
||||||
|
.decode(buf);
|
||||||
|
list.add(new RecipeHolder<>(id, recipe));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to decode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new FabricRecipeEntry(recipeSerializer, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(RegistryFriendlyByteBuf buf) {
|
||||||
|
try {
|
||||||
|
var getKeyMethod = BuiltInRegistries.RECIPE_SERIALIZER.getClass().getMethod("getKey", Object.class);
|
||||||
|
Identifier identifier = (Identifier) getKeyMethod.invoke(BuiltInRegistries.RECIPE_SERIALIZER, this.serializer);
|
||||||
|
buf.writeIdentifier(identifier);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to get serializer key: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.writeVarInt(this.recipes.size());
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = this.serializer.getClass().getMethod("streamCodec");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var codec = (net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>)
|
||||||
|
streamCodecMethod.invoke(this.serializer);
|
||||||
|
|
||||||
|
for (RecipeHolder<?> recipe : this.recipes) {
|
||||||
|
buf.writeResourceKey(recipe.id());
|
||||||
|
codec.encode(buf, recipe.value());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to encode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record FabricRecipeSyncPayload(List<FabricRecipeEntry> entries) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private record NeoForgeRecipeSyncPayload(
|
||||||
|
java.util.Set<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
java.util.List<RecipeHolder<?>> recipes
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'io.papermc.paperweight.userdev'
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven {
|
||||||
|
name = 'papermc'
|
||||||
|
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
api project(':compat-api')
|
||||||
|
paperweight.paperDevBundle('26.1.2.build.72-stable')
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
|
}
|
||||||
|
|
||||||
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
}
|
||||||
+240
@@ -0,0 +1,240 @@
|
|||||||
|
package cn.infstar.essentialsC.v26_1_2.jei;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
|
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
|
||||||
|
import net.minecraft.network.protocol.common.custom.DiscardedPayload;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeMap;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||||
|
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 Fabric 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
|
|
||||||
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
|
if (!seen.add(serializer)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!recipes.isEmpty()) {
|
||||||
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = new FabricRecipeSyncPayload(list);
|
||||||
|
if (debug) {
|
||||||
|
logger.info("Fabric 配方条目数: " + list.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getFabricCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 Fabric 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 NeoForge 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> allRecipeTypes =
|
||||||
|
BuiltInRegistries.RECIPE_TYPE.stream().toList();
|
||||||
|
if (debug) {
|
||||||
|
logger.info("NeoForge 配方类型数: " + allRecipeTypes.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
.map(FabricRecipeSyncPayload::new, FabricRecipeSyncPayload::entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private NeoForgeRecipeSyncPayload createNeoForgePayload(
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
RecipeMap recipeMap
|
||||||
|
) {
|
||||||
|
var recipeTypeSet = new java.util.HashSet<>(recipeTypes);
|
||||||
|
if (recipeTypeSet.isEmpty()) {
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, java.util.List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
var recipeSubset = recipeMap.values().stream()
|
||||||
|
.filter(h -> recipeTypeSet.contains(h.value().getType()))
|
||||||
|
.toList();
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, recipeSubset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, NeoForgeRecipeSyncPayload> getNeoForgeStreamCodec() {
|
||||||
|
return net.minecraft.network.codec.StreamCodec.composite(
|
||||||
|
net.minecraft.network.codec.ByteBufCodecs.registry(net.minecraft.core.registries.Registries.RECIPE_TYPE)
|
||||||
|
.apply(net.minecraft.network.codec.ByteBufCodecs.collection(java.util.HashSet::new)),
|
||||||
|
NeoForgeRecipeSyncPayload::recipeTypes,
|
||||||
|
RecipeHolder.STREAM_CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list()),
|
||||||
|
NeoForgeRecipeSyncPayload::recipes,
|
||||||
|
NeoForgeRecipeSyncPayload::new
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
private static class FabricRecipeEntry {
|
||||||
|
final Object serializer;
|
||||||
|
final List<RecipeHolder<?>> recipes;
|
||||||
|
|
||||||
|
FabricRecipeEntry(Object serializer, List<RecipeHolder<?>> recipes) {
|
||||||
|
this.serializer = serializer;
|
||||||
|
this.recipes = recipes;
|
||||||
|
}
|
||||||
|
|
||||||
|
static final net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeEntry> CODEC =
|
||||||
|
net.minecraft.network.codec.StreamCodec.ofMember(
|
||||||
|
FabricRecipeEntry::write,
|
||||||
|
FabricRecipeEntry::read
|
||||||
|
);
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static FabricRecipeEntry read(RegistryFriendlyByteBuf buf) {
|
||||||
|
Identifier recipeSerializerId = buf.readIdentifier();
|
||||||
|
RecipeSerializer<?> recipeSerializer = BuiltInRegistries.RECIPE_SERIALIZER.getValue(recipeSerializerId);
|
||||||
|
|
||||||
|
if (recipeSerializer == null) {
|
||||||
|
throw new RuntimeException("Tried syncing unsupported packet serializer '" + recipeSerializerId + "'!");
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = buf.readVarInt();
|
||||||
|
var list = new ArrayList<RecipeHolder<?>>();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
net.minecraft.resources.ResourceKey<net.minecraft.world.item.crafting.Recipe<?>> id =
|
||||||
|
buf.readResourceKey(net.minecraft.core.registries.Registries.RECIPE);
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = recipeSerializer.getClass().getMethod("streamCodec");
|
||||||
|
var streamCodec = streamCodecMethod.invoke(recipeSerializer);
|
||||||
|
net.minecraft.world.item.crafting.Recipe<?> recipe =
|
||||||
|
((net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>) streamCodec)
|
||||||
|
.decode(buf);
|
||||||
|
list.add(new RecipeHolder<>(id, recipe));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to decode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new FabricRecipeEntry(recipeSerializer, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(RegistryFriendlyByteBuf buf) {
|
||||||
|
try {
|
||||||
|
var getKeyMethod = BuiltInRegistries.RECIPE_SERIALIZER.getClass().getMethod("getKey", Object.class);
|
||||||
|
Identifier identifier = (Identifier) getKeyMethod.invoke(BuiltInRegistries.RECIPE_SERIALIZER, this.serializer);
|
||||||
|
buf.writeIdentifier(identifier);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to get serializer key: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.writeVarInt(this.recipes.size());
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = this.serializer.getClass().getMethod("streamCodec");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var codec = (net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>)
|
||||||
|
streamCodecMethod.invoke(this.serializer);
|
||||||
|
|
||||||
|
for (RecipeHolder<?> recipe : this.recipes) {
|
||||||
|
buf.writeResourceKey(recipe.id());
|
||||||
|
codec.encode(buf, recipe.value());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to encode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record FabricRecipeSyncPayload(List<FabricRecipeEntry> entries) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private record NeoForgeRecipeSyncPayload(
|
||||||
|
java.util.Set<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
java.util.List<RecipeHolder<?>> recipes
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'io.papermc.paperweight.userdev'
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven {
|
||||||
|
name = 'papermc'
|
||||||
|
url = uri('https://repo.papermc.io/repository/maven-public/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
api project(':compat-api')
|
||||||
|
paperweight.paperDevBundle('26.2.build.31-alpha')
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
|
}
|
||||||
|
|
||||||
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
}
|
||||||
+240
@@ -0,0 +1,240 @@
|
|||||||
|
package cn.infstar.essentialsC.v26_2.jei;
|
||||||
|
|
||||||
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
|
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
|
||||||
|
import net.minecraft.network.protocol.common.custom.DiscardedPayload;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeMap;
|
||||||
|
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||||
|
import org.bukkit.craftbukkit.entity.CraftPlayer;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 Fabric 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
|
|
||||||
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
|
if (!seen.add(serializer)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!recipes.isEmpty()) {
|
||||||
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = new FabricRecipeSyncPayload(list);
|
||||||
|
if (debug) {
|
||||||
|
logger.info("Fabric 配方条目数: " + list.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getFabricCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 Fabric 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
public void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
|
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
|
||||||
|
MinecraftServer server = serverPlayer.level().getServer();
|
||||||
|
if (server == null) {
|
||||||
|
if (debug) {
|
||||||
|
logger.warning("服务端实例为 null");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
|
if (debug) {
|
||||||
|
logger.info("开始构建 NeoForge 配方数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> allRecipeTypes =
|
||||||
|
BuiltInRegistries.RECIPE_TYPE.stream().toList();
|
||||||
|
if (debug) {
|
||||||
|
logger.info("NeoForge 配方类型数: " + allRecipeTypes.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
|
buffer.getBytes(0, bytes);
|
||||||
|
|
||||||
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
.map(FabricRecipeSyncPayload::new, FabricRecipeSyncPayload::entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private NeoForgeRecipeSyncPayload createNeoForgePayload(
|
||||||
|
java.util.List<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
RecipeMap recipeMap
|
||||||
|
) {
|
||||||
|
var recipeTypeSet = new java.util.HashSet<>(recipeTypes);
|
||||||
|
if (recipeTypeSet.isEmpty()) {
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, java.util.List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
var recipeSubset = recipeMap.values().stream()
|
||||||
|
.filter(h -> recipeTypeSet.contains(h.value().getType()))
|
||||||
|
.toList();
|
||||||
|
return new NeoForgeRecipeSyncPayload(recipeTypeSet, recipeSubset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, NeoForgeRecipeSyncPayload> getNeoForgeStreamCodec() {
|
||||||
|
return net.minecraft.network.codec.StreamCodec.composite(
|
||||||
|
net.minecraft.network.codec.ByteBufCodecs.registry(net.minecraft.core.registries.Registries.RECIPE_TYPE)
|
||||||
|
.apply(net.minecraft.network.codec.ByteBufCodecs.collection(java.util.HashSet::new)),
|
||||||
|
NeoForgeRecipeSyncPayload::recipeTypes,
|
||||||
|
RecipeHolder.STREAM_CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list()),
|
||||||
|
NeoForgeRecipeSyncPayload::recipes,
|
||||||
|
NeoForgeRecipeSyncPayload::new
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
private static class FabricRecipeEntry {
|
||||||
|
final Object serializer;
|
||||||
|
final List<RecipeHolder<?>> recipes;
|
||||||
|
|
||||||
|
FabricRecipeEntry(Object serializer, List<RecipeHolder<?>> recipes) {
|
||||||
|
this.serializer = serializer;
|
||||||
|
this.recipes = recipes;
|
||||||
|
}
|
||||||
|
|
||||||
|
static final net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeEntry> CODEC =
|
||||||
|
net.minecraft.network.codec.StreamCodec.ofMember(
|
||||||
|
FabricRecipeEntry::write,
|
||||||
|
FabricRecipeEntry::read
|
||||||
|
);
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static FabricRecipeEntry read(RegistryFriendlyByteBuf buf) {
|
||||||
|
Identifier recipeSerializerId = buf.readIdentifier();
|
||||||
|
RecipeSerializer<?> recipeSerializer = BuiltInRegistries.RECIPE_SERIALIZER.getValue(recipeSerializerId);
|
||||||
|
|
||||||
|
if (recipeSerializer == null) {
|
||||||
|
throw new RuntimeException("Tried syncing unsupported packet serializer '" + recipeSerializerId + "'!");
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = buf.readVarInt();
|
||||||
|
var list = new ArrayList<RecipeHolder<?>>();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
net.minecraft.resources.ResourceKey<net.minecraft.world.item.crafting.Recipe<?>> id =
|
||||||
|
buf.readResourceKey(net.minecraft.core.registries.Registries.RECIPE);
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = recipeSerializer.getClass().getMethod("streamCodec");
|
||||||
|
var streamCodec = streamCodecMethod.invoke(recipeSerializer);
|
||||||
|
net.minecraft.world.item.crafting.Recipe<?> recipe =
|
||||||
|
((net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>) streamCodec)
|
||||||
|
.decode(buf);
|
||||||
|
list.add(new RecipeHolder<>(id, recipe));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to decode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new FabricRecipeEntry(recipeSerializer, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(RegistryFriendlyByteBuf buf) {
|
||||||
|
try {
|
||||||
|
var getKeyMethod = BuiltInRegistries.RECIPE_SERIALIZER.getClass().getMethod("getKey", Object.class);
|
||||||
|
Identifier identifier = (Identifier) getKeyMethod.invoke(BuiltInRegistries.RECIPE_SERIALIZER, this.serializer);
|
||||||
|
buf.writeIdentifier(identifier);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to get serializer key: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.writeVarInt(this.recipes.size());
|
||||||
|
|
||||||
|
try {
|
||||||
|
var streamCodecMethod = this.serializer.getClass().getMethod("streamCodec");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var codec = (net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, net.minecraft.world.item.crafting.Recipe<?>>)
|
||||||
|
streamCodecMethod.invoke(this.serializer);
|
||||||
|
|
||||||
|
for (RecipeHolder<?> recipe : this.recipes) {
|
||||||
|
buf.writeResourceKey(recipe.id());
|
||||||
|
codec.encode(buf, recipe.value());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to encode recipe: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record FabricRecipeSyncPayload(List<FabricRecipeEntry> entries) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private record NeoForgeRecipeSyncPayload(
|
||||||
|
java.util.Set<net.minecraft.world.item.crafting.RecipeType<?>> recipeTypes,
|
||||||
|
java.util.List<RecipeHolder<?>> recipes
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user