Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2479192ad3 | ||
|
|
b57c7d4843 |
@@ -1,28 +0,0 @@
|
|||||||
version: 2
|
|
||||||
updates:
|
|
||||||
- package-ecosystem: gradle
|
|
||||||
directory: /
|
|
||||||
schedule:
|
|
||||||
interval: weekly
|
|
||||||
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
|
|
||||||
directory: /
|
|
||||||
schedule:
|
|
||||||
interval: weekly
|
|
||||||
open-pull-requests-limit: 5
|
|
||||||
groups:
|
|
||||||
github-actions:
|
|
||||||
patterns:
|
|
||||||
- "*"
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
name: Build
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
- 'dev/**'
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: 检出代码
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 设置 Java 25
|
|
||||||
uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
java-version: '25'
|
|
||||||
distribution: temurin
|
|
||||||
cache: gradle
|
|
||||||
|
|
||||||
- name: 验证 Gradle Wrapper
|
|
||||||
uses: gradle/actions/wrapper-validation@v4
|
|
||||||
|
|
||||||
- name: 配置 Gradle
|
|
||||||
uses: gradle/actions/setup-gradle@v4
|
|
||||||
|
|
||||||
- name: 授予执行权限
|
|
||||||
run: chmod +x gradlew
|
|
||||||
|
|
||||||
- name: 构建插件
|
|
||||||
run: ./gradlew clean build --no-daemon
|
|
||||||
|
|
||||||
- name: 上传测试产物
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: EssentialsC-test-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,34 +16,23 @@ 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@v1
|
||||||
with:
|
with:
|
||||||
files: build/libs/EssentialsC*.jar
|
files: build/libs/EssentialsC*.jar
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
# 更新日志
|
|
||||||
|
|
||||||
## 1.3.0 - 2026-08-02
|
|
||||||
|
|
||||||
### 新增
|
|
||||||
|
|
||||||
- 按 HuskHomes 的单服逻辑完整实现 TPA 请求、接受、拒绝、忽略、预热、冷却、位置快照、音效与相关权限。
|
|
||||||
- 新增维护模式,包括 MOTD、BossBar、登录拦截、白名单、管理员通知和 LuckPerms 异步权限检查。
|
|
||||||
- 新增 SkinBridge,可识别 InfstarMC、LittleSkin 与自定义 Blessing Skin Provider,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
|
||||||
- 新增管理模式独立状态存储、玩家功能状态管理与 JEI 配方同步版本适配。
|
|
||||||
|
|
||||||
### 优化
|
|
||||||
|
|
||||||
- 按便捷方块、管理、修复与皮肤功能重新整理运行时模块。
|
|
||||||
- 完善潜影盒会话保护、TPA 请求队列、配置迁移、数据原子写入与持久化错误处理。
|
|
||||||
- 适配 Paper `1.21.11`、`26.1.2` 与 `26.2`,最终插件保持 Java 21 字节码兼容。
|
|
||||||
- 迁移 Paper 弃用 API,并将弃用警告设为构建错误。
|
|
||||||
- 统一 HuskHomes 风格的中英文消息、颜色和配置注释。
|
|
||||||
|
|
||||||
### 注意事项
|
|
||||||
|
|
||||||
- 最低服务端版本为 Paper `1.21.11`,不支持 Folia 或 Fabric 服务端。
|
|
||||||
- LuckPerms 为推荐软依赖;未安装时维护模式会在玩家加入后复核绕过权限。
|
|
||||||
- SkinBridge 默认关闭,启用前必须配置有效的 MineSkin API Key。
|
|
||||||
- 主配置版本为 `2`。
|
|
||||||
@@ -11,8 +11,8 @@
|
|||||||
|
|
||||||
- 最低支持版本为 `Paper 1.21.11`
|
- 最低支持版本为 `Paper 1.21.11`
|
||||||
- 已适配 `Paper 26.2`
|
- 已适配 `Paper 26.2`
|
||||||
- 主插件使用 `Java 21`,Paper 26.x 版本适配模块使用对应服务端要求的 Java 工具链
|
- 构建环境固定为 `Java 21`
|
||||||
- 配置按职责拆分:主行为与 SkinBridge、模块开关、菜单布局、维护模式和语言文本分别管理
|
- 配置、模块开关与文本分离:行为配置放在 `config.yml`,模块开关放在 `modules.yml`,提示文本放在 `lang/`
|
||||||
- 支持运行期模块开关,避免为不同功能组合构建多个插件版本
|
- 支持运行期模块开关,避免为不同功能组合构建多个插件版本
|
||||||
|
|
||||||
## 主要功能
|
## 主要功能
|
||||||
@@ -45,15 +45,6 @@
|
|||||||
- `/essc admin` 管理模式切换
|
- `/essc admin` 管理模式切换
|
||||||
- `/maintenance` `(/maint)` 维护模式管理
|
- `/maintenance` `(/maint)` 维护模式管理
|
||||||
|
|
||||||
### 控制台命令
|
|
||||||
|
|
||||||
- `/essc help`、`/essc version`、`/essc reload`
|
|
||||||
- `/maintenance [on|off|status|reload|add|remove|list]`,也可通过 `/essc maintenance ...` 执行
|
|
||||||
- `/seen [玩家]`、`/heal [玩家]`、`/feed [玩家]`、`/tpsbar [玩家]`
|
|
||||||
- `/essc skin [status|refresh] [玩家]`
|
|
||||||
|
|
||||||
依赖发送者位置、背包或玩家交互状态的命令仅允许在游戏内执行。控制台执行玩家状态命令时必须明确提供目标玩家。
|
|
||||||
|
|
||||||
### 其它功能
|
### 其它功能
|
||||||
|
|
||||||
- Shift + 右键快捷打开潜影盒
|
- Shift + 右键快捷打开潜影盒
|
||||||
@@ -65,34 +56,31 @@
|
|||||||
|
|
||||||
## 模块配置
|
## 模块配置
|
||||||
|
|
||||||
项目默认构建一个完整插件。玩家常用命令、Vanish 与 TPA 属于核心功能,始终加载并通过权限控制;其他可选功能由 `plugins/EssentialsC/modules.yml` 控制。
|
项目现在默认构建一个完整插件,功能是否启用由 `plugins/EssentialsC/modules.yml` 控制。
|
||||||
|
|
||||||
| 模块 | 默认状态 | 说明 |
|
| 模块 | 默认状态 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `blocks` | 开启 | 便捷方块命令、`/essc blocks` 菜单、潜影盒快捷打开 |
|
| `blocks` | 开启 | 便捷方块命令、`/essc blocks` 菜单、潜影盒快捷打开 |
|
||||||
|
| `player` | 开启 | 飞行、夜视、发光、治疗、喂食、修复、帽子、自杀、隐身、查询玩家 |
|
||||||
| `admin-mode` | 开启 | `/essc admin` 管理模式与独立状态保存 |
|
| `admin-mode` | 开启 | `/essc admin` 管理模式与独立状态保存 |
|
||||||
| `tpsbar` | 开启 | 插件版 TPSBar,检测到服务端原生命令时自动避免冲突 |
|
| `tpsbar` | 开启 | 插件版 TPSBar,仍受 `config.yml` 中 `tpsbar.mode` 控制 |
|
||||||
| `jei-sync` | 开启 | Fabric / NeoForge JEI 配方同步修复 |
|
| `jei-sync` | 开启 | Fabric / NeoForge JEI 配方同步修复 |
|
||||||
| `mob-drops` | 关闭 | 末影人掉落控制,默认关闭以保留过去标准版行为 |
|
| `mob-drops` | 关闭 | 末影人掉落控制,默认关闭以保留过去标准版行为 |
|
||||||
| `maintenance` | 开启 | 维护模式命令、MOTD 替换、登录拦截、白名单和拦截通知 |
|
| `maintenance` | 开启 | 维护模式命令、MOTD 替换、登录拦截、白名单和拦截通知 |
|
||||||
| `skin-bridge` | 关闭 | 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤 |
|
|
||||||
|
|
||||||
修改模块开关后使用 `/essc reload` 即可刷新运行期服务、监听器和命令门禁。可选模块命令始终注册,模块关闭时会返回统一的停用提示,因此无需为了启用命令重启服务器。
|
修改模块开关后可先使用 `/essc reload` 刷新运行期服务与监听器状态。由于 Bukkit 命令表不适合在运行期完整热增删,若模块是在启动时关闭的,对应直连命令可能仍需重启后才会注册;通过 `/essc <子命令>` 入口通常可立即按新的模块状态执行。
|
||||||
|
|
||||||
## 安装说明
|
## 安装说明
|
||||||
|
|
||||||
1. 从 [Releases](https://github.com/Coldsmiles/EssentialsC/releases) 下载所需版本。
|
1. 从 [Releases](https://github.com/Coldsmiles/EssentialsC/releases) 下载所需版本。
|
||||||
2. 将插件放入服务端的 `plugins/` 目录。
|
2. 将插件放入服务端的 `plugins/` 目录。
|
||||||
3. 建议安装 LuckPerms;维护模式会优先通过其缓存异步检查登录权限,未安装时会在玩家加入后立即复核。
|
3. 启动一次服务端以生成配置文件。
|
||||||
4. 启动一次服务端以生成配置文件。
|
4. 按需修改 `plugins/EssentialsC/config.yml` 与 `plugins/EssentialsC/lang/` 下的语言文件。
|
||||||
5. 按需修改 `plugins/EssentialsC/` 下的配置文件与 `lang/` 语言文件。
|
5. 如有需要,使用权限插件为玩家授权。
|
||||||
6. 使用权限插件为玩家分配所需权限。
|
|
||||||
|
|
||||||
## 配置说明
|
## 配置说明
|
||||||
|
|
||||||
当前配置按功能职责拆分,避免所有设置堆积在一个文件中:
|
当前配置结构以“行为配置”和“文本配置”分离为原则:
|
||||||
|
|
||||||
SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-bridge.enabled`,填写 `config.yml` 中的 `skin-bridge.mineskin.api-key`,并至少启用一个 Provider。真实密钥只应填写在服务器运行目录的 `config.yml` 中,不要写入源码或提交到公开仓库。该模块不要求安装 SkinsRestorer。默认支持 InfstarMC 与 LittleSkin;Provider 的 `name` 可自由修改,并会显示在日志和 `/essc skin status <玩家>` 中。生成后的 MineSkin 纹理会按皮肤 URL 缓存到 `skin-cache.yml`,并遵守配置的 TTL。
|
|
||||||
|
|
||||||
- `config.yml`
|
- `config.yml`
|
||||||
- 语言选择
|
- 语言选择
|
||||||
@@ -100,12 +88,9 @@ SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-
|
|||||||
- JEI 同步开关
|
- JEI 同步开关
|
||||||
- 掉落控制
|
- 掉落控制
|
||||||
- TPSBar 模式
|
- TPSBar 模式
|
||||||
- TPA 请求、预热、冷却和音效
|
- 便捷菜单布局
|
||||||
- SkinBridge、MineSkin、Provider 与排除名单
|
|
||||||
- `modules.yml`
|
- `modules.yml`
|
||||||
- 功能模块开关
|
- 功能模块开关
|
||||||
- `blocks-menu.yml`
|
|
||||||
- 便捷菜单分区、槽位、材质和权限
|
|
||||||
- `maintenance.yml`
|
- `maintenance.yml`
|
||||||
- 维护模式状态
|
- 维护模式状态
|
||||||
- 维护 MOTD
|
- 维护 MOTD
|
||||||
@@ -121,9 +106,7 @@ SkinBridge 默认关闭。使用前需启用 `modules.yml` 中的 `modules.skin-
|
|||||||
- 管理模式文本
|
- 管理模式文本
|
||||||
- TPSBar 文本
|
- TPSBar 文本
|
||||||
|
|
||||||
主配置当前使用 `config-version: 2`。SkinBridge 直接配置在 `config.yml` 中,便捷菜单配置仍保存在独立文件中。
|
配置文件包含 `config-version`,后续如有结构升级,可基于版本号进行迁移与重建。
|
||||||
|
|
||||||
版本变化与升级说明见 [CHANGELOG.md](CHANGELOG.md)。
|
|
||||||
|
|
||||||
## 权限示例
|
## 权限示例
|
||||||
|
|
||||||
@@ -140,25 +123,10 @@ essentialsc.command.heal
|
|||||||
essentialsc.command.feed
|
essentialsc.command.feed
|
||||||
essentialsc.command.repair
|
essentialsc.command.repair
|
||||||
essentialsc.command.vanish
|
essentialsc.command.vanish
|
||||||
essentialsc.vanish.see
|
|
||||||
essentialsc.command.seen
|
essentialsc.command.seen
|
||||||
essentialsc.command.tpa
|
|
||||||
essentialsc.command.tpahere
|
|
||||||
essentialsc.command.tpaall
|
|
||||||
essentialsc.command.tpaccept
|
|
||||||
essentialsc.command.tpdeny
|
|
||||||
essentialsc.command.tpignore
|
|
||||||
essentialsc.tpa.bypass-warmup
|
|
||||||
essentialsc.tpa.bypass-cooldown
|
|
||||||
# 使用数字覆盖玩家预热时间,例如 3 秒
|
|
||||||
essentialsc.tpa.warmup.3
|
|
||||||
essentialsc.command.admin
|
essentialsc.command.admin
|
||||||
essentialsc.command.tpsbar
|
essentialsc.command.tpsbar
|
||||||
essentialsc.command.maintenance
|
essentialsc.command.maintenance
|
||||||
essentialsc.command.skin
|
|
||||||
essentialsc.command.skin.status
|
|
||||||
essentialsc.command.skin.refresh
|
|
||||||
essentialsc.command.skin.others
|
|
||||||
essentialsc.maintenance.bypass
|
essentialsc.maintenance.bypass
|
||||||
essentialsc.maintenance.notify
|
essentialsc.maintenance.notify
|
||||||
essentialsc.shulkerbox.open
|
essentialsc.shulkerbox.open
|
||||||
@@ -191,18 +159,16 @@ Windows 可使用:
|
|||||||
./gradlew build
|
./gradlew build
|
||||||
./gradlew deployToPaper12111
|
./gradlew deployToPaper12111
|
||||||
./gradlew deployToPaper2612
|
./gradlew deployToPaper2612
|
||||||
./gradlew deployToPaper262
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 本地测试服
|
## 本地测试服
|
||||||
|
|
||||||
项目包含三个本地测试服目录:
|
项目包含两个本地测试服目录:
|
||||||
|
|
||||||
| 测试服 | 端口 | 部署任务 | 启动脚本 |
|
| 测试服 | 端口 | 部署任务 | 启动脚本 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 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.1.2 | `25565` | `deployToPaper2612` | `test-server/paper-26.1.2/start.bat` |
|
| Paper 26.1.2 | `25565` | `deployToPaper2612` | `test-server/paper-26.1.2/start.bat` |
|
||||||
| Paper 26.2 | 以本地配置为准 | `deployToPaper262` | `test-server/paper-26.2/start.bat` |
|
|
||||||
|
|
||||||
IDEA 运行配置会在启动测试服前自动执行对应部署任务。部署任务会替换 `EssentialsC*.jar`,并删除 `plugins/EssentialsC` 数据目录,以便测试新增默认配置和语言文本。
|
IDEA 运行配置会在启动测试服前自动执行对应部署任务。部署任务会替换 `EssentialsC*.jar`,并删除 `plugins/EssentialsC` 数据目录,以便测试新增默认配置和语言文本。
|
||||||
|
|
||||||
@@ -211,8 +177,8 @@ IDEA 运行配置会在启动测试服前自动执行对应部署任务。部署
|
|||||||
- 使用 `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`
|
- 涉及 NMS 的功能通过 `compat-api` + `versions/v<版本>` 适配模块隔离,主插件只依赖稳定接口;当前包含 `1.21.11`、`26.1.2`、`26.2`
|
||||||
- 运行时通过 `modules.yml` 控制模块加载,命令始终注册并按模块状态执行门禁
|
- 运行时通过 `modules.yml` 控制模块加载,命令与监听器按模块状态注册
|
||||||
- 普通 push/PR 会执行构建与测试,版本标签继续生成 GitHub Release
|
- 发布流程基于 GitHub Actions 和 Gradle Wrapper
|
||||||
|
|
||||||
## 许可证
|
## 许可证
|
||||||
|
|
||||||
|
|||||||
+3
-51
@@ -1,16 +1,14 @@
|
|||||||
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 java.util.zip.ZipFile
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java'
|
id 'java'
|
||||||
id 'io.papermc.paperweight.userdev' version '2.0.0-beta.21'
|
id 'io.papermc.paperweight.userdev' version '2.0.0-beta.21'
|
||||||
id 'com.gradleup.shadow' version '8.3.11'
|
id 'com.gradleup.shadow' version '8.3.6'
|
||||||
}
|
}
|
||||||
|
|
||||||
group = 'cn.infstar'
|
group = 'cn.infstar'
|
||||||
version = providers.gradleProperty('pluginVersion').orElse('1.3.0').get()
|
version = '1.6.0'
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
@@ -22,12 +20,7 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
paperweight.paperDevBundle('1.21.11-R0.1-SNAPSHOT')
|
||||||
compileOnly 'net.luckperms:api:5.5'
|
|
||||||
implementation project(':compat-api')
|
implementation project(':compat-api')
|
||||||
implementation 'com.google.code.gson:gson:2.11.0'
|
|
||||||
testImplementation platform('org.junit:junit-bom:5.13.4')
|
|
||||||
testImplementation 'org.junit.jupiter:junit-jupiter'
|
|
||||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
@@ -36,21 +29,14 @@ 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 {
|
||||||
filteringCharset = 'UTF-8'
|
filteringCharset = 'UTF-8'
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType(Test).configureEach {
|
|
||||||
useJUnitPlatform()
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('processResources', ProcessResources).configure {
|
tasks.named('processResources', ProcessResources).configure {
|
||||||
inputs.property('version', project.version)
|
inputs.property('version', project.version)
|
||||||
filesMatching('paper-plugin.yml') {
|
filesMatching('paper-plugin.yml') {
|
||||||
@@ -67,7 +53,6 @@ tasks.named('shadowJar', ShadowJar).configure {
|
|||||||
description = '构建包含全部运行期可开关模块的 EssentialsC 插件。'
|
description = '构建包含全部运行期可开关模块的 EssentialsC 插件。'
|
||||||
archiveFileName.set("EssentialsC-${project.version}.jar")
|
archiveFileName.set("EssentialsC-${project.version}.jar")
|
||||||
configurations = [project.configurations.runtimeClasspath]
|
configurations = [project.configurations.runtimeClasspath]
|
||||||
relocate 'com.google.gson', 'cn.infstar.essentialsC.libs.gson'
|
|
||||||
|
|
||||||
[
|
[
|
||||||
project(':versions:v1_21_11'),
|
project(':versions:v1_21_11'),
|
||||||
@@ -84,39 +69,6 @@ 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'
|
||||||
|
|||||||
@@ -9,6 +9,4 @@ public interface JeiRecipeSyncAdapter {
|
|||||||
void sendFabricRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
void sendFabricRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
||||||
|
|
||||||
void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
void sendNeoForgeRecipeSync(Player player, Logger logger, boolean debug) throws Exception;
|
||||||
|
|
||||||
void clearCache();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.compat.jei;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.function.Function;
|
|
||||||
|
|
||||||
public final class RecipeGrouping {
|
|
||||||
|
|
||||||
private RecipeGrouping() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <K, V> Map<K, List<V>> groupBy(Iterable<V> values,
|
|
||||||
Function<? super V, ? extends K> keyFunction) {
|
|
||||||
Map<K, List<V>> grouped = new LinkedHashMap<>();
|
|
||||||
for (V value : values) {
|
|
||||||
grouped.computeIfAbsent(keyFunction.apply(value), ignored -> new ArrayList<>()).add(value);
|
|
||||||
}
|
|
||||||
return grouped;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
paper_version="${1:?必须提供 Paper 版本}"
|
|
||||||
workspace="$(mktemp -d)"
|
|
||||||
server_pid=""
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
if [[ -n "$server_pid" ]] && kill -0 "$server_pid" 2>/dev/null; then
|
|
||||||
kill -TERM "$server_pid" 2>/dev/null || true
|
|
||||||
wait "$server_pid" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
rm -rf "$workspace"
|
|
||||||
}
|
|
||||||
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 build/libs/EssentialsC-*.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"
|
|
||||||
java -Xms512M -Xmx1G -jar paper.jar --nogui > server.log 2>&1
|
|
||||||
) &
|
|
||||||
server_pid=$!
|
|
||||||
|
|
||||||
for _ in $(seq 1 120); do
|
|
||||||
if grep -Fq 'EssentialsC v1.3.0 已启用' "$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
|
|
||||||
@@ -2,7 +2,6 @@ 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;
|
||||||
@@ -14,8 +13,6 @@ import cn.infstar.essentialsC.listeners.ShulkerBoxListener;
|
|||||||
import cn.infstar.essentialsC.listeners.VanishListener;
|
import cn.infstar.essentialsC.listeners.VanishListener;
|
||||||
import cn.infstar.essentialsC.maintenance.MaintenanceListener;
|
import cn.infstar.essentialsC.maintenance.MaintenanceListener;
|
||||||
import cn.infstar.essentialsC.maintenance.MaintenanceManager;
|
import cn.infstar.essentialsC.maintenance.MaintenanceManager;
|
||||||
import cn.infstar.essentialsC.player.PlayerStateManager;
|
|
||||||
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;
|
||||||
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
||||||
@@ -38,26 +35,21 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
|
|
||||||
private static LangManager langManager;
|
private static LangManager langManager;
|
||||||
private ModuleManager moduleManager;
|
private ModuleManager moduleManager;
|
||||||
private FeatureConfigManager featureConfigManager;
|
|
||||||
private AdminModeManager adminModeManager;
|
private AdminModeManager adminModeManager;
|
||||||
private MaintenanceManager maintenanceManager;
|
private MaintenanceManager maintenanceManager;
|
||||||
private TeleportRequestManager teleportRequestManager;
|
private TeleportRequestManager teleportRequestManager;
|
||||||
private PlayerStateManager playerStateManager;
|
|
||||||
private MaintenanceListener maintenanceListener;
|
private MaintenanceListener maintenanceListener;
|
||||||
private TpsBarService tpsBarManager;
|
private TpsBarService tpsBarManager;
|
||||||
private ShulkerBoxListener shulkerBoxListener;
|
private ShulkerBoxListener shulkerBoxListener;
|
||||||
private BlocksMenuCommand blocksMenuCommandListener;
|
|
||||||
private JeiRecipeSyncListener jeiRecipeSyncListener;
|
private JeiRecipeSyncListener jeiRecipeSyncListener;
|
||||||
private MobDropListener mobDropListener;
|
private MobDropListener mobDropListener;
|
||||||
private MobDropMenuListener mobDropMenuListener;
|
private MobDropMenuListener mobDropMenuListener;
|
||||||
private VanishListener vanishListener;
|
private VanishListener vanishListener;
|
||||||
private SkinBridgeManager skinBridgeManager;
|
|
||||||
private boolean commandsRegistered;
|
private boolean commandsRegistered;
|
||||||
private final Map<String, String> moduleStatus = new LinkedHashMap<>();
|
private final Map<String, String> moduleStatus = new LinkedHashMap<>();
|
||||||
|
|
||||||
@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);
|
||||||
|
|
||||||
@@ -81,18 +73,6 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
if (teleportRequestManager != null) {
|
if (teleportRequestManager != null) {
|
||||||
teleportRequestManager.shutdown();
|
teleportRequestManager.shutdown();
|
||||||
}
|
}
|
||||||
if (playerStateManager != null) {
|
|
||||||
playerStateManager.shutdown();
|
|
||||||
}
|
|
||||||
if (skinBridgeManager != null) {
|
|
||||||
skinBridgeManager.shutdown();
|
|
||||||
}
|
|
||||||
if (shulkerBoxListener != null) {
|
|
||||||
shulkerBoxListener.shutdown();
|
|
||||||
}
|
|
||||||
if (vanishListener != null) {
|
|
||||||
vanishListener.shutdown();
|
|
||||||
}
|
|
||||||
VanishCommand.clearAll(this);
|
VanishCommand.clearAll(this);
|
||||||
unregisterRuntimeListeners();
|
unregisterRuntimeListeners();
|
||||||
unregisterPluginChannels();
|
unregisterPluginChannels();
|
||||||
@@ -111,10 +91,6 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
return moduleManager;
|
return moduleManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public FeatureConfigManager getFeatureConfigManager() {
|
|
||||||
return featureConfigManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MaintenanceManager getMaintenanceManager() {
|
public MaintenanceManager getMaintenanceManager() {
|
||||||
return maintenanceManager;
|
return maintenanceManager;
|
||||||
}
|
}
|
||||||
@@ -123,35 +99,37 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
return teleportRequestManager;
|
return teleportRequestManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PlayerStateManager getPlayerStateManager() {
|
|
||||||
return playerStateManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TpsBarService getTpsBarManager() {
|
public TpsBarService getTpsBarManager() {
|
||||||
return tpsBarManager;
|
return tpsBarManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SkinBridgeManager getSkinBridgeManager() {
|
|
||||||
return skinBridgeManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void reloadRuntimeModules() {
|
public void reloadRuntimeModules() {
|
||||||
moduleStatus.clear();
|
moduleStatus.clear();
|
||||||
refreshCorePlayerFeatures();
|
refreshPlayer();
|
||||||
refreshAdminMode();
|
refreshAdminMode();
|
||||||
refreshMaintenance();
|
refreshMaintenance();
|
||||||
refreshTpsBar();
|
refreshTpsBar();
|
||||||
refreshBlocks();
|
refreshBlocks();
|
||||||
refreshJeiSync();
|
refreshJeiSync();
|
||||||
refreshMobDrops();
|
refreshMobDrops();
|
||||||
refreshSkinBridge();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void refreshCorePlayerFeatures() {
|
private void refreshPlayer() {
|
||||||
if (playerStateManager == null) {
|
if (!moduleManager.isEnabled(ModuleManager.PLAYER)) {
|
||||||
playerStateManager = new PlayerStateManager(this);
|
if (teleportRequestManager != null) {
|
||||||
getServer().getPluginManager().registerEvents(playerStateManager, this);
|
teleportRequestManager.shutdown();
|
||||||
|
HandlerList.unregisterAll(teleportRequestManager);
|
||||||
|
teleportRequestManager = null;
|
||||||
}
|
}
|
||||||
|
VanishCommand.clearAll(this);
|
||||||
|
if (vanishListener != null) {
|
||||||
|
HandlerList.unregisterAll(vanishListener);
|
||||||
|
vanishListener = null;
|
||||||
|
}
|
||||||
|
setModuleStatus("玩家功能", false, "已禁用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (vanishListener == null) {
|
if (vanishListener == null) {
|
||||||
vanishListener = new VanishListener(this);
|
vanishListener = new VanishListener(this);
|
||||||
getServer().getPluginManager().registerEvents(vanishListener, this);
|
getServer().getPluginManager().registerEvents(vanishListener, this);
|
||||||
@@ -162,6 +140,7 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
} else {
|
} else {
|
||||||
teleportRequestManager.reload();
|
teleportRequestManager.reload();
|
||||||
}
|
}
|
||||||
|
setModuleStatus("玩家功能", true, "命令可用");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void refreshAdminMode() {
|
private void refreshAdminMode() {
|
||||||
@@ -178,8 +157,6 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
if (adminModeManager == null) {
|
if (adminModeManager == null) {
|
||||||
adminModeManager = new AdminModeManager(this);
|
adminModeManager = new AdminModeManager(this);
|
||||||
getServer().getPluginManager().registerEvents(adminModeManager, this);
|
getServer().getPluginManager().registerEvents(adminModeManager, this);
|
||||||
} else {
|
|
||||||
adminModeManager.reload();
|
|
||||||
}
|
}
|
||||||
setModuleStatus("管理模式", true, "监听器已注册");
|
setModuleStatus("管理模式", true, "监听器已注册");
|
||||||
}
|
}
|
||||||
@@ -204,7 +181,7 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
maintenanceManager.reload();
|
maintenanceManager.reload();
|
||||||
}
|
}
|
||||||
if (maintenanceListener == null) {
|
if (maintenanceListener == null) {
|
||||||
maintenanceListener = new MaintenanceListener(this, maintenanceManager);
|
maintenanceListener = new MaintenanceListener(this);
|
||||||
getServer().getPluginManager().registerEvents(maintenanceListener, this);
|
getServer().getPluginManager().registerEvents(maintenanceListener, this);
|
||||||
}
|
}
|
||||||
setModuleStatus("维护模式", true, maintenanceManager.isEnabled() ? "当前开启" : "当前关闭");
|
setModuleStatus("维护模式", true, maintenanceManager.isEnabled() ? "当前开启" : "当前关闭");
|
||||||
@@ -242,12 +219,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;
|
||||||
}
|
}
|
||||||
@@ -259,13 +231,6 @@ 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, "命令和潜影盒监听器已启用");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,31 +274,10 @@ 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, "末影人掉落控制已启用");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void refreshSkinBridge() {
|
|
||||||
if (!moduleManager.isEnabled(ModuleManager.SKIN_BRIDGE)) {
|
|
||||||
if (skinBridgeManager != null) {
|
|
||||||
skinBridgeManager.shutdown();
|
|
||||||
HandlerList.unregisterAll(skinBridgeManager);
|
|
||||||
skinBridgeManager = null;
|
|
||||||
}
|
|
||||||
setModuleStatus("皮肤桥接", false, "已禁用");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (skinBridgeManager == null) {
|
|
||||||
skinBridgeManager = new SkinBridgeManager(this);
|
|
||||||
getServer().getPluginManager().registerEvents(skinBridgeManager, this);
|
|
||||||
} else {
|
|
||||||
skinBridgeManager.reload();
|
|
||||||
}
|
|
||||||
setModuleStatus("皮肤桥接", true, skinBridgeManager.getModuleDetail());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void registerPluginChannels() {
|
private void registerPluginChannels() {
|
||||||
Messenger messenger = getServer().getMessenger();
|
Messenger messenger = getServer().getMessenger();
|
||||||
messenger.registerOutgoingPluginChannel(this, "fabric:recipe_sync");
|
messenger.registerOutgoingPluginChannel(this, "fabric:recipe_sync");
|
||||||
@@ -350,14 +294,11 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
unregisterListener(adminModeManager);
|
unregisterListener(adminModeManager);
|
||||||
unregisterListener(maintenanceListener);
|
unregisterListener(maintenanceListener);
|
||||||
unregisterListener(shulkerBoxListener);
|
unregisterListener(shulkerBoxListener);
|
||||||
unregisterListener(blocksMenuCommandListener);
|
|
||||||
unregisterListener(jeiRecipeSyncListener);
|
unregisterListener(jeiRecipeSyncListener);
|
||||||
unregisterListener(mobDropListener);
|
unregisterListener(mobDropListener);
|
||||||
unregisterListener(mobDropMenuListener);
|
unregisterListener(mobDropMenuListener);
|
||||||
unregisterListener(vanishListener);
|
unregisterListener(vanishListener);
|
||||||
unregisterListener(teleportRequestManager);
|
unregisterListener(teleportRequestManager);
|
||||||
unregisterListener(playerStateManager);
|
|
||||||
unregisterListener(skinBridgeManager);
|
|
||||||
if (tpsBarManager instanceof Listener listener) {
|
if (tpsBarManager instanceof Listener listener) {
|
||||||
unregisterListener(listener);
|
unregisterListener(listener);
|
||||||
}
|
}
|
||||||
@@ -379,7 +320,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)) {
|
||||||
@@ -402,7 +343,7 @@ public final class EssentialsC extends JavaPlugin {
|
|||||||
if (!spec.standalone()) {
|
if (!spec.standalone()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
BaseCommand executor = CommandRegistry.getRegisteredCommand(spec.name());
|
BaseCommand executor = CommandRegistry.getCommand(spec.name());
|
||||||
if (executor == null) {
|
if (executor == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -448,15 +389,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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,204 +0,0 @@
|
|||||||
package cn.infstar.essentialsC;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 管理主配置与独立功能配置,并负责按顺序执行配置迁移。
|
|
||||||
*/
|
|
||||||
public final class FeatureConfigManager {
|
|
||||||
|
|
||||||
private static final int MAIN_CONFIG_VERSION = 2;
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final File mainConfigFile;
|
|
||||||
private final File blocksMenuFile;
|
|
||||||
private FileConfiguration blocksMenuConfig;
|
|
||||||
|
|
||||||
public FeatureConfigManager(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.mainConfigFile = new File(plugin.getDataFolder(), "config.yml");
|
|
||||||
this.blocksMenuFile = new File(plugin.getDataFolder(), "blocks-menu.yml");
|
|
||||||
reload();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void reload() {
|
|
||||||
ensureResource(mainConfigFile, "config.yml");
|
|
||||||
ensureResource(blocksMenuFile, "blocks-menu.yml");
|
|
||||||
|
|
||||||
blocksMenuConfig = loadWithDefaults(blocksMenuFile, "blocks-menu.yml");
|
|
||||||
YamlConfiguration loadedMainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
|
||||||
YamlConfiguration mainConfig = migrateMainConfigVersion(loadedMainConfig);
|
|
||||||
|
|
||||||
boolean mainChanged = mainConfig != loadedMainConfig;
|
|
||||||
mainChanged |= migrateLegacyMainConfig(mainConfig);
|
|
||||||
mainChanged |= migrateLegacyDebugSettings(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() {
|
|
||||||
return blocksMenuConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void saveBlocksMenuConfig() {
|
|
||||||
save(blocksMenuConfig, blocksMenuFile);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean updateMainConfigValue(String path, Object value) {
|
|
||||||
YamlConfiguration mainConfig = loadWithDefaults(mainConfigFile, "config.yml");
|
|
||||||
mainConfig.set(path, value);
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
copySection(mainConfig.getConfigurationSection("blocks-menu"), blocksMenuConfig);
|
|
||||||
mainConfig.set("blocks-menu", null);
|
|
||||||
saveBlocksMenuConfig();
|
|
||||||
plugin.getLogger().info("已将便捷菜单配置迁移到 blocks-menu.yml。");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean migrateLegacyDebugSettings(FileConfiguration mainConfig) {
|
|
||||||
boolean hasJeiDebug = mainConfig.contains("jei-sync.debug", true);
|
|
||||||
boolean hasSkinBridgeDebug = mainConfig.contains("skin-bridge.debug", true);
|
|
||||||
if (!hasJeiDebug && !hasSkinBridgeDebug) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean debugEnabled = mainConfig.getBoolean("debug", false)
|
|
||||||
|| mainConfig.getBoolean("jei-sync.debug", false)
|
|
||||||
|| mainConfig.getBoolean("skin-bridge.debug", false);
|
|
||||||
mainConfig.set("debug", debugEnabled);
|
|
||||||
mainConfig.set("jei-sync.debug", null);
|
|
||||||
mainConfig.set("skin-bridge.debug", null);
|
|
||||||
plugin.getLogger().info("已将独立功能调试开关合并到 config.yml 的全局 debug。");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void copySection(ConfigurationSection source, FileConfiguration target) {
|
|
||||||
if (source == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (String path : source.getKeys(true)) {
|
|
||||||
if (!source.isConfigurationSection(path)) {
|
|
||||||
target.set(path, source.get(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private YamlConfiguration loadWithDefaults(File file, String resourcePath) {
|
|
||||||
YamlConfiguration config = loadFile(file);
|
|
||||||
YamlConfiguration defaults = loadResource(resourcePath);
|
|
||||||
if (defaults != null) {
|
|
||||||
config.setDefaults(defaults);
|
|
||||||
config.options().copyDefaults(true);
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
if (!file.exists()) {
|
|
||||||
plugin.saveResource(resourcePath, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean save(FileConfiguration config, File file) {
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(config, file);
|
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
plugin.getLogger().warning("保存 " + file.getName() + " 失败: " + exception.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package cn.infstar.essentialsC;
|
package cn.infstar.essentialsC;
|
||||||
|
|
||||||
import net.kyori.adventure.text.Component;
|
import org.bukkit.ChatColor;
|
||||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
|
||||||
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,41 +10,29 @@ 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;
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
public class LangManager {
|
public class LangManager {
|
||||||
|
|
||||||
private static final Pattern HEX_COLOR_PATTERN = Pattern.compile("(?i)&#([0-9a-f]{6})");
|
private static final int CURRENT_CONFIG_VERSION = 2;
|
||||||
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 LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.legacyAmpersand();
|
|
||||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
|
||||||
private static final Map<String, String> THEME_COLORS = Map.of(
|
|
||||||
"&a", "�fb9a",
|
|
||||||
"&b", "ᒦff",
|
|
||||||
"&c", "&#ff7e5e",
|
|
||||||
"&d", "&#c160ff",
|
|
||||||
"&e", "&#ffc43b",
|
|
||||||
"&6", "&#f5c962"
|
|
||||||
);
|
|
||||||
|
|
||||||
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPrefix() {
|
public String getPrefix() {
|
||||||
return renderToLegacy(langFile.getString("prefix", "&6[EssentialsC] &r"));
|
return translateColorCodes(langFile.getString("prefix", "&6[EssentialsC] &r"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getString(String path) {
|
public String getString(String path) {
|
||||||
@@ -54,40 +40,11 @@ public class LangManager {
|
|||||||
if (value == null) {
|
if (value == null) {
|
||||||
return translateColorCodes("&c缺少语言文本: " + path);
|
return translateColorCodes("&c缺少语言文本: " + path);
|
||||||
}
|
}
|
||||||
return renderToLegacy(value);
|
return translateColorCodes(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getString(String path, Map<String, String> placeholders) {
|
public String getString(String path, Map<String, String> placeholders) {
|
||||||
String value = langFile.getString(path);
|
return applyPlaceholders(getString(path), placeholders);
|
||||||
if (value == null) {
|
|
||||||
return translateColorCodes("&c缺少语言文本: " + path);
|
|
||||||
}
|
|
||||||
return renderToLegacy(applyPlaceholders(value, placeholders));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Component getComponent(String path) {
|
|
||||||
return getComponent(path, Map.of());
|
|
||||||
}
|
|
||||||
|
|
||||||
public Component getComponent(String path, Map<String, String> placeholders) {
|
|
||||||
String value = langFile.getString(path);
|
|
||||||
if (value == null) {
|
|
||||||
return LEGACY_SECTION.deserialize(translateColorCodes("&c缺少语言文本: " + path));
|
|
||||||
}
|
|
||||||
|
|
||||||
return renderToComponent(applyPlaceholders(value, placeholders));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Component getPrefixedComponent(String path) {
|
|
||||||
return getPrefixedComponent(path, Map.of());
|
|
||||||
}
|
|
||||||
|
|
||||||
public Component getPrefixedComponent(String path, Map<String, String> placeholders) {
|
|
||||||
String value = langFile.getString(path);
|
|
||||||
if (value == null) {
|
|
||||||
return LEGACY_SECTION.deserialize(getPrefix() + translateColorCodes("&c缺少语言文本: " + path));
|
|
||||||
}
|
|
||||||
return renderToComponent(langFile.getString("prefix", "") + applyPlaceholders(value, placeholders));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPrefixedString(String path) {
|
public String getPrefixedString(String path) {
|
||||||
@@ -106,12 +63,13 @@ public class LangManager {
|
|||||||
|
|
||||||
List<String> translated = new ArrayList<>();
|
List<String> translated = new ArrayList<>();
|
||||||
for (String value : values) {
|
for (String value : values) {
|
||||||
translated.add(renderToLegacy(value));
|
translated.add(translateColorCodes(value));
|
||||||
}
|
}
|
||||||
return translated;
|
return translated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
|
loadConfig();
|
||||||
loadLanguage();
|
loadLanguage();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,8 +77,58 @@ 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);
|
||||||
|
|
||||||
|
try {
|
||||||
|
config.save(configFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().severe("保存 config.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void migrateConfigIfNeeded(File configFile) {
|
||||||
|
FileConfiguration existingConfig = YamlConfiguration.loadConfiguration(configFile);
|
||||||
|
int existingVersion = existingConfig.getInt("config-version", 0);
|
||||||
|
if (existingVersion <= 0 || 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 defaultConfig = YamlConfiguration.loadConfiguration(
|
||||||
|
new InputStreamReader(defaultConfigStream, StandardCharsets.UTF_8)
|
||||||
|
);
|
||||||
|
existingConfig.setDefaults(defaultConfig);
|
||||||
|
existingConfig.options().copyDefaults(true);
|
||||||
|
}
|
||||||
|
existingConfig.set("config-version", CURRENT_CONFIG_VERSION);
|
||||||
|
existingConfig.save(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()) {
|
||||||
@@ -144,107 +152,26 @@ public class LangManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void loadDefaultLanguageFallback() {
|
private void loadDefaultLanguageFallback() {
|
||||||
InputStream selectedLangStream = plugin.getResource("lang/" + currentLanguage + ".yml");
|
InputStream defaultLangStream = plugin.getResource("lang/en_US.yml");
|
||||||
if (selectedLangStream == null) {
|
if (defaultLangStream == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
YamlConfiguration selectedDefaults = YamlConfiguration.loadConfiguration(
|
YamlConfiguration defaultLang = YamlConfiguration.loadConfiguration(
|
||||||
new InputStreamReader(selectedLangStream, StandardCharsets.UTF_8)
|
new InputStreamReader(defaultLangStream, StandardCharsets.UTF_8)
|
||||||
);
|
);
|
||||||
if (!"en_US".equalsIgnoreCase(currentLanguage)) {
|
langFile.setDefaults(defaultLang);
|
||||||
InputStream englishLangStream = plugin.getResource("lang/en_US.yml");
|
|
||||||
if (englishLangStream != null) {
|
|
||||||
YamlConfiguration englishDefaults = YamlConfiguration.loadConfiguration(
|
|
||||||
new InputStreamReader(englishLangStream, StandardCharsets.UTF_8)
|
|
||||||
);
|
|
||||||
selectedDefaults.setDefaults(englishDefaults);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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() + "}", entry.getValue());
|
||||||
? escapeMiniMessageReplacement(entry.getValue())
|
|
||||||
: entry.getValue();
|
|
||||||
result = result.replace("{" + entry.getKey() + "}", replacement == null ? "" : replacement);
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
static String escapeMiniMessageReplacement(String value) {
|
|
||||||
if (value == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
if (value.indexOf('§') >= 0) {
|
|
||||||
return MINI_MESSAGE.serialize(LEGACY_SECTION.deserialize(value));
|
|
||||||
}
|
|
||||||
return value.replace("\\", "\\\\").replace("<", "\\<");
|
|
||||||
}
|
|
||||||
|
|
||||||
private String translateColorCodes(String text) {
|
private String translateColorCodes(String text) {
|
||||||
if (text == null) {
|
return text == null ? "" : ChatColor.translateAlternateColorCodes('&', text);
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
String themedText = text;
|
|
||||||
for (Map.Entry<String, String> color : THEME_COLORS.entrySet()) {
|
|
||||||
themedText = themedText.replace(color.getKey(), color.getValue());
|
|
||||||
}
|
|
||||||
return LEGACY_SECTION.serialize(LEGACY_AMPERSAND.deserialize(expandHexColors(themedText)));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String expandHexColors(String text) {
|
|
||||||
Matcher matcher = HEX_COLOR_PATTERN.matcher(text);
|
|
||||||
StringBuilder result = new StringBuilder();
|
|
||||||
while (matcher.find()) {
|
|
||||||
String hex = matcher.group(1);
|
|
||||||
StringBuilder legacyHex = new StringBuilder("&x");
|
|
||||||
for (char digit : hex.toCharArray()) {
|
|
||||||
legacyHex.append('&').append(digit);
|
|
||||||
}
|
|
||||||
matcher.appendReplacement(result, Matcher.quoteReplacement(legacyHex.toString()));
|
|
||||||
}
|
|
||||||
matcher.appendTail(result);
|
|
||||||
return result.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String renderToLegacy(String text) {
|
|
||||||
return LEGACY_SECTION.serialize(renderToComponent(text));
|
|
||||||
}
|
|
||||||
|
|
||||||
private Component renderToComponent(String text) {
|
|
||||||
if (text == null) {
|
|
||||||
return Component.empty();
|
|
||||||
}
|
|
||||||
if (looksLikeMiniMessage(text)) {
|
|
||||||
try {
|
|
||||||
return MINI_MESSAGE.deserialize(normalizeMiniMessageTags(text));
|
|
||||||
} catch (RuntimeException ignored) {
|
|
||||||
// 配置中 MiniMessage 语法错误时回退到旧颜色码解析,避免消息完全不可用。
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return LEGACY_SECTION.deserialize(translateColorCodes(text));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean looksLikeMiniMessage(String text) {
|
|
||||||
int open = text.indexOf('<');
|
|
||||||
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,7 +1,6 @@
|
|||||||
package cn.infstar.essentialsC;
|
package cn.infstar.essentialsC;
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
@@ -15,23 +14,23 @@ public final class ModuleManager {
|
|||||||
private static final int CURRENT_CONFIG_VERSION = 1;
|
private static final int CURRENT_CONFIG_VERSION = 1;
|
||||||
|
|
||||||
public static final String BLOCKS = "blocks";
|
public static final String BLOCKS = "blocks";
|
||||||
|
public static final String PLAYER = "player";
|
||||||
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 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 MAINTENANCE = "maintenance";
|
||||||
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<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
DEFAULT_MODULES.put(BLOCKS, true);
|
DEFAULT_MODULES.put(BLOCKS, true);
|
||||||
|
DEFAULT_MODULES.put(PLAYER, 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(JEI_SYNC, true);
|
||||||
DEFAULT_MODULES.put(MOB_DROPS, false);
|
DEFAULT_MODULES.put(MOB_DROPS, false);
|
||||||
DEFAULT_MODULES.put(MAINTENANCE, true);
|
DEFAULT_MODULES.put(MAINTENANCE, true);
|
||||||
DEFAULT_MODULES.put(SKIN_BRIDGE, false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private final JavaPlugin plugin;
|
private final JavaPlugin plugin;
|
||||||
@@ -49,20 +48,13 @@ 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;
|
|
||||||
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);
|
||||||
|
save();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEnabled(String moduleKey) {
|
public boolean isEnabled(String moduleKey) {
|
||||||
@@ -76,4 +68,11 @@ public final class ModuleManager {
|
|||||||
return "modules." + moduleKey + ".enabled";
|
return "modules." + moduleKey + ".enabled";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void save() {
|
||||||
|
try {
|
||||||
|
modulesConfig.save(modulesFile);
|
||||||
|
} catch (IOException e) {
|
||||||
|
plugin.getLogger().warning("保存 modules.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package cn.infstar.essentialsC.admin;
|
package cn.infstar.essentialsC.admin;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||||
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 +16,8 @@ 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.io.IOException;
|
||||||
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 +30,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,24 +39,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() {
|
|
||||||
if (actionBarTask != null) {
|
|
||||||
actionBarTask.cancel();
|
|
||||||
actionBarTask = null;
|
|
||||||
}
|
|
||||||
float flySpeed = getAdminFlySpeed();
|
|
||||||
for (UUID uuid : new ArrayList<>(activePlayers)) {
|
|
||||||
Player player = plugin.getServer().getPlayer(uuid);
|
|
||||||
if (player != null && player.isOnline()) {
|
|
||||||
player.setFlySpeed(flySpeed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!activePlayers.isEmpty()) {
|
|
||||||
startActionBarTask();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isAdminMode(Player player) {
|
public boolean isAdminMode(Player player) {
|
||||||
@@ -78,37 +67,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,77 +94,47 @@ 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);
|
|
||||||
if (!saveData(player, data)) {
|
|
||||||
sendLangMessage(player, "admin-mode.messages.save-failed");
|
|
||||||
data.set("active", false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!loadProfile(player, data, "admin")) {
|
if (!loadProfile(player, playerPath + ".admin")) {
|
||||||
clearInventory(player);
|
clearInventory(player);
|
||||||
}
|
}
|
||||||
|
|
||||||
activePlayers.add(player.getUniqueId());
|
activePlayers.add(player.getUniqueId());
|
||||||
|
data.set(playerPath + ".active", true);
|
||||||
|
|
||||||
player.setGameMode(GameMode.CREATIVE);
|
player.setGameMode(GameMode.CREATIVE);
|
||||||
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 +143,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 +164,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 +192,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 +208,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 +216,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 +227,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;
|
||||||
@@ -327,7 +270,9 @@ public final class AdminModeManager implements Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void sendActionBar(Player player) {
|
private void sendActionBar(Player player) {
|
||||||
player.sendActionBar(EssentialsC.getLangManager().getComponent("admin-mode.actionbar"));
|
String text = EssentialsC.getLangManager().getString("admin-mode.actionbar");
|
||||||
|
Component component = LegacyComponentSerializer.legacyAmpersand().deserialize(text);
|
||||||
|
player.sendActionBar(component);
|
||||||
}
|
}
|
||||||
|
|
||||||
private float getAdminFlySpeed() {
|
private float getAdminFlySpeed() {
|
||||||
@@ -371,17 +316,26 @@ 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 void saveData() {
|
||||||
return store.save(player.getUniqueId(), data);
|
try {
|
||||||
|
data.save(dataFile);
|
||||||
|
} catch (IOException e) {
|
||||||
|
plugin.getLogger().warning("保存 admin-mode.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addConfigDefaults() {
|
private void addConfigDefaults() {
|
||||||
plugin.getConfig().addDefault("admin-mode.fly-speed", 0.2D);
|
plugin.getConfig().addDefault("admin-mode.fly-speed", 0.2D);
|
||||||
plugin.getConfig().addDefault("admin-mode.actionbar.interval-ticks", 40);
|
plugin.getConfig().addDefault("admin-mode.actionbar.interval-ticks", 40);
|
||||||
plugin.getConfig().options().copyDefaults(true);
|
plugin.getConfig().options().copyDefaults(true);
|
||||||
|
plugin.saveConfig();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.Location;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Cancellable;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportEvent extends Event implements Cancellable {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player player;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private Location destination;
|
|
||||||
private boolean cancelled;
|
|
||||||
|
|
||||||
public TeleportEvent(Player player, TeleportRequest request, Location destination) {
|
|
||||||
this.player = player;
|
|
||||||
this.request = request;
|
|
||||||
this.destination = destination.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayer() {
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Location getDestination() {
|
|
||||||
return destination.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDestination(Location destination) {
|
|
||||||
this.destination = destination.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCancelled() {
|
|
||||||
return cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCancelled(boolean cancelled) {
|
|
||||||
this.cancelled = cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Cancellable;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportRequestReceiveEvent extends Event implements Cancellable {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player recipient;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private boolean cancelled;
|
|
||||||
|
|
||||||
public TeleportRequestReceiveEvent(Player recipient, TeleportRequest request) {
|
|
||||||
this.recipient = recipient;
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getRecipient() {
|
|
||||||
return recipient;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCancelled() {
|
|
||||||
return cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCancelled(boolean cancelled) {
|
|
||||||
this.cancelled = cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Cancellable;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportRequestReplyEvent extends Event implements Cancellable {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player recipient;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private boolean cancelled;
|
|
||||||
|
|
||||||
public TeleportRequestReplyEvent(Player recipient, TeleportRequest request) {
|
|
||||||
this.recipient = recipient;
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getRecipient() {
|
|
||||||
return recipient;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isAccepted() {
|
|
||||||
return request.status() == TeleportRequest.Status.ACCEPTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCancelled() {
|
|
||||||
return cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCancelled(boolean cancelled) {
|
|
||||||
this.cancelled = cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Cancellable;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportRequestSendEvent extends Event implements Cancellable {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player sender;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private boolean cancelled;
|
|
||||||
|
|
||||||
public TeleportRequestSendEvent(Player sender, TeleportRequest request) {
|
|
||||||
this.sender = sender;
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getSender() {
|
|
||||||
return sender;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCancelled() {
|
|
||||||
return cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCancelled(boolean cancelled) {
|
|
||||||
this.cancelled = cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportWarmupCancelledEvent extends Event {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player player;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private final int durationSeconds;
|
|
||||||
private final int elapsedSeconds;
|
|
||||||
private final Reason reason;
|
|
||||||
|
|
||||||
public TeleportWarmupCancelledEvent(Player player, TeleportRequest request, int durationSeconds,
|
|
||||||
int elapsedSeconds, Reason reason) {
|
|
||||||
this.player = player;
|
|
||||||
this.request = request;
|
|
||||||
this.durationSeconds = durationSeconds;
|
|
||||||
this.elapsedSeconds = elapsedSeconds;
|
|
||||||
this.reason = reason;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayer() {
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getDurationSeconds() {
|
|
||||||
return durationSeconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getElapsedSeconds() {
|
|
||||||
return elapsedSeconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Reason getReason() {
|
|
||||||
return reason;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum Reason {
|
|
||||||
PLAYER_MOVE,
|
|
||||||
PLAYER_DAMAGE,
|
|
||||||
PLAYER_QUIT,
|
|
||||||
PLUGIN_SHUTDOWN
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.api.event;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager.TeleportRequest;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.event.Cancellable;
|
|
||||||
import org.bukkit.event.Event;
|
|
||||||
import org.bukkit.event.HandlerList;
|
|
||||||
|
|
||||||
public final class TeleportWarmupEvent extends Event implements Cancellable {
|
|
||||||
|
|
||||||
private static final HandlerList HANDLERS = new HandlerList();
|
|
||||||
|
|
||||||
private final Player player;
|
|
||||||
private final TeleportRequest request;
|
|
||||||
private final int durationSeconds;
|
|
||||||
private boolean cancelled;
|
|
||||||
|
|
||||||
public TeleportWarmupEvent(Player player, TeleportRequest request, int durationSeconds) {
|
|
||||||
this.player = player;
|
|
||||||
this.request = request;
|
|
||||||
this.durationSeconds = durationSeconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayer() {
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TeleportRequest getRequest() {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getDurationSeconds() {
|
|
||||||
return durationSeconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCancelled() {
|
|
||||||
return cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setCancelled(boolean cancelled) {
|
|
||||||
this.cancelled = cancelled;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public HandlerList getHandlers() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HandlerList getHandlerList() {
|
|
||||||
return HANDLERS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,10 +1,10 @@
|
|||||||
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;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
|
||||||
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;
|
||||||
@@ -15,8 +15,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 +24,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 +44,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,10 +58,9 @@ 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();
|
var sectionsConfig = plugin.getConfig().getConfigurationSection("blocks-menu.sections");
|
||||||
var sectionsConfig = menuConfig.getConfigurationSection("sections");
|
|
||||||
if (sectionsConfig != null) {
|
if (sectionsConfig != null) {
|
||||||
int visibleSections = renderSections(menu, player, sectionsConfig);
|
int visibleSections = renderSections(menu, player, sectionsConfig);
|
||||||
if (visibleSections > 1) {
|
if (visibleSections > 1) {
|
||||||
@@ -72,7 +75,7 @@ public class BlocksMenuCommand extends BaseCommand implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var itemsConfig = menuConfig.getConfigurationSection("items");
|
var itemsConfig = plugin.getConfig().getConfigurationSection("blocks-menu.items");
|
||||||
if (itemsConfig == null) {
|
if (itemsConfig == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -165,10 +168,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 +182,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,74 +248,71 @@ 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() {
|
||||||
FileConfiguration config = plugin.getFeatureConfigManager().getBlocksMenuConfig();
|
plugin.getConfig().addDefault("blocks-menu.layout-version", 2);
|
||||||
config.addDefault("config-version", 1);
|
|
||||||
config.addDefault("layout-version", 2);
|
|
||||||
|
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.workbench", 10, "CRAFTING_TABLE",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.workbench", 10, "CRAFTING_TABLE",
|
||||||
"essentialsc.command.workbench", "workbench");
|
"essentialsc.command.workbench", "workbench");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.enderchest", 11, "ENDER_CHEST",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.enderchest", 11, "ENDER_CHEST",
|
||||||
"essentialsc.command.enderchest", "enderchest");
|
"essentialsc.command.enderchest", "enderchest");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.anvil", 12, "ANVIL",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.anvil", 12, "ANVIL",
|
||||||
"essentialsc.command.anvil", "anvil");
|
"essentialsc.command.anvil", "anvil");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.grindstone", 19, "GRINDSTONE",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.grindstone", 19, "GRINDSTONE",
|
||||||
"essentialsc.command.grindstone", "grindstone");
|
"essentialsc.command.grindstone", "grindstone");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.smithingtable", 20, "SMITHING_TABLE",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.smithingtable", 20, "SMITHING_TABLE",
|
||||||
"essentialsc.command.smithingtable", "smithingtable");
|
"essentialsc.command.smithingtable", "smithingtable");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.stonecutter", 21, "STONECUTTER",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.stonecutter", 21, "STONECUTTER",
|
||||||
"essentialsc.command.stonecutter", "stonecutter");
|
"essentialsc.command.stonecutter", "stonecutter");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.loom", 28, "LOOM",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.loom", 28, "LOOM",
|
||||||
"essentialsc.command.loom", "loom");
|
"essentialsc.command.loom", "loom");
|
||||||
addMenuItemDefaults(config, "sections.blocks.items.cartographytable", 29, "CARTOGRAPHY_TABLE",
|
addMenuItemDefaults("blocks-menu.sections.blocks.items.cartographytable", 29, "CARTOGRAPHY_TABLE",
|
||||||
"essentialsc.command.cartographytable", "cartographytable");
|
"essentialsc.command.cartographytable", "cartographytable");
|
||||||
|
|
||||||
addMenuItemDefaults(config, "sections.shortcuts.items.nightvision", 14, "TINTED_GLASS",
|
addMenuItemDefaults("blocks-menu.sections.shortcuts.items.nightvision", 14, "TINTED_GLASS",
|
||||||
"essentialsc.command.nightvision", "nightvision");
|
"essentialsc.command.nightvision", "nightvision");
|
||||||
addMenuItemDefaults(config, "sections.shortcuts.items.glow", 15, "GLOWSTONE",
|
addMenuItemDefaults("blocks-menu.sections.shortcuts.items.glow", 15, "GLOWSTONE",
|
||||||
"essentialsc.command.glow", "glow");
|
"essentialsc.command.glow", "glow");
|
||||||
|
|
||||||
config.options().copyDefaults(true);
|
plugin.getConfig().options().copyDefaults(true);
|
||||||
migrateLayoutIfNeeded(config);
|
migrateLayoutIfNeeded();
|
||||||
plugin.getFeatureConfigManager().saveBlocksMenuConfig();
|
plugin.saveConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void migrateLayoutIfNeeded(FileConfiguration config) {
|
private void migrateLayoutIfNeeded() {
|
||||||
boolean hasStoredLayoutVersion = config.contains("layout-version", true);
|
boolean hasStoredLayoutVersion = plugin.getConfig().contains("blocks-menu.layout-version", true);
|
||||||
if (hasStoredLayoutVersion && config.getInt("layout-version", 0) >= 2) {
|
if (hasStoredLayoutVersion && plugin.getConfig().getInt("blocks-menu.layout-version", 0) >= 2) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
applySlot(config, "blocks", "workbench", 10);
|
applySlot("blocks", "workbench", 10);
|
||||||
applySlot(config, "blocks", "enderchest", 11);
|
applySlot("blocks", "enderchest", 11);
|
||||||
applySlot(config, "blocks", "anvil", 12);
|
applySlot("blocks", "anvil", 12);
|
||||||
applySlot(config, "blocks", "grindstone", 19);
|
applySlot("blocks", "grindstone", 19);
|
||||||
applySlot(config, "blocks", "smithingtable", 20);
|
applySlot("blocks", "smithingtable", 20);
|
||||||
applySlot(config, "blocks", "stonecutter", 21);
|
applySlot("blocks", "stonecutter", 21);
|
||||||
applySlot(config, "blocks", "loom", 28);
|
applySlot("blocks", "loom", 28);
|
||||||
applySlot(config, "blocks", "cartographytable", 29);
|
applySlot("blocks", "cartographytable", 29);
|
||||||
applySlot(config, "shortcuts", "nightvision", 14);
|
applySlot("shortcuts", "nightvision", 14);
|
||||||
applySlot(config, "shortcuts", "glow", 15);
|
applySlot("shortcuts", "glow", 15);
|
||||||
|
|
||||||
config.set("sections.blocks.title-item", null);
|
plugin.getConfig().set("blocks-menu.sections.blocks.title-item", null);
|
||||||
config.set("sections.shortcuts.title-item", null);
|
plugin.getConfig().set("blocks-menu.sections.shortcuts.title-item", null);
|
||||||
config.set("layout-version", 2);
|
plugin.getConfig().set("blocks-menu.layout-version", 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void applySlot(FileConfiguration config, String section, String key, int slot) {
|
private void applySlot(String section, String key, int slot) {
|
||||||
config.set("sections." + section + ".items." + key + ".slot", slot);
|
plugin.getConfig().set("blocks-menu.sections." + section + ".items." + key + ".slot", slot);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addMenuItemDefaults(FileConfiguration config, String path, int slot, String material,
|
private void addMenuItemDefaults(String path, int slot, String material, String permission, String command) {
|
||||||
String permission, String command) {
|
plugin.getConfig().addDefault(path + ".slot", slot);
|
||||||
config.addDefault(path + ".slot", slot);
|
plugin.getConfig().addDefault(path + ".material", material);
|
||||||
config.addDefault(path + ".material", material);
|
plugin.getConfig().addDefault(path + ".permission", permission);
|
||||||
config.addDefault(path + ".permission", permission);
|
plugin.getConfig().addDefault(path + ".command", command);
|
||||||
config.addDefault(path + ".command", command);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private record MenuItem(int slot, Material material, String name, List<String> lore, String commandKey) {
|
private record MenuItem(int slot, Material material, String name, List<String> lore, String commandKey) {
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import cn.infstar.essentialsC.EssentialsC;
|
|||||||
import cn.infstar.essentialsC.ModuleManager;
|
import cn.infstar.essentialsC.ModuleManager;
|
||||||
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
import cn.infstar.essentialsC.tpsbar.TpsBarService;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -11,7 +12,6 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.Supplier;
|
|
||||||
|
|
||||||
public final class CommandRegistry {
|
public final class CommandRegistry {
|
||||||
|
|
||||||
@@ -21,57 +21,51 @@ public final class CommandRegistry {
|
|||||||
private static final Set<String> UNAVAILABLE_COMMANDS = new java.util.HashSet<>();
|
private static final Set<String> UNAVAILABLE_COMMANDS = new java.util.HashSet<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
register("workbench", "essentialsc.command.workbench", ModuleManager.BLOCKS, WorkbenchCommand::new, "wb");
|
register("workbench", "essentialsc.command.workbench", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.WorkbenchCommand", "wb");
|
||||||
register("anvil", "essentialsc.command.anvil", ModuleManager.BLOCKS, AnvilCommand::new);
|
register("anvil", "essentialsc.command.anvil", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.AnvilCommand");
|
||||||
register("cartographytable", "essentialsc.command.cartographytable", ModuleManager.BLOCKS, CartographyTableCommand::new, "ct", "cartography");
|
register("cartographytable", "essentialsc.command.cartographytable", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.CartographyTableCommand", "ct", "cartography");
|
||||||
register("grindstone", "essentialsc.command.grindstone", ModuleManager.BLOCKS, GrindstoneCommand::new, "gs");
|
register("grindstone", "essentialsc.command.grindstone", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.GrindstoneCommand", "gs");
|
||||||
register("loom", "essentialsc.command.loom", ModuleManager.BLOCKS, LoomCommand::new);
|
register("loom", "essentialsc.command.loom", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.LoomCommand");
|
||||||
register("smithingtable", "essentialsc.command.smithingtable", ModuleManager.BLOCKS, SmithingTableCommand::new, "st", "smithing");
|
register("smithingtable", "essentialsc.command.smithingtable", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.SmithingTableCommand", "st", "smithing");
|
||||||
register("stonecutter", "essentialsc.command.stonecutter", ModuleManager.BLOCKS, StonecutterCommand::new, "sc");
|
register("stonecutter", "essentialsc.command.stonecutter", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.StonecutterCommand", "sc");
|
||||||
register("enderchest", "essentialsc.command.enderchest", ModuleManager.BLOCKS, EnderChestCommand::new, "ec");
|
register("enderchest", "essentialsc.command.enderchest", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.EnderChestCommand", "ec");
|
||||||
register("blocks", "essentialsc.command.blocks", ModuleManager.BLOCKS, BlocksMenuCommand::new);
|
register("blocks", "essentialsc.command.blocks", ModuleManager.BLOCKS, "cn.infstar.essentialsC.commands.BlocksMenuCommand");
|
||||||
registerCore("hat", "essentialsc.command.hat", HatCommand::new);
|
register("hat", "essentialsc.command.hat", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.HatCommand");
|
||||||
registerCore("suicide", "essentialsc.command.suicide", SuicideCommand::new, "die");
|
register("suicide", "essentialsc.command.suicide", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.SuicideCommand", "die");
|
||||||
registerCore("fly", "essentialsc.command.fly", FlyCommand::new);
|
register("fly", "essentialsc.command.fly", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.FlyCommand");
|
||||||
registerCore("nightvision", "essentialsc.command.nightvision", NightVisionCommand::new, "nv");
|
register("nightvision", "essentialsc.command.nightvision", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.NightVisionCommand", "nv");
|
||||||
registerCore("glow", "essentialsc.command.glow", GlowCommand::new);
|
register("glow", "essentialsc.command.glow", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.GlowCommand");
|
||||||
registerCore("heal", "essentialsc.command.heal", HealCommand::new);
|
register("heal", "essentialsc.command.heal", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.HealCommand");
|
||||||
registerCore("vanish", "essentialsc.command.vanish", VanishCommand::new, "v");
|
register("vanish", "essentialsc.command.vanish", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.VanishCommand", "v");
|
||||||
registerCore("seen", "essentialsc.command.seen", SeenCommand::new, "info");
|
register("seen", "essentialsc.command.seen", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.SeenCommand", "info");
|
||||||
registerCore("feed", "essentialsc.command.feed", FeedCommand::new);
|
register("feed", "essentialsc.command.feed", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.FeedCommand");
|
||||||
registerCore("repair", "essentialsc.command.repair", RepairCommand::new, "rep");
|
register("repair", "essentialsc.command.repair", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.RepairCommand", "rep");
|
||||||
registerCore("tpa", "essentialsc.command.tpa", TpaCommand::new);
|
register("tpa", "essentialsc.command.tpa", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpaCommand");
|
||||||
registerCore("tpahere", "essentialsc.command.tpahere", TpaHereCommand::new);
|
register("tpahere", "essentialsc.command.tpahere", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpaHereCommand");
|
||||||
registerCore("tpaall", "essentialsc.command.tpaall", TpaAllCommand::new);
|
register("tpaall", "essentialsc.command.tpaall", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpaAllCommand");
|
||||||
registerCore("tpaccept", "essentialsc.command.tpaccept", TpAcceptCommand::new, "tpyes");
|
register("tpaccept", "essentialsc.command.tpaccept", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpAcceptCommand", "tpyes");
|
||||||
registerCore("tpdeny", "essentialsc.command.tpdeny", TpDenyCommand::new, "tpdecline", "tpno");
|
register("tpdeny", "essentialsc.command.tpdeny", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpDenyCommand", "tpdecline", "tpno");
|
||||||
registerCore("tpignore", "essentialsc.command.tpignore", TpIgnoreCommand::new);
|
register("tpignore", "essentialsc.command.tpignore", ModuleManager.PLAYER, "cn.infstar.essentialsC.commands.TpIgnoreCommand");
|
||||||
register("tpsbar", "essentialsc.command.tpsbar", ModuleManager.TPSBAR, TpsBarCommand::new);
|
register("tpsbar", "essentialsc.command.tpsbar", ModuleManager.TPSBAR, "cn.infstar.essentialsC.commands.TpsBarCommand");
|
||||||
register("mobdrops", "essentialsc.mobdrops.enderman", ModuleManager.MOB_DROPS, MobDropCommand::new);
|
register("mobdrops", "essentialsc.mobdrops.enderman", ModuleManager.MOB_DROPS, "cn.infstar.essentialsC.commands.MobDropCommand");
|
||||||
register("maintenance", "essentialsc.command.maintenance", ModuleManager.MAINTENANCE, MaintenanceCommand::new, "maint");
|
register("maintenance", "essentialsc.command.maintenance", ModuleManager.MAINTENANCE, "cn.infstar.essentialsC.commands.MaintenanceCommand", "maint");
|
||||||
registerSubCommand("admin", "essentialsc.command.admin", ModuleManager.ADMIN_MODE, AdminCommand::new);
|
registerSubCommand("admin", "essentialsc.command.admin", ModuleManager.ADMIN_MODE, "cn.infstar.essentialsC.commands.AdminCommand");
|
||||||
registerSubCommand("skin", "essentialsc.command.skin", ModuleManager.SKIN_BRIDGE, SkinBridgeCommand::new);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandRegistry() {
|
private CommandRegistry() {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void registerCore(String name, String permission, Supplier<BaseCommand> factory, String... aliases) {
|
private static void register(String name, String permission, String moduleKey, String className, String... aliases) {
|
||||||
register(name, permission, null, factory, aliases);
|
register(name, permission, moduleKey, className, true, aliases);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void register(String name, String permission, String moduleKey, Supplier<BaseCommand> factory, String... aliases) {
|
private static void registerSubCommand(String name, String permission, String moduleKey, String className, String... aliases) {
|
||||||
register(name, permission, moduleKey, factory, true, aliases);
|
register(name, permission, moduleKey, className, false, aliases);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void registerSubCommand(String name, String permission, String moduleKey, Supplier<BaseCommand> factory, String... aliases) {
|
private static void register(String name, String permission, String moduleKey, String className, boolean standalone, String... aliases) {
|
||||||
register(name, permission, moduleKey, factory, false, aliases);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void register(String name, String permission, String moduleKey, Supplier<BaseCommand> factory,
|
|
||||||
boolean standalone, String... aliases) {
|
|
||||||
List<String> aliasList = List.of(aliases);
|
List<String> aliasList = List.of(aliases);
|
||||||
CommandSpec spec = new CommandSpec(name, permission, moduleKey, factory, aliasList, standalone);
|
CommandSpec spec = new CommandSpec(name, permission, moduleKey, className, aliasList, standalone);
|
||||||
COMMANDS.put(name, spec);
|
COMMANDS.put(name, spec);
|
||||||
ALIAS_TO_COMMAND.put(name, name);
|
ALIAS_TO_COMMAND.put(name, name);
|
||||||
for (String alias : aliasList) {
|
for (String alias : aliasList) {
|
||||||
@@ -91,8 +85,7 @@ public final class CommandRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isAvailable(String name) {
|
public static boolean isAvailable(String name) {
|
||||||
String resolvedName = resolveCommandName(name);
|
return getCommand(name) != null;
|
||||||
return resolvedName != null && !isRuntimeDisabled(resolvedName) && getRegisteredCommand(resolvedName) != null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getPermission(String name) {
|
public static String getPermission(String name) {
|
||||||
@@ -110,15 +103,6 @@ public final class CommandRegistry {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return getRegisteredCommand(resolvedName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static BaseCommand getRegisteredCommand(String name) {
|
|
||||||
String resolvedName = resolveCommandName(name);
|
|
||||||
if (resolvedName == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
BaseCommand cached = COMMAND_CACHE.get(resolvedName);
|
BaseCommand cached = COMMAND_CACHE.get(resolvedName);
|
||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
return cached;
|
return cached;
|
||||||
@@ -133,16 +117,18 @@ public final class CommandRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
BaseCommand command = spec.factory().get();
|
Class<?> rawClass = Class.forName(spec.className());
|
||||||
|
if (!BaseCommand.class.isAssignableFrom(rawClass)) {
|
||||||
|
UNAVAILABLE_COMMANDS.add(resolvedName);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Constructor<? extends BaseCommand> constructor = rawClass.asSubclass(BaseCommand.class).getDeclaredConstructor();
|
||||||
|
BaseCommand command = constructor.newInstance();
|
||||||
COMMAND_CACHE.put(resolvedName, command);
|
COMMAND_CACHE.put(resolvedName, command);
|
||||||
return command;
|
return command;
|
||||||
} catch (RuntimeException | LinkageError exception) {
|
} catch (ReflectiveOperationException | LinkageError ignored) {
|
||||||
UNAVAILABLE_COMMANDS.add(resolvedName);
|
UNAVAILABLE_COMMANDS.add(resolvedName);
|
||||||
try {
|
|
||||||
EssentialsC.getPlugin(EssentialsC.class).getLogger()
|
|
||||||
.warning("初始化命令 /" + resolvedName + " 失败: " + exception.getMessage());
|
|
||||||
} catch (IllegalStateException ignored) {
|
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -176,11 +162,11 @@ public final class CommandRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void clearInitializationFailures() {
|
public static void clearCache() {
|
||||||
|
COMMAND_CACHE.clear();
|
||||||
UNAVAILABLE_COMMANDS.clear();
|
UNAVAILABLE_COMMANDS.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public record CommandSpec(String name, String permission, String moduleKey, Supplier<BaseCommand> factory,
|
public record CommandSpec(String name, String permission, String moduleKey, String className, List<String> aliases, boolean standalone) {
|
||||||
List<String> aliases, boolean standalone) {
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,80 +27,23 @@ 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.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"));
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("maintenance")
|
|
||||||
&& sender.hasPermission("essentialsc.command.maintenance")) {
|
|
||||||
sendPrefixed(sender, lang.getString("help.commands.maintenance"));
|
|
||||||
}
|
|
||||||
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();
|
||||||
@@ -121,10 +53,10 @@ 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.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;
|
||||||
@@ -150,7 +82,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;
|
||||||
@@ -163,7 +95,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)));
|
||||||
@@ -270,10 +202,6 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
otherCommands.append(lang.getString("help.commands.tpignore")).append("\n");
|
otherCommands.append(lang.getString("help.commands.tpignore")).append("\n");
|
||||||
hasOtherCommands = true;
|
hasOtherCommands = true;
|
||||||
}
|
}
|
||||||
if (CommandRegistry.isAvailable("skin") && player.hasPermission("essentialsc.command.skin")) {
|
|
||||||
otherCommands.append(lang.getString("help.commands.skin")).append("\n");
|
|
||||||
hasOtherCommands = true;
|
|
||||||
}
|
|
||||||
if (CommandRegistry.isAvailable("admin") && player.hasPermission("essentialsc.command.admin")) {
|
if (CommandRegistry.isAvailable("admin") && player.hasPermission("essentialsc.command.admin")) {
|
||||||
otherCommands.append(lang.getString("help.commands.admin")).append("\n");
|
otherCommands.append(lang.getString("help.commands.admin")).append("\n");
|
||||||
hasOtherCommands = true;
|
hasOtherCommands = true;
|
||||||
@@ -303,7 +231,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) {
|
||||||
@@ -365,7 +293,6 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
{"tpdecline", "essentialsc.command.tpdeny"},
|
{"tpdecline", "essentialsc.command.tpdeny"},
|
||||||
{"tpno", "essentialsc.command.tpdeny"},
|
{"tpno", "essentialsc.command.tpdeny"},
|
||||||
{"tpignore", "essentialsc.command.tpignore"},
|
{"tpignore", "essentialsc.command.tpignore"},
|
||||||
{"skin", "essentialsc.command.skin"},
|
|
||||||
{"tpsbar", "essentialsc.command.tpsbar"},
|
{"tpsbar", "essentialsc.command.tpsbar"},
|
||||||
{"maintenance", "essentialsc.command.maintenance"},
|
{"maintenance", "essentialsc.command.maintenance"},
|
||||||
{"maint", "essentialsc.command.maintenance"},
|
{"maint", "essentialsc.command.maintenance"},
|
||||||
@@ -418,20 +345,6 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
return manager == null ? List.of() : manager.getIncomingRequesterNames(completionPlayer, args[1]);
|
return manager == null ? List.of() : manager.getIncomingRequesterNames(completionPlayer, args[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (subCmd.equals("skin") && sender.hasPermission("essentialsc.command.skin")) {
|
|
||||||
String partial = args[1].toLowerCase();
|
|
||||||
List<String> actions = new ArrayList<>();
|
|
||||||
if (sender.hasPermission("essentialsc.command.skin.status")) {
|
|
||||||
actions.add("status");
|
|
||||||
}
|
|
||||||
if (sender.hasPermission("essentialsc.command.skin.refresh")) {
|
|
||||||
actions.add("refresh");
|
|
||||||
}
|
|
||||||
return actions.stream()
|
|
||||||
.filter(option -> option.startsWith(partial))
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((subCmd.equals("nightvision") || subCmd.equals("nv")) && sender.hasPermission("essentialsc.command.nightvision")) {
|
if ((subCmd.equals("nightvision") || subCmd.equals("nv")) && sender.hasPermission("essentialsc.command.nightvision")) {
|
||||||
return completeToggleArgs(args[1]);
|
return completeToggleArgs(args[1]);
|
||||||
}
|
}
|
||||||
@@ -457,22 +370,6 @@ public class HelpCommand extends BaseCommand implements TabCompleter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args.length == 3 && args[0].equalsIgnoreCase("skin")
|
|
||||||
&& (args[1].equalsIgnoreCase("status") || args[1].equalsIgnoreCase("refresh"))
|
|
||||||
&& sender.hasPermission("essentialsc.command.skin.others")
|
|
||||||
&& sender.hasPermission(args[1].equalsIgnoreCase("status")
|
|
||||||
? "essentialsc.command.skin.status"
|
|
||||||
: "essentialsc.command.skin.refresh")) {
|
|
||||||
List<String> players = new ArrayList<>();
|
|
||||||
String partial = args[2].toLowerCase();
|
|
||||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
|
||||||
if (player.getName().toLowerCase().startsWith(partial)) {
|
|
||||||
players.add(player.getName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return players;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ArrayList<>();
|
return new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,18 +41,12 @@ public class MaintenanceCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
switch (args[0].toLowerCase(Locale.ROOT)) {
|
switch (args[0].toLowerCase(Locale.ROOT)) {
|
||||||
case "on", "enable", "enabled" -> {
|
case "on", "enable", "enabled" -> {
|
||||||
if (maintenanceManager.setEnabled(true) == MaintenanceManager.OperationResult.SAVE_FAILED) {
|
maintenanceManager.setEnabled(true);
|
||||||
sendSaveFailed(sender);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.enabled"));
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.enabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
case "off", "disable", "disabled" -> {
|
case "off", "disable", "disabled" -> {
|
||||||
if (maintenanceManager.setEnabled(false) == MaintenanceManager.OperationResult.SAVE_FAILED) {
|
maintenanceManager.setEnabled(false);
|
||||||
sendSaveFailed(sender);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.disabled"));
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -68,10 +62,7 @@ public class MaintenanceCommand extends BaseCommand implements TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String target = args[1];
|
String target = args[1];
|
||||||
MaintenanceManager.OperationResult result = maintenanceManager.addWhitelistEntry(target);
|
if (maintenanceManager.addWhitelistEntry(target)) {
|
||||||
if (result == MaintenanceManager.OperationResult.SAVE_FAILED) {
|
|
||||||
sendSaveFailed(sender);
|
|
||||||
} else if (result == MaintenanceManager.OperationResult.SUCCESS) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-added",
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-added",
|
||||||
Map.of("player", target)));
|
Map.of("player", target)));
|
||||||
} else {
|
} else {
|
||||||
@@ -87,10 +78,7 @@ public class MaintenanceCommand extends BaseCommand implements TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String target = args[1];
|
String target = args[1];
|
||||||
MaintenanceManager.OperationResult result = maintenanceManager.removeWhitelistEntry(target);
|
if (maintenanceManager.removeWhitelistEntry(target)) {
|
||||||
if (result == MaintenanceManager.OperationResult.SAVE_FAILED) {
|
|
||||||
sendSaveFailed(sender);
|
|
||||||
} else if (result == MaintenanceManager.OperationResult.SUCCESS) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-removed",
|
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.whitelist-removed",
|
||||||
Map.of("player", target)));
|
Map.of("player", target)));
|
||||||
} else {
|
} else {
|
||||||
@@ -135,10 +123,6 @@ public class MaintenanceCommand extends BaseCommand implements TabCompleter {
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendSaveFailed(CommandSender sender) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("maintenance.messages.save-failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@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 (!sender.hasPermission(getPermission())) {
|
if (!sender.hasPermission(getPermission())) {
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,22 +42,22 @@ public class MobDropCommand extends BaseCommand {
|
|||||||
|
|
||||||
public static void openMobDropMenu(EssentialsC plugin, Player player) {
|
public static void openMobDropMenu(EssentialsC plugin, Player player) {
|
||||||
var lang = EssentialsC.getLangManager();
|
var lang = EssentialsC.getLangManager();
|
||||||
boolean endermanDropsAllowed = plugin.getConfig().getBoolean("mob-drops.enderman.allow-drops", true);
|
boolean endermanEnabled = plugin.getConfig().getBoolean("mob-drops.enderman.enabled", true);
|
||||||
String status = lang.getString(endermanDropsAllowed
|
String status = lang.getString(endermanEnabled
|
||||||
? "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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
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.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,57 +17,42 @@ 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",
|
StringBuilder info = new StringBuilder();
|
||||||
Map.of("player", String.valueOf(target.getName()))));
|
info.append(getLang().getPrefix()).append(ChatColor.GOLD).append("玩家信息: ")
|
||||||
|
.append(ChatColor.WHITE).append(target.getName()).append("\n");
|
||||||
|
|
||||||
if (target.isOnline()) {
|
if (target.isOnline()) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-status-online"));
|
info.append(ChatColor.GRAY).append("状态: ").append(ChatColor.GREEN).append("在线").append("\n");
|
||||||
Player onlinePlayer = target.getPlayer();
|
Player onlinePlayer = target.getPlayer();
|
||||||
if (onlinePlayer != null) {
|
if (onlinePlayer != null) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-world",
|
info.append(ChatColor.GRAY).append("所在世界: ").append(ChatColor.WHITE)
|
||||||
Map.of("world", onlinePlayer.getWorld().getName())));
|
.append(onlinePlayer.getWorld().getName()).append("\n");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-status-offline"));
|
info.append(ChatColor.GRAY).append("状态: ").append(ChatColor.RED).append("离线").append("\n");
|
||||||
long lastSeen = target.getLastSeen();
|
long lastSeen = target.getLastSeen();
|
||||||
if (lastSeen > 0) {
|
if (lastSeen > 0) {
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-last-online",
|
info.append(ChatColor.GRAY).append("最后在线: ").append(ChatColor.WHITE)
|
||||||
Map.of("time", format.format(new Date(lastSeen)))));
|
.append(format.format(new Date(lastSeen))).append("\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sender.sendMessage(getLang().getComponent("messages.seen-first-joined",
|
info.append(ChatColor.GRAY).append("首次加入: ").append(ChatColor.WHITE)
|
||||||
Map.of("time", format.format(new Date(target.getFirstPlayed())))));
|
.append(format.format(new Date(target.getFirstPlayed())));
|
||||||
|
|
||||||
|
player.sendMessage(info.toString());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,171 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.skinbridge.SkinBridgeManager;
|
|
||||||
import org.bukkit.Bukkit;
|
|
||||||
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 final class SkinBridgeCommand extends BaseCommand implements TabCompleter {
|
|
||||||
|
|
||||||
private static final String STATUS_PERMISSION = "essentialsc.command.skin.status";
|
|
||||||
private static final String REFRESH_PERMISSION = "essentialsc.command.skin.refresh";
|
|
||||||
private static final String OTHERS_PERMISSION = "essentialsc.command.skin.others";
|
|
||||||
|
|
||||||
public SkinBridgeCommand() {
|
|
||||||
super("essentialsc.command.skin");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean execute(Player player, String[] args) {
|
|
||||||
return executeCommand(player, args, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean executeConsole(CommandSender sender, String[] args) {
|
|
||||||
return executeCommand(sender, args, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean executeCommand(CommandSender sender, String[] args, boolean console) {
|
|
||||||
if (args.length < 1 || args.length > 2) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
SkinBridgeManager manager = plugin.getSkinBridgeManager();
|
|
||||||
if (manager == null) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player target = console ? null : (Player) sender;
|
|
||||||
if (args.length == 2) {
|
|
||||||
target = Bukkit.getPlayerExact(args[1]);
|
|
||||||
if (target == null || !target.isOnline()) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[1])));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (target == null) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
String action = args[0].toLowerCase(Locale.ROOT);
|
|
||||||
boolean targetsOther = sender instanceof Player playerSender
|
|
||||||
&& !playerSender.getUniqueId().equals(target.getUniqueId());
|
|
||||||
if (action.equals("status")) {
|
|
||||||
if (!hasPermission(sender, STATUS_PERMISSION)) {
|
|
||||||
sendNoPermission(sender, STATUS_PERMISSION);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (targetsOther && !hasPermission(sender, OTHERS_PERMISSION)) {
|
|
||||||
sendNoPermission(sender, OTHERS_PERMISSION);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
sendStatus(sender, target, manager);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (action.equals("refresh")) {
|
|
||||||
if (!hasPermission(sender, REFRESH_PERMISSION)) {
|
|
||||||
sendNoPermission(sender, REFRESH_PERMISSION);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (targetsOther && !hasPermission(sender, OTHERS_PERMISSION)) {
|
|
||||||
sendNoPermission(sender, OTHERS_PERMISSION);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
sendRefreshResult(sender, target, manager.queueSync(target, true));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.usage"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean hasPermission(CommandSender sender, String permission) {
|
|
||||||
return !(sender instanceof Player) || sender.hasPermission(permission);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendNoPermission(CommandSender sender, String permission) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("messages.no-permission", Map.of("permission", permission)));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendStatus(CommandSender sender, Player target, SkinBridgeManager manager) {
|
|
||||||
if (!manager.isSkinGatewayAvailable()) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.dependency-missing"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (manager.getProviderCount() == 0) {
|
|
||||||
sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.no-providers"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
SkinBridgeManager.Status status = manager.getStatus(target);
|
|
||||||
Map<String, String> placeholders = Map.of("player", target.getName(), "provider", String.valueOf(status.providerId()));
|
|
||||||
switch (status.state()) {
|
|
||||||
case EXTERNAL -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-external", placeholders));
|
|
||||||
case EXCLUDED -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-excluded", placeholders));
|
|
||||||
case NOT_EXTERNAL -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-not-external", placeholders));
|
|
||||||
case PENDING -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-pending", placeholders));
|
|
||||||
case UNKNOWN -> sender.sendMessage(getLang().getPrefixedString("skin-bridge.messages.status-unknown", placeholders));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendRefreshResult(CommandSender sender, Player target, SkinBridgeManager.SyncResult result) {
|
|
||||||
Map<String, String> placeholders = Map.of("player", target.getName());
|
|
||||||
String messagePath = switch (result) {
|
|
||||||
case QUEUED -> "skin-bridge.messages.refresh-queued";
|
|
||||||
case CACHED -> "skin-bridge.messages.refresh-cached";
|
|
||||||
case ALREADY_RUNNING -> "skin-bridge.messages.refresh-running";
|
|
||||||
case EXCLUDED -> "skin-bridge.messages.refresh-excluded";
|
|
||||||
case QUEUE_FULL -> "skin-bridge.messages.queue-full";
|
|
||||||
case DEPENDENCY_MISSING -> "skin-bridge.messages.dependency-missing";
|
|
||||||
case NO_PROVIDERS -> "skin-bridge.messages.no-providers";
|
|
||||||
case REFRESH_COOLDOWN -> "skin-bridge.messages.refresh-cooldown";
|
|
||||||
};
|
|
||||||
if (result == SkinBridgeManager.SyncResult.REFRESH_COOLDOWN) {
|
|
||||||
placeholders = Map.of(
|
|
||||||
"player", target.getName(),
|
|
||||||
"seconds", String.valueOf(plugin.getSkinBridgeManager().getRemainingForceRefreshCooldownSeconds(target))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
sender.sendMessage(getLang().getPrefixedString(messagePath, placeholders));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
|
||||||
if (args.length == 1) {
|
|
||||||
String partial = args[0].toLowerCase(Locale.ROOT);
|
|
||||||
List<String> actions = new ArrayList<>();
|
|
||||||
if (hasPermission(sender, STATUS_PERMISSION)) {
|
|
||||||
actions.add("status");
|
|
||||||
}
|
|
||||||
if (hasPermission(sender, REFRESH_PERMISSION)) {
|
|
||||||
actions.add("refresh");
|
|
||||||
}
|
|
||||||
return actions.stream()
|
|
||||||
.filter(option -> option.startsWith(partial))
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
if (args.length == 2 && hasPermission(sender, OTHERS_PERMISSION)
|
|
||||||
&& ((args[0].equalsIgnoreCase("status") && hasPermission(sender, STATUS_PERMISSION))
|
|
||||||
|| (args[0].equalsIgnoreCase("refresh") && hasPermission(sender, REFRESH_PERMISSION)))) {
|
|
||||||
String partial = args[1].toLowerCase(Locale.ROOT);
|
|
||||||
List<String> players = new ArrayList<>();
|
|
||||||
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
|
||||||
if (onlinePlayer.getName().toLowerCase(Locale.ROOT).startsWith(partial)) {
|
|
||||||
players.add(onlinePlayer.getName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return players;
|
|
||||||
}
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.command.Command;
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
import org.bukkit.command.TabCompleter;
|
import org.bukkit.command.TabCompleter;
|
||||||
@@ -19,17 +20,17 @@ public final class TpAcceptCommand extends BaseCommand implements TabCompleter {
|
|||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpaccept"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.usage-tpaccept"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||||
if (manager == null) {
|
if (manager == null) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (manager.isIgnoringRequests(player)) {
|
if (manager.isIgnoringRequests(player)) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.ignoring-requests"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,9 +39,7 @@ public final class TpAcceptCommand extends BaseCommand implements TabCompleter {
|
|||||||
args.length == 0 ? null : args[0]
|
args.length == 0 ? null : args[0]
|
||||||
);
|
);
|
||||||
if (request.isEmpty()) {
|
if (request.isEmpty()) {
|
||||||
player.sendMessage(args.length == 0
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.no-request"));
|
||||||
? getLang().getPrefixedComponent("tpa.messages.no-request")
|
|
||||||
: getLang().getPrefixedComponent("tpa.messages.invalid-request", Map.of("requester", args[0])));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,18 +47,28 @@ public final class TpAcceptCommand extends BaseCommand implements TabCompleter {
|
|||||||
Map<String, String> placeholders = manager.placeholders(accepted);
|
Map<String, String> placeholders = manager.placeholders(accepted);
|
||||||
TeleportRequestManager.TeleportResult result = manager.accept(player, accepted);
|
TeleportRequestManager.TeleportResult result = manager.accept(player, accepted);
|
||||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.expired", placeholders));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.expired", placeholders));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.PLAYER_OFFLINE) {
|
if (result.status() == TeleportRequestManager.TeleportResult.Status.PLAYER_OFFLINE) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.player-offline", placeholders));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (result.status() == TeleportRequestManager.TeleportResult.Status.ALREADY_WARMING_UP) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.already-warming-up", placeholders));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.ON_COOLDOWN) {
|
if (result.status() == TeleportRequestManager.TeleportResult.Status.ON_COOLDOWN) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.accept-cooldown",
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.accept-cooldown",
|
||||||
Map.of("seconds", String.valueOf(result.cooldownSeconds()))));
|
Map.of("seconds", String.valueOf(result.cooldownSeconds()))));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.accepted-target", placeholders));
|
||||||
|
Player requester = Bukkit.getPlayer(accepted.requesterId());
|
||||||
|
if (requester != null && requester.isOnline()) {
|
||||||
|
requester.sendMessage(getLang().getPrefixedString("tpa.messages.accepted-sender", placeholders));
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.command.Command;
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
import org.bukkit.command.TabCompleter;
|
import org.bukkit.command.TabCompleter;
|
||||||
@@ -19,17 +20,17 @@ public final class TpDenyCommand extends BaseCommand implements TabCompleter {
|
|||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpdeny"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.usage-tpdeny"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||||
if (manager == null) {
|
if (manager == null) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (manager.isIgnoringRequests(player)) {
|
if (manager.isIgnoringRequests(player)) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.ignoring-requests"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,19 +39,23 @@ public final class TpDenyCommand extends BaseCommand implements TabCompleter {
|
|||||||
args.length == 0 ? null : args[0]
|
args.length == 0 ? null : args[0]
|
||||||
);
|
);
|
||||||
if (request.isEmpty()) {
|
if (request.isEmpty()) {
|
||||||
player.sendMessage(args.length == 0
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.no-request"));
|
||||||
? getLang().getPrefixedComponent("tpa.messages.no-request")
|
|
||||||
: getLang().getPrefixedComponent("tpa.messages.invalid-request", Map.of("requester", args[0])));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager.TeleportRequest denied = request.get();
|
TeleportRequestManager.TeleportRequest denied = request.get();
|
||||||
TeleportRequestManager.TeleportResult result = manager.deny(player, denied);
|
TeleportRequestManager.TeleportResult result = manager.deny(player, denied);
|
||||||
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
if (result.status() == TeleportRequestManager.TeleportResult.Status.EXPIRED) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.expired", manager.placeholders(denied)));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.expired", manager.placeholders(denied)));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, String> placeholders = manager.placeholders(denied);
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.denied-target", placeholders));
|
||||||
|
Player requester = Bukkit.getPlayer(denied.requesterId());
|
||||||
|
if (requester != null && requester.isOnline()) {
|
||||||
|
requester.sendMessage(getLang().getPrefixedString("tpa.messages.denied-sender", placeholders));
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,17 +13,14 @@ public final class TpIgnoreCommand extends BaseCommand {
|
|||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||||
if (manager == null) {
|
if (manager == null) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager.ToggleIgnoreResult result = manager.toggleIgnoringRequests(player);
|
boolean ignoring = manager.toggleIgnoringRequests(player);
|
||||||
String messagePath = switch (result) {
|
player.sendMessage(getLang().getPrefixedString(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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package cn.infstar.essentialsC.commands;
|
|||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public final class TpaAllCommand extends BaseCommand {
|
public final class TpaAllCommand extends BaseCommand {
|
||||||
|
|
||||||
public TpaAllCommand() {
|
public TpaAllCommand() {
|
||||||
@@ -12,27 +14,32 @@ public final class TpaAllCommand extends BaseCommand {
|
|||||||
@Override
|
@Override
|
||||||
protected boolean execute(Player player, String[] args) {
|
protected boolean execute(Player player, String[] args) {
|
||||||
if (args.length != 0) {
|
if (args.length != 0) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.usage-tpaall"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.usage-tpaall"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||||
if (manager == null) {
|
if (manager == null) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (manager.isIgnoringRequests(player)) {
|
if (manager.isIgnoringRequests(player)) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.ignoring-requests"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int sent = manager.sendTeleportAllRequest(player);
|
int sent = manager.sendTeleportAllRequest(player, target -> !VanishCommand.isVanished(target));
|
||||||
|
if (sent < 0) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.send-cooldown",
|
||||||
|
Map.of("seconds", String.valueOf(manager.getSendCooldownSeconds(player)))));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
if (sent <= 0) {
|
if (sent <= 0) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.tpaall-no-targets"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.tpaall-no-targets"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.tpaall-sent"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.tpaall-sent"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
import cn.infstar.essentialsC.teleport.TeleportRequestManager;
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.event.ClickEvent;
|
||||||
|
import net.kyori.adventure.text.event.HoverEvent;
|
||||||
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.command.Command;
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
@@ -10,6 +15,7 @@ import org.bukkit.entity.Player;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public class TpaCommand extends BaseCommand implements TabCompleter {
|
public class TpaCommand extends BaseCommand implements TabCompleter {
|
||||||
|
|
||||||
@@ -24,7 +30,7 @@ public class TpaCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
protected boolean sendRequest(Player player, String[] args, TeleportRequestManager.TeleportRequest.Type type) {
|
protected boolean sendRequest(Player player, String[] args, TeleportRequestManager.TeleportRequest.Type type) {
|
||||||
if (args.length != 1) {
|
if (args.length != 1) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
player.sendMessage(getLang().getPrefixedString(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||||
? "tpa.messages.usage-tpa"
|
? "tpa.messages.usage-tpa"
|
||||||
: "tpa.messages.usage-tpahere"));
|
: "tpa.messages.usage-tpahere"));
|
||||||
return true;
|
return true;
|
||||||
@@ -32,76 +38,82 @@ public class TpaCommand extends BaseCommand implements TabCompleter {
|
|||||||
|
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
||||||
if (manager == null) {
|
if (manager == null) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.module-disabled"));
|
player.sendMessage(getLang().getPrefixedString("messages.module-disabled"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (manager.isIgnoringRequests(player)) {
|
if (manager.isIgnoringRequests(player)) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.ignoring-requests"));
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.ignoring-requests"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args[0].equalsIgnoreCase(player.getName())) {
|
Player target = Bukkit.getPlayerExact(args[0]);
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.self"));
|
if (target == null || !target.isOnline() || VanishCommand.isVanished(target)) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("messages.player-not-found", Map.of("player", args[0])));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int remainingCooldown = manager.getRemainingSendCooldownSeconds(player);
|
if (target.getUniqueId().equals(player.getUniqueId())) {
|
||||||
if (remainingCooldown > 0) {
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.self"));
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.send-cooldown",
|
|
||||||
Map.of("seconds", String.valueOf(remainingCooldown))));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Player target = manager.findOnlinePlayer(args[0], onlinePlayer ->
|
|
||||||
!onlinePlayer.getUniqueId().equals(player.getUniqueId()) && !manager.isVanished(onlinePlayer)
|
|
||||||
).orElse(null);
|
|
||||||
if (target == null || !target.isOnline()) {
|
|
||||||
player.sendMessage(getLang().getPrefixedComponent("messages.player-not-found", Map.of("player", args[0])));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager.CreateRequestResult createdRequest = manager.createRequest(player, target, type);
|
TeleportRequestManager.CreateRequestResult createdRequest = manager.createRequest(player, target, type);
|
||||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.ON_COOLDOWN) {
|
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.DUPLICATE) {
|
||||||
player.sendMessage(getLang().getPrefixedComponent("tpa.messages.send-cooldown",
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.duplicate-request", Map.of("target", target.getName())));
|
||||||
Map.of("seconds", String.valueOf(createdRequest.cooldownSeconds()))));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.CANCELLED) {
|
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.ON_COOLDOWN) {
|
||||||
|
player.sendMessage(getLang().getPrefixedString("tpa.messages.send-cooldown",
|
||||||
|
Map.of("seconds", String.valueOf(createdRequest.cooldownSeconds()))));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager.TeleportRequest request = createdRequest.request();
|
TeleportRequestManager.TeleportRequest request = createdRequest.request();
|
||||||
Map<String, String> placeholders = manager.placeholders(request);
|
Map<String, String> placeholders = manager.placeholders(request);
|
||||||
player.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
player.sendMessage(getLang().getPrefixedString(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||||
? "tpa.messages.sent-tpa"
|
? "tpa.messages.sent-tpa"
|
||||||
: "tpa.messages.sent-tpahere", placeholders));
|
: "tpa.messages.sent-tpahere", placeholders));
|
||||||
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.IGNORED
|
if (createdRequest.status() == TeleportRequestManager.CreateRequestStatus.IGNORED) {
|
||||||
|| createdRequest.status() == TeleportRequestManager.CreateRequestStatus.DUPLICATE) {
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
target.sendMessage(getLang().getPrefixedComponent(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
target.sendMessage(getLang().getPrefixedString(type == TeleportRequestManager.TeleportRequest.Type.TPA
|
||||||
? "tpa.messages.received-tpa"
|
? "tpa.messages.received-tpa"
|
||||||
: "tpa.messages.received-tpahere", placeholders));
|
: "tpa.messages.received-tpahere", placeholders));
|
||||||
manager.playRequestReceivedSound(target);
|
manager.playRequestReceivedSound(target);
|
||||||
manager.sendResponseHint(target, placeholders);
|
sendResponseHint(target, request, placeholders);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void sendResponseHint(Player target, TeleportRequestManager.TeleportRequest request, Map<String, String> placeholders) {
|
||||||
|
String requesterName = request.requesterName();
|
||||||
|
String acceptCommand = "/tpaccept " + requesterName;
|
||||||
|
String denyCommand = "/tpdeny " + requesterName;
|
||||||
|
|
||||||
|
Component hint = LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(getLang().getPrefixedString("tpa.messages.response-hint", placeholders));
|
||||||
|
Component accept = LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(getLang().getString("tpa.messages.accept-button"))
|
||||||
|
.clickEvent(ClickEvent.runCommand(acceptCommand))
|
||||||
|
.hoverEvent(HoverEvent.showText(Component.text(acceptCommand, NamedTextColor.GREEN)));
|
||||||
|
Component deny = LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(getLang().getString("tpa.messages.deny-button"))
|
||||||
|
.clickEvent(ClickEvent.runCommand(denyCommand))
|
||||||
|
.hoverEvent(HoverEvent.showText(Component.text(denyCommand, NamedTextColor.RED)));
|
||||||
|
|
||||||
|
target.sendMessage(hint.append(Component.space()).append(accept).append(Component.space()).append(deny));
|
||||||
|
}
|
||||||
|
|
||||||
@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 instanceof Player player)) {
|
if (args.length != 1 || !(sender instanceof Player player)) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportRequestManager manager = plugin.getTeleportRequestManager();
|
|
||||||
if (manager == null) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
String partial = args[0].toLowerCase();
|
String partial = args[0].toLowerCase();
|
||||||
List<String> completions = new ArrayList<>();
|
List<String> completions = new ArrayList<>();
|
||||||
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
||||||
if (!onlinePlayer.getUniqueId().equals(player.getUniqueId())
|
if (!onlinePlayer.getUniqueId().equals(player.getUniqueId())
|
||||||
&& !manager.isVanished(onlinePlayer)
|
&& !VanishCommand.isVanished(onlinePlayer)
|
||||||
&& onlinePlayer.getName().toLowerCase().startsWith(partial)) {
|
&& onlinePlayer.getName().toLowerCase().startsWith(partial)) {
|
||||||
completions.add(onlinePlayer.getName());
|
completions.add(onlinePlayer.getName());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,8 @@
|
|||||||
package cn.infstar.essentialsC.commands;
|
package cn.infstar.essentialsC.commands;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
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;
|
||||||
@@ -16,8 +10,6 @@ import java.util.UUID;
|
|||||||
public class VanishCommand extends BaseCommand {
|
public class VanishCommand extends BaseCommand {
|
||||||
|
|
||||||
private static final Set<UUID> vanishedPlayers = new HashSet<>();
|
private static final Set<UUID> vanishedPlayers = new HashSet<>();
|
||||||
public static final String SEE_PERMISSION = "essentialsc.vanish.see";
|
|
||||||
private static File stateFile;
|
|
||||||
|
|
||||||
public VanishCommand() {
|
public VanishCommand() {
|
||||||
super("essentialsc.command.vanish");
|
super("essentialsc.command.vanish");
|
||||||
@@ -29,52 +21,17 @@ 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"));
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void loadState(EssentialsC plugin) {
|
|
||||||
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
|
||||||
vanishedPlayers.clear();
|
|
||||||
if (!stateFile.exists()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
YamlConfiguration state = new YamlConfiguration();
|
|
||||||
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")) {
|
|
||||||
try {
|
|
||||||
vanishedPlayers.add(UUID.fromString(value));
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
|
||||||
plugin.getLogger().warning("忽略无效的隐身玩家 UUID: " + value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void hideVanishedPlayersFrom(EssentialsC plugin, Player observer) {
|
public static void hideVanishedPlayersFrom(EssentialsC plugin, Player observer) {
|
||||||
if (observer.hasPermission(SEE_PERMISSION)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (Player vanished : plugin.getServer().getOnlinePlayers()) {
|
for (Player vanished : plugin.getServer().getOnlinePlayers()) {
|
||||||
if (!observer.equals(vanished) && isVanished(vanished)) {
|
if (!observer.equals(vanished) && isVanished(vanished)) {
|
||||||
observer.hidePlayer(plugin, vanished);
|
observer.hidePlayer(plugin, vanished);
|
||||||
@@ -82,28 +39,8 @@ public class VanishCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean restoreVisibility(EssentialsC plugin, Player player, boolean notify) {
|
public static void removeVanished(Player player) {
|
||||||
if (!vanishedPlayers.remove(player.getUniqueId())) {
|
vanishedPlayers.remove(player.getUniqueId());
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (!saveState(plugin)) {
|
|
||||||
vanishedPlayers.add(player.getUniqueId());
|
|
||||||
if (notify) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-save-failed"));
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
showPlayerToAll(plugin, player);
|
|
||||||
if (notify) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString("messages.vanish-permission-removed"));
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void applyHiddenState(EssentialsC plugin, Player player) {
|
|
||||||
if (isVanished(player)) {
|
|
||||||
hidePlayerFromAll(plugin, player);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void clearAll(EssentialsC plugin) {
|
public static void clearAll(EssentialsC plugin) {
|
||||||
@@ -117,7 +54,7 @@ public class VanishCommand extends BaseCommand {
|
|||||||
|
|
||||||
private static void hidePlayerFromAll(EssentialsC plugin, Player player) {
|
private static void hidePlayerFromAll(EssentialsC plugin, Player player) {
|
||||||
for (Player online : player.getServer().getOnlinePlayers()) {
|
for (Player online : player.getServer().getOnlinePlayers()) {
|
||||||
if (online != player && !online.hasPermission(SEE_PERMISSION)) {
|
if (online != player) {
|
||||||
online.hidePlayer(plugin, player);
|
online.hidePlayer(plugin, player);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,19 +71,4 @@ public class VanishCommand extends BaseCommand {
|
|||||||
public static boolean isVanished(Player player) {
|
public static boolean isVanished(Player player) {
|
||||||
return vanishedPlayers.contains(player.getUniqueId());
|
return vanishedPlayers.contains(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean saveState(EssentialsC plugin) {
|
|
||||||
if (stateFile == null) {
|
|
||||||
stateFile = new File(plugin.getDataFolder(), "vanished-players.yml");
|
|
||||||
}
|
|
||||||
FileConfiguration state = new YamlConfiguration();
|
|
||||||
state.set("players", vanishedPlayers.stream().map(UUID::toString).sorted().toList());
|
|
||||||
try {
|
|
||||||
AtomicYamlWriter.save(state, stateFile);
|
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package cn.infstar.essentialsC.listeners;
|
|||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@@ -10,8 +9,6 @@ import org.bukkit.event.Listener;
|
|||||||
import org.bukkit.event.player.PlayerJoinEvent;
|
import org.bukkit.event.player.PlayerJoinEvent;
|
||||||
|
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,9 +16,8 @@ import java.util.logging.Level;
|
|||||||
*/
|
*/
|
||||||
public class JeiRecipeSyncListener implements Listener {
|
public class JeiRecipeSyncListener implements Listener {
|
||||||
|
|
||||||
private static final Set<String> WARNED_UNSUPPORTED_VERSIONS = ConcurrentHashMap.newKeySet();
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
|
private final boolean enabled;
|
||||||
private final boolean debug;
|
private final boolean debug;
|
||||||
private final boolean sendPlayerMessage;
|
private final boolean sendPlayerMessage;
|
||||||
private final int brandCheckDelayTicks;
|
private final int brandCheckDelayTicks;
|
||||||
@@ -33,8 +29,10 @@ public class JeiRecipeSyncListener implements Listener {
|
|||||||
FileConfiguration config = plugin.getConfig();
|
FileConfiguration config = plugin.getConfig();
|
||||||
config.addDefault("jei-sync.brand-check-delay-ticks", 20);
|
config.addDefault("jei-sync.brand-check-delay-ticks", 20);
|
||||||
config.options().copyDefaults(true);
|
config.options().copyDefaults(true);
|
||||||
|
plugin.saveConfig();
|
||||||
|
|
||||||
this.debug = config.getBoolean("debug", false);
|
this.enabled = config.getBoolean("jei-sync.enabled", true);
|
||||||
|
this.debug = config.getBoolean("jei-sync.debug", config.getBoolean("debug", false));
|
||||||
this.sendPlayerMessage = config.getBoolean("jei-sync.send-player-message", true);
|
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.brandCheckDelayTicks = Math.max(0, config.getInt("jei-sync.brand-check-delay-ticks", 20));
|
||||||
this.adapter = loadAdapter();
|
this.adapter = loadAdapter();
|
||||||
@@ -42,6 +40,9 @@ public class JeiRecipeSyncListener implements Listener {
|
|||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (adapter == null) {
|
if (adapter == null) {
|
||||||
if (debug) {
|
if (debug) {
|
||||||
plugin.getLogger().warning("当前服务端版本没有可用的 JEI 配方同步适配器。");
|
plugin.getLogger().warning("当前服务端版本没有可用的 JEI 配方同步适配器。");
|
||||||
@@ -53,13 +54,6 @@ public class JeiRecipeSyncListener implements Listener {
|
|||||||
plugin.getServer().getScheduler().runTaskLater(plugin, () -> detectAndSync(player), brandCheckDelayTicks);
|
plugin.getServer().getScheduler().runTaskLater(plugin, () -> detectAndSync(player), brandCheckDelayTicks);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
|
||||||
public void onServerResourcesReloaded(ServerResourcesReloadedEvent event) {
|
|
||||||
if (adapter != null) {
|
|
||||||
adapter.clearCache();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void detectAndSync(Player player) {
|
private void detectAndSync(Player player) {
|
||||||
if (!player.isOnline()) {
|
if (!player.isOnline()) {
|
||||||
return;
|
return;
|
||||||
@@ -118,7 +112,10 @@ public class JeiRecipeSyncListener implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedComponent(messageKey));
|
String fullMessage = EssentialsC.getLangManager().getPrefixedString(messageKey);
|
||||||
|
net.kyori.adventure.text.Component component =
|
||||||
|
net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacyAmpersand().deserialize(fullMessage);
|
||||||
|
player.sendMessage(component);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendFabricRecipeSync(Player player) {
|
private void sendFabricRecipeSync(Player player) {
|
||||||
@@ -158,10 +155,6 @@ public class JeiRecipeSyncListener implements Listener {
|
|||||||
}
|
}
|
||||||
plugin.getLogger().warning("JEI 配方同步适配器类型无效: " + className);
|
plugin.getLogger().warning("JEI 配方同步适配器类型无效: " + className);
|
||||||
} catch (ReflectiveOperationException | LinkageError e) {
|
} catch (ReflectiveOperationException | LinkageError e) {
|
||||||
if (WARNED_UNSUPPORTED_VERSIONS.add(versionKey)) {
|
|
||||||
plugin.getLogger().warning("当前 Paper 版本 " + plugin.getServer().getBukkitVersion()
|
|
||||||
+ " 没有可用的 JEI 配方同步适配器;仅 JEI 同步功能已停用。");
|
|
||||||
}
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
plugin.getLogger().warning("加载 JEI 配方同步适配器失败: " + className + " (" + e.getMessage() + ")");
|
plugin.getLogger().warning("加载 JEI 配方同步适配器失败: " + className + " (" + e.getMessage() + ")");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import org.bukkit.event.entity.EntityDeathEvent;
|
|||||||
public class MobDropListener implements Listener {
|
public class MobDropListener implements Listener {
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private boolean endermanDropsAllowed;
|
private boolean endermanDropEnabled;
|
||||||
|
|
||||||
public MobDropListener(EssentialsC plugin) {
|
public MobDropListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
@@ -19,10 +19,16 @@ public class MobDropListener implements Listener {
|
|||||||
|
|
||||||
private void loadConfig() {
|
private void loadConfig() {
|
||||||
FileConfiguration config = plugin.getConfig();
|
FileConfiguration config = plugin.getConfig();
|
||||||
config.addDefault("mob-drops.enderman.allow-drops", true);
|
config.addDefault("mob-drops.enderman.enabled", true);
|
||||||
config.options().copyDefaults(true);
|
config.options().copyDefaults(true);
|
||||||
|
|
||||||
this.endermanDropsAllowed = config.getBoolean("mob-drops.enderman.allow-drops", true);
|
try {
|
||||||
|
config.save(plugin.getDataFolder().toPath().resolve("config.yml").toFile());
|
||||||
|
} catch (Exception e) {
|
||||||
|
plugin.getLogger().warning("无法保存配置文件: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
this.endermanDropEnabled = config.getBoolean("mob-drops.enderman.enabled", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
@@ -31,13 +37,13 @@ public class MobDropListener implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!plugin.getConfig().getBoolean("mob-drops.enderman.allow-drops", true)) {
|
if (!plugin.getConfig().getBoolean("mob-drops.enderman.enabled", true)) {
|
||||||
event.getDrops().clear();
|
event.getDrops().clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
loadConfig();
|
loadConfig();
|
||||||
plugin.getLogger().info("生物掉落配置已重载(末影人掉落: " + (endermanDropsAllowed ? "允许" : "禁止") + ")");
|
plugin.getLogger().info("生物掉落配置已重载(末影人: " + (endermanDropEnabled ? "开启" : "关闭") + ")");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,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 +39,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);
|
||||||
}
|
}
|
||||||
@@ -51,11 +46,14 @@ 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.enabled", true);
|
||||||
if (!plugin.getFeatureConfigManager().updateMainConfigValue(
|
config.set("mob-drops.enderman.enabled", newValue);
|
||||||
"mob-drops.enderman.allow-drops", newValue)) {
|
|
||||||
|
try {
|
||||||
|
config.save(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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,82 +7,23 @@ 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.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 Map<UUID, Boolean> observerSeePermissions = new HashMap<>();
|
|
||||||
|
|
||||||
public VanishListener(EssentialsC plugin) {
|
public VanishListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
VanishCommand.loadState(plugin);
|
|
||||||
this.permissionTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this::checkPermissions, 40L, 40L);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
Player player = event.getPlayer();
|
|
||||||
observerSeePermissions.put(player.getUniqueId(), player.hasPermission(VanishCommand.SEE_PERMISSION));
|
|
||||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
|
||||||
VanishCommand.restoreVisibility(plugin, player, false);
|
|
||||||
}
|
|
||||||
if (VanishCommand.isVanished(player)) {
|
|
||||||
event.joinMessage(null);
|
|
||||||
plugin.getServer().getScheduler().runTask(plugin, () -> VanishCommand.applyHiddenState(plugin, player));
|
|
||||||
}
|
|
||||||
VanishCommand.hideVanishedPlayersFrom(plugin, event.getPlayer());
|
VanishCommand.hideVanishedPlayersFrom(plugin, event.getPlayer());
|
||||||
}
|
}
|
||||||
|
|
||||||
@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)) {
|
VanishCommand.removeVanished(player);
|
||||||
event.quitMessage(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
|
||||||
permissionTask.cancel();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void checkPermissions() {
|
|
||||||
Set<UUID> onlinePlayers = new HashSet<>();
|
|
||||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
|
||||||
onlinePlayers.add(player.getUniqueId());
|
|
||||||
if (VanishCommand.isVanished(player) && !player.hasPermission("essentialsc.command.vanish")) {
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-56
@@ -1,56 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.maintenance;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import net.luckperms.api.LuckPerms;
|
|
||||||
import net.luckperms.api.model.user.User;
|
|
||||||
import net.luckperms.api.model.user.UserManager;
|
|
||||||
import net.luckperms.api.query.QueryOptions;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
|
|
||||||
public final class LuckPermsMaintenancePermissionResolver implements MaintenancePermissionResolver {
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final LuckPerms luckPerms;
|
|
||||||
private final UserManager userManager;
|
|
||||||
private final AtomicBoolean failureLogged = new AtomicBoolean();
|
|
||||||
|
|
||||||
public LuckPermsMaintenancePermissionResolver(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.luckPerms = plugin.getServer().getServicesManager().load(LuckPerms.class);
|
|
||||||
if (luckPerms == null) {
|
|
||||||
throw new IllegalStateException("LuckPerms 服务尚未注册");
|
|
||||||
}
|
|
||||||
this.userManager = luckPerms.getUserManager();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public PermissionResult checkPermission(UUID uniqueId, String permission) {
|
|
||||||
if (uniqueId == null || permission == null || permission.isBlank()) {
|
|
||||||
return PermissionResult.DENIED;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
User user = userManager.getUser(uniqueId);
|
|
||||||
if (user == null) {
|
|
||||||
user = userManager.loadUser(uniqueId).join();
|
|
||||||
}
|
|
||||||
|
|
||||||
QueryOptions queryOptions = luckPerms.getContextManager().getQueryOptions(user)
|
|
||||||
.orElseGet(() -> luckPerms.getContextManager().getStaticQueryOptions());
|
|
||||||
boolean granted = user.getCachedData()
|
|
||||||
.getPermissionData(queryOptions)
|
|
||||||
.checkPermission(permission)
|
|
||||||
.asBoolean();
|
|
||||||
failureLogged.set(false);
|
|
||||||
return granted ? PermissionResult.GRANTED : PermissionResult.DENIED;
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
if (failureLogged.compareAndSet(false, true)) {
|
|
||||||
plugin.getLogger().warning("LuckPerms 维护权限查询失败,将在玩家加入后复核权限: "
|
|
||||||
+ exception.getMessage());
|
|
||||||
}
|
|
||||||
return PermissionResult.UNAVAILABLE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,110 +4,93 @@ import cn.infstar.essentialsC.EssentialsC;
|
|||||||
import cn.infstar.essentialsC.ModuleManager;
|
import cn.infstar.essentialsC.ModuleManager;
|
||||||
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.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
|
import org.bukkit.event.player.PlayerLoginEvent;
|
||||||
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.event.server.ServerListPingEvent;
|
import org.bukkit.event.server.ServerListPingEvent;
|
||||||
|
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public final class MaintenanceListener implements Listener {
|
public final class MaintenanceListener implements Listener {
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final MaintenanceManager maintenanceManager;
|
|
||||||
private final MaintenancePermissionResolver permissionResolver;
|
|
||||||
|
|
||||||
public MaintenanceListener(EssentialsC plugin, MaintenanceManager maintenanceManager) {
|
public MaintenanceListener(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.maintenanceManager = maintenanceManager;
|
|
||||||
this.permissionResolver = MaintenancePermissionResolverFactory.create(plugin);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onServerListPing(ServerListPingEvent event) {
|
public void onServerListPing(ServerListPingEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)
|
||||||
|
|| maintenanceManager == null
|
||||||
|| !maintenanceManager.isEnabled()
|
|| !maintenanceManager.isEnabled()
|
||||||
|| !maintenanceManager.isMotdEnabled()) {
|
|| !maintenanceManager.isMotdEnabled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
event.motd(maintenanceManager.getMotd());
|
event.setMotd(maintenanceManager.getMotd());
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
@EventHandler
|
||||||
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
|
public void onPlayerLogin(PlayerLoginEvent event) {
|
||||||
if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)
|
||||||
|
|| maintenanceManager == null
|
||||||
|
|| !maintenanceManager.isEnabled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
MaintenanceManager.AccessSnapshot snapshot = maintenanceManager.getAccessSnapshot();
|
if (maintenanceManager.canJoin(event.getPlayer())) {
|
||||||
if (!snapshot.enabled()
|
|
||||||
|| snapshot.isWhitelisted(event.getUniqueId(), event.getName())
|
|
||||||
|| maintenanceManager.isOperator(event.getUniqueId())) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (permissionResolver == null) {
|
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, maintenanceManager.getKickMessage());
|
||||||
return;
|
notifyBlockedLogin(event, maintenanceManager);
|
||||||
}
|
|
||||||
|
|
||||||
MaintenancePermissionResolver.PermissionResult permissionResult = permissionResolver
|
|
||||||
.checkPermission(event.getUniqueId(), snapshot.bypassPermission());
|
|
||||||
if (permissionResult != MaintenancePermissionResolver.PermissionResult.DENIED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, snapshot.kickMessage());
|
|
||||||
notifyBlockedLogin(event.getName(), event.getUniqueId().toString(), event.getAddress(), snapshot);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE)) {
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (!plugin.getModuleManager().isEnabled(ModuleManager.MAINTENANCE) || maintenanceManager == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Player player = event.getPlayer();
|
maintenanceManager.addBossBarPlayer(event.getPlayer());
|
||||||
if (maintenanceManager.isEnabled() && !maintenanceManager.canJoin(player)) {
|
|
||||||
MaintenanceManager.AccessSnapshot snapshot = maintenanceManager.getAccessSnapshot();
|
|
||||||
player.kick(snapshot.kickMessage());
|
|
||||||
InetSocketAddress socketAddress = player.getAddress();
|
|
||||||
notifyBlockedLogin(player.getName(), player.getUniqueId().toString(),
|
|
||||||
socketAddress == null ? null : socketAddress.getAddress(), snapshot);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
maintenanceManager.addBossBarPlayer(player);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
|
MaintenanceManager maintenanceManager = plugin.getMaintenanceManager();
|
||||||
|
if (maintenanceManager != null) {
|
||||||
maintenanceManager.removeBossBarPlayer(event.getPlayer());
|
maintenanceManager.removeBossBarPlayer(event.getPlayer());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void notifyBlockedLogin(String playerName, String uniqueId, InetAddress inetAddress,
|
private void notifyBlockedLogin(PlayerLoginEvent event, MaintenanceManager maintenanceManager) {
|
||||||
MaintenanceManager.AccessSnapshot snapshot) {
|
if (!maintenanceManager.isNotifyEnabled()) {
|
||||||
if (!snapshot.notifyEnabled()) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String visibleAddress = snapshot.includeAddress() && inetAddress != null ? inetAddress.getHostAddress() : null;
|
String address = "";
|
||||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
InetAddress inetAddress = event.getAddress();
|
||||||
String address = visibleAddress == null
|
if (inetAddress != null) {
|
||||||
? EssentialsC.getLangManager().getString("maintenance.status.address-hidden")
|
address = inetAddress.getHostAddress();
|
||||||
: visibleAddress;
|
}
|
||||||
var message = EssentialsC.getLangManager().getPrefixedComponent("maintenance.messages.login-blocked",
|
|
||||||
Map.of("player", playerName, "uuid", uniqueId, "address", address));
|
|
||||||
|
|
||||||
for (Player onlinePlayer : plugin.getServer().getOnlinePlayers()) {
|
String message = EssentialsC.getLangManager().getPrefixedString("maintenance.messages.login-blocked",
|
||||||
if (onlinePlayer.hasPermission(snapshot.notifyPermission())) {
|
Map.of(
|
||||||
onlinePlayer.sendMessage(message);
|
"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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,13 @@
|
|||||||
package cn.infstar.essentialsC.maintenance;
|
package cn.infstar.essentialsC.maintenance;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.util.AtomicYamlWriter;
|
import org.bukkit.ChatColor;
|
||||||
import net.kyori.adventure.text.Component;
|
|
||||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
|
||||||
import org.bukkit.Bukkit;
|
|
||||||
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;
|
||||||
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 org.bukkit.scheduler.BukkitTask;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -26,23 +21,15 @@ import java.util.UUID;
|
|||||||
public final class MaintenanceManager {
|
public final class MaintenanceManager {
|
||||||
|
|
||||||
private static final int CURRENT_CONFIG_VERSION = 1;
|
private static final int CURRENT_CONFIG_VERSION = 1;
|
||||||
private static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.legacyAmpersand();
|
|
||||||
private static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection();
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final File configFile;
|
private final File configFile;
|
||||||
private final BukkitTask operatorCacheTask;
|
|
||||||
private FileConfiguration config;
|
private FileConfiguration config;
|
||||||
private BossBar bossBar;
|
private BossBar bossBar;
|
||||||
private volatile AccessSnapshot accessSnapshot = AccessSnapshot.disabled();
|
|
||||||
private volatile Set<UUID> operatorUuids = Set.of();
|
|
||||||
|
|
||||||
public MaintenanceManager(EssentialsC plugin) {
|
public MaintenanceManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.configFile = new File(plugin.getDataFolder(), "maintenance.yml");
|
this.configFile = new File(plugin.getDataFolder(), "maintenance.yml");
|
||||||
refreshOperatorCache();
|
|
||||||
this.operatorCacheTask = plugin.getServer().getScheduler()
|
|
||||||
.runTaskTimer(plugin, this::refreshOperatorCache, 20L, 20L);
|
|
||||||
reload();
|
reload();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,13 +38,12 @@ public final class MaintenanceManager {
|
|||||||
plugin.saveResource("maintenance.yml", false);
|
plugin.saveResource("maintenance.yml", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
config = loadConfiguration();
|
config = YamlConfiguration.loadConfiguration(configFile);
|
||||||
config.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
config.addDefault("config-version", CURRENT_CONFIG_VERSION);
|
||||||
config.addDefault("enabled", false);
|
config.addDefault("enabled", false);
|
||||||
config.addDefault("bypass-permission", "essentialsc.maintenance.bypass");
|
config.addDefault("bypass-permission", "essentialsc.maintenance.bypass");
|
||||||
config.addDefault("notify.enabled", true);
|
config.addDefault("notify.enabled", true);
|
||||||
config.addDefault("notify.permission", "essentialsc.maintenance.notify");
|
config.addDefault("notify.permission", "essentialsc.maintenance.notify");
|
||||||
config.addDefault("notify.include-address", false);
|
|
||||||
config.addDefault("whitelist.uuids", List.of());
|
config.addDefault("whitelist.uuids", List.of());
|
||||||
config.addDefault("whitelist.names", List.of());
|
config.addDefault("whitelist.names", List.of());
|
||||||
config.addDefault("motd.enabled", true);
|
config.addDefault("motd.enabled", true);
|
||||||
@@ -69,33 +55,18 @@ public final class MaintenanceManager {
|
|||||||
config.addDefault("bossbar.style", "SOLID");
|
config.addDefault("bossbar.style", "SOLID");
|
||||||
config.addDefault("bossbar.progress", 1.0D);
|
config.addDefault("bossbar.progress", 1.0D);
|
||||||
config.options().copyDefaults(true);
|
config.options().copyDefaults(true);
|
||||||
publishAccessSnapshot();
|
save();
|
||||||
refreshBossBar();
|
refreshBossBar();
|
||||||
if (isEnabled()) {
|
|
||||||
kickUnauthorizedPlayers();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEnabled() {
|
public boolean isEnabled() {
|
||||||
return config.getBoolean("enabled", false);
|
return config.getBoolean("enabled", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public OperationResult setEnabled(boolean enabled) {
|
public void setEnabled(boolean enabled) {
|
||||||
if (isEnabled() == enabled) {
|
|
||||||
return OperationResult.UNCHANGED;
|
|
||||||
}
|
|
||||||
boolean previous = isEnabled();
|
|
||||||
config.set("enabled", enabled);
|
config.set("enabled", enabled);
|
||||||
if (!save()) {
|
save();
|
||||||
config.set("enabled", previous);
|
|
||||||
return OperationResult.SAVE_FAILED;
|
|
||||||
}
|
|
||||||
publishAccessSnapshot();
|
|
||||||
refreshBossBar();
|
refreshBossBar();
|
||||||
if (enabled) {
|
|
||||||
kickUnauthorizedPlayers();
|
|
||||||
}
|
|
||||||
return OperationResult.SUCCESS;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getBypassPermission() {
|
public String getBypassPermission() {
|
||||||
@@ -110,20 +81,8 @@ public final class MaintenanceManager {
|
|||||||
return config.getString("notify.permission", "essentialsc.maintenance.notify");
|
return config.getString("notify.permission", "essentialsc.maintenance.notify");
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean shouldIncludeAddressInNotification() {
|
|
||||||
return config.getBoolean("notify.include-address", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean canJoin(Player player) {
|
public boolean canJoin(Player player) {
|
||||||
return player != null && (player.isOp() || player.hasPermission(getBypassPermission()) || isWhitelisted(player));
|
return player != null && (player.hasPermission(getBypassPermission()) || isWhitelisted(player));
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isOperator(UUID uniqueId) {
|
|
||||||
return uniqueId != null && operatorUuids.contains(uniqueId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public AccessSnapshot getAccessSnapshot() {
|
|
||||||
return accessSnapshot;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isWhitelisted(Player player) {
|
public boolean isWhitelisted(Player player) {
|
||||||
@@ -135,10 +94,10 @@ public final class MaintenanceManager {
|
|||||||
|| getWhitelistNames().contains(normalizeName(player.getName()));
|
|| getWhitelistNames().contains(normalizeName(player.getName()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public OperationResult addWhitelistEntry(String input) {
|
public boolean addWhitelistEntry(String input) {
|
||||||
String normalized = normalizeEntry(input);
|
String normalized = normalizeEntry(input);
|
||||||
if (normalized.isEmpty()) {
|
if (normalized.isEmpty()) {
|
||||||
return OperationResult.UNCHANGED;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
UUID uuid = parseUuid(normalized);
|
UUID uuid = parseUuid(normalized);
|
||||||
@@ -146,18 +105,13 @@ public final class MaintenanceManager {
|
|||||||
return addWhitelistUuid(uuid.toString());
|
return addWhitelistUuid(uuid.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
Player onlinePlayer = Bukkit.getPlayerExact(normalized);
|
|
||||||
if (onlinePlayer != null) {
|
|
||||||
return addWhitelistUuid(onlinePlayer.getUniqueId().toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
return addWhitelistName(input);
|
return addWhitelistName(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
public OperationResult removeWhitelistEntry(String input) {
|
public boolean removeWhitelistEntry(String input) {
|
||||||
String normalized = normalizeEntry(input);
|
String normalized = normalizeEntry(input);
|
||||||
if (normalized.isEmpty()) {
|
if (normalized.isEmpty()) {
|
||||||
return OperationResult.UNCHANGED;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
UUID uuid = parseUuid(normalized);
|
UUID uuid = parseUuid(normalized);
|
||||||
@@ -165,14 +119,6 @@ public final class MaintenanceManager {
|
|||||||
return removeWhitelistUuid(uuid.toString());
|
return removeWhitelistUuid(uuid.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
Player onlinePlayer = Bukkit.getPlayerExact(normalized);
|
|
||||||
if (onlinePlayer != null) {
|
|
||||||
OperationResult uuidResult = removeWhitelistUuid(onlinePlayer.getUniqueId().toString());
|
|
||||||
if (uuidResult != OperationResult.UNCHANGED) {
|
|
||||||
return uuidResult;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return removeWhitelistName(input);
|
return removeWhitelistName(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,11 +137,11 @@ public final class MaintenanceManager {
|
|||||||
return config.getBoolean("motd.enabled", true);
|
return config.getBoolean("motd.enabled", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Component getMotd() {
|
public String getMotd() {
|
||||||
return colorizeLines(config.getStringList("motd.lines"));
|
return colorizeLines(config.getStringList("motd.lines"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Component getKickMessage() {
|
public String getKickMessage() {
|
||||||
return colorizeLines(config.getStringList("kick-message"));
|
return colorizeLines(config.getStringList("kick-message"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,7 +152,7 @@ public final class MaintenanceManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bossBar = plugin.getServer().createBossBar(
|
bossBar = plugin.getServer().createBossBar(
|
||||||
LEGACY_SECTION.serialize(colorize(config.getString("bossbar.title", "&c服务器正在维护"))),
|
colorize(config.getString("bossbar.title", "&c服务器正在维护")),
|
||||||
readBossBarColor(),
|
readBossBarColor(),
|
||||||
readBossBarStyle()
|
readBossBarStyle()
|
||||||
);
|
);
|
||||||
@@ -222,6 +168,10 @@ public final class MaintenanceManager {
|
|||||||
if (bossBar == null || player == null || !player.isOnline()) {
|
if (bossBar == null || player == null || !player.isOnline()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (canJoin(player)) {
|
||||||
|
bossBar.removePlayer(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
bossBar.addPlayer(player);
|
bossBar.addPlayer(player);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,30 +181,10 @@ public final class MaintenanceManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void kickUnauthorizedPlayers() {
|
|
||||||
Component message = getKickMessage();
|
|
||||||
for (Player player : List.copyOf(plugin.getServer().getOnlinePlayers())) {
|
|
||||||
if (!canJoin(player)) {
|
|
||||||
player.kick(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
operatorCacheTask.cancel();
|
|
||||||
accessSnapshot = AccessSnapshot.disabled();
|
|
||||||
operatorUuids = Set.of();
|
|
||||||
clearBossBar();
|
clearBossBar();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void refreshOperatorCache() {
|
|
||||||
Set<UUID> operators = new LinkedHashSet<>();
|
|
||||||
for (org.bukkit.OfflinePlayer operator : plugin.getServer().getOperators()) {
|
|
||||||
operators.add(operator.getUniqueId());
|
|
||||||
}
|
|
||||||
operatorUuids = Set.copyOf(operators);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearBossBar() {
|
private void clearBossBar() {
|
||||||
if (bossBar == null) {
|
if (bossBar == null) {
|
||||||
return;
|
return;
|
||||||
@@ -292,28 +222,27 @@ public final class MaintenanceManager {
|
|||||||
return Math.max(0.0D, Math.min(1.0D, progress));
|
return Math.max(0.0D, Math.min(1.0D, progress));
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationResult addWhitelistUuid(String uuid) {
|
private boolean addWhitelistUuid(String uuid) {
|
||||||
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), true);
|
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationResult addWhitelistName(String name) {
|
private boolean addWhitelistName(String name) {
|
||||||
return updateWhitelist("whitelist.names", normalizeName(name), true);
|
return updateWhitelist("whitelist.names", normalizeName(name), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationResult removeWhitelistUuid(String uuid) {
|
private boolean removeWhitelistUuid(String uuid) {
|
||||||
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), false);
|
return updateWhitelist("whitelist.uuids", uuid.toLowerCase(Locale.ROOT), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationResult removeWhitelistName(String name) {
|
private boolean removeWhitelistName(String name) {
|
||||||
return updateWhitelist("whitelist.names", normalizeName(name), false);
|
return updateWhitelist("whitelist.names", normalizeName(name), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationResult updateWhitelist(String path, String value, boolean add) {
|
private boolean updateWhitelist(String path, String value, boolean add) {
|
||||||
if (value == null || value.isBlank()) {
|
if (value == null || value.isBlank()) {
|
||||||
return OperationResult.UNCHANGED;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> previousEntries = new ArrayList<>(config.getStringList(path));
|
|
||||||
Set<String> entries = path.endsWith(".names") ? getWhitelistNames() : getWhitelistUuids();
|
Set<String> entries = path.endsWith(".names") ? getWhitelistNames() : getWhitelistUuids();
|
||||||
boolean changed;
|
boolean changed;
|
||||||
if (add) {
|
if (add) {
|
||||||
@@ -322,21 +251,12 @@ public final class MaintenanceManager {
|
|||||||
changed = entries.remove(value);
|
changed = entries.remove(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!changed) {
|
if (changed) {
|
||||||
return OperationResult.UNCHANGED;
|
|
||||||
}
|
|
||||||
|
|
||||||
config.set(path, new ArrayList<>(entries));
|
config.set(path, new ArrayList<>(entries));
|
||||||
if (!save()) {
|
save();
|
||||||
config.set(path, previousEntries);
|
|
||||||
return OperationResult.SAVE_FAILED;
|
|
||||||
}
|
|
||||||
publishAccessSnapshot();
|
|
||||||
refreshBossBar();
|
refreshBossBar();
|
||||||
if (isEnabled()) {
|
|
||||||
kickUnauthorizedPlayers();
|
|
||||||
}
|
}
|
||||||
return OperationResult.SUCCESS;
|
return changed;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<String> getWhitelistUuids() {
|
private Set<String> getWhitelistUuids() {
|
||||||
@@ -377,85 +297,25 @@ public final class MaintenanceManager {
|
|||||||
return normalizeEntry(input).toLowerCase(Locale.ROOT);
|
return normalizeEntry(input).toLowerCase(Locale.ROOT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Component colorizeLines(List<String> lines) {
|
private String colorizeLines(List<String> lines) {
|
||||||
if (lines == null || lines.isEmpty()) {
|
if (lines == null || lines.isEmpty()) {
|
||||||
return Component.empty();
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
return colorize(String.join("\n", lines));
|
return String.join("\n", lines.stream()
|
||||||
|
.map(this::colorize)
|
||||||
|
.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private Component colorize(String text) {
|
private String colorize(String text) {
|
||||||
return LEGACY_AMPERSAND.deserialize(text == null ? "" : text);
|
return ChatColor.translateAlternateColorCodes('&', text == null ? "" : text);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void publishAccessSnapshot() {
|
private void save() {
|
||||||
Set<UUID> whitelistUuids = new LinkedHashSet<>();
|
|
||||||
for (String value : getWhitelistUuids()) {
|
|
||||||
UUID uuid = parseUuid(value);
|
|
||||||
if (uuid != null) {
|
|
||||||
whitelistUuids.add(uuid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
accessSnapshot = new AccessSnapshot(
|
|
||||||
isEnabled(),
|
|
||||||
getBypassPermission(),
|
|
||||||
whitelistUuids,
|
|
||||||
getWhitelistNames(),
|
|
||||||
getKickMessage(),
|
|
||||||
isNotifyEnabled(),
|
|
||||||
getNotifyPermission(),
|
|
||||||
shouldIncludeAddressInNotification()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean save() {
|
|
||||||
try {
|
try {
|
||||||
AtomicYamlWriter.save(config, configFile);
|
config.save(configFile);
|
||||||
return true;
|
} catch (IOException e) {
|
||||||
} catch (Exception e) {
|
|
||||||
plugin.getLogger().warning("保存 maintenance.yml 失败: " + e.getMessage());
|
plugin.getLogger().warning("保存 maintenance.yml 失败: " + e.getMessage());
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private YamlConfiguration loadConfiguration() {
|
|
||||||
YamlConfiguration loaded = new YamlConfiguration();
|
|
||||||
loaded.options().parseComments(true);
|
|
||||||
try {
|
|
||||||
loaded.load(configFile);
|
|
||||||
} catch (IOException | InvalidConfigurationException exception) {
|
|
||||||
plugin.getLogger().severe("加载 maintenance.yml 失败: " + exception.getMessage());
|
|
||||||
throw new IllegalStateException("无法加载 maintenance.yml,请修复配置格式后重试。", exception);
|
|
||||||
}
|
|
||||||
return loaded;
|
|
||||||
}
|
|
||||||
|
|
||||||
public record AccessSnapshot(boolean enabled, String bypassPermission, Set<UUID> whitelistUuids,
|
|
||||||
Set<String> whitelistNames, Component kickMessage, boolean notifyEnabled,
|
|
||||||
String notifyPermission, boolean includeAddress) {
|
|
||||||
|
|
||||||
public AccessSnapshot {
|
|
||||||
bypassPermission = bypassPermission == null ? "" : bypassPermission;
|
|
||||||
whitelistUuids = Set.copyOf(whitelistUuids);
|
|
||||||
whitelistNames = Set.copyOf(whitelistNames);
|
|
||||||
kickMessage = kickMessage == null ? Component.empty() : kickMessage;
|
|
||||||
notifyPermission = notifyPermission == null ? "" : notifyPermission;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isWhitelisted(UUID uniqueId, String playerName) {
|
|
||||||
return whitelistUuids.contains(uniqueId)
|
|
||||||
|| whitelistNames.contains(playerName == null ? "" : playerName.trim().toLowerCase(Locale.ROOT));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static AccessSnapshot disabled() {
|
|
||||||
return new AccessSnapshot(false, "", Set.of(), Set.of(), Component.empty(), false, "", false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum OperationResult {
|
|
||||||
SUCCESS,
|
|
||||||
UNCHANGED,
|
|
||||||
SAVE_FAILED
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.maintenance;
|
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
public interface MaintenancePermissionResolver {
|
|
||||||
|
|
||||||
PermissionResult checkPermission(UUID uniqueId, String permission);
|
|
||||||
|
|
||||||
enum PermissionResult {
|
|
||||||
GRANTED,
|
|
||||||
DENIED,
|
|
||||||
UNAVAILABLE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.maintenance;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import org.bukkit.plugin.Plugin;
|
|
||||||
|
|
||||||
import java.lang.reflect.InvocationTargetException;
|
|
||||||
|
|
||||||
final class MaintenancePermissionResolverFactory {
|
|
||||||
|
|
||||||
private static final String LUCKPERMS_RESOLVER_CLASS =
|
|
||||||
"cn.infstar.essentialsC.maintenance.LuckPermsMaintenancePermissionResolver";
|
|
||||||
|
|
||||||
private MaintenancePermissionResolverFactory() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static MaintenancePermissionResolver create(EssentialsC plugin) {
|
|
||||||
Plugin luckPerms = plugin.getServer().getPluginManager().getPlugin("LuckPerms");
|
|
||||||
if (luckPerms == null || !luckPerms.isEnabled()) {
|
|
||||||
plugin.getLogger().info("未检测到 LuckPerms,维护模式将在玩家加入后复核绕过权限。");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Class<?> resolverClass = Class.forName(LUCKPERMS_RESOLVER_CLASS, true, plugin.getClass().getClassLoader());
|
|
||||||
return (MaintenancePermissionResolver) resolverClass
|
|
||||||
.getConstructor(EssentialsC.class)
|
|
||||||
.newInstance(plugin);
|
|
||||||
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException
|
|
||||||
| IllegalAccessException | InvocationTargetException | LinkageError exception) {
|
|
||||||
plugin.getLogger().warning("LuckPerms 维护权限解析器初始化失败,将在玩家加入后复核权限: "
|
|
||||||
+ exception.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,231 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.skinbridge;
|
|
||||||
|
|
||||||
import com.destroystokyo.paper.profile.PlayerProfile;
|
|
||||||
import com.destroystokyo.paper.profile.ProfileProperty;
|
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import com.google.gson.JsonParser;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.time.Duration;
|
|
||||||
|
|
||||||
public final class MineSkinGateway implements SkinBridgeGateway {
|
|
||||||
|
|
||||||
private static final String TEXTURES_PROPERTY = "textures";
|
|
||||||
private static final String QUEUE_PATH = "/v2/queue";
|
|
||||||
private static final long POLL_INTERVAL_MILLIS = 1000L;
|
|
||||||
private static final int MAX_RATE_LIMIT_RETRIES = 3;
|
|
||||||
|
|
||||||
private final HttpClient httpClient;
|
|
||||||
private final URI queueUri;
|
|
||||||
private final String apiKey;
|
|
||||||
private final String visibility;
|
|
||||||
private final int timeoutSeconds;
|
|
||||||
private final long minimumSubmitIntervalMillis;
|
|
||||||
private final String userAgent;
|
|
||||||
private final Object submissionLock = new Object();
|
|
||||||
private long lastSubmissionMillis;
|
|
||||||
|
|
||||||
public MineSkinGateway(HttpClient httpClient, String endpoint, String apiKey, String visibility, int timeoutSeconds,
|
|
||||||
long minimumSubmitIntervalMillis, String userAgent) {
|
|
||||||
this.httpClient = httpClient;
|
|
||||||
this.queueUri = URI.create(normalizeEndpoint(endpoint) + QUEUE_PATH);
|
|
||||||
this.apiKey = apiKey;
|
|
||||||
this.visibility = normalizeVisibility(visibility);
|
|
||||||
this.timeoutSeconds = timeoutSeconds;
|
|
||||||
this.minimumSubmitIntervalMillis = minimumSubmitIntervalMillis;
|
|
||||||
this.userAgent = userAgent;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public GeneratedSkin generateSkin(String skinUrl, SkinModel model) throws Exception {
|
|
||||||
JsonObject requestBody = new JsonObject();
|
|
||||||
requestBody.addProperty("url", skinUrl);
|
|
||||||
requestBody.addProperty("variant", model == SkinModel.SLIM ? "slim" : "classic");
|
|
||||||
requestBody.addProperty("visibility", visibility);
|
|
||||||
|
|
||||||
HttpResponse<String> response;
|
|
||||||
synchronized (submissionLock) {
|
|
||||||
waitForSubmissionInterval();
|
|
||||||
try {
|
|
||||||
response = submitWithRateLimitRetry(requestBody.toString());
|
|
||||||
} finally {
|
|
||||||
lastSubmissionMillis = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
JsonObject body = parseResponse(response);
|
|
||||||
if (response.statusCode() == 200) {
|
|
||||||
return parseGeneratedSkin(body);
|
|
||||||
}
|
|
||||||
if (response.statusCode() != 202) {
|
|
||||||
throw apiError("提交 MineSkin 生成请求", response, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject job = object(body, "job");
|
|
||||||
String jobId = string(job, "id");
|
|
||||||
return pollJob(jobId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void applySkin(Player player, GeneratedSkin skin) {
|
|
||||||
PlayerProfile profile = player.getPlayerProfile();
|
|
||||||
profile.removeProperty(TEXTURES_PROPERTY);
|
|
||||||
profile.setProperty(new ProfileProperty(TEXTURES_PROPERTY, skin.value(), skin.signature()));
|
|
||||||
player.setPlayerProfile(profile);
|
|
||||||
}
|
|
||||||
|
|
||||||
private GeneratedSkin pollJob(String jobId) throws Exception {
|
|
||||||
long deadline = System.nanoTime() + Duration.ofSeconds(timeoutSeconds).toNanos();
|
|
||||||
URI jobUri = URI.create(queueUri + "/" + jobId);
|
|
||||||
while (System.nanoTime() < deadline) {
|
|
||||||
HttpResponse<String> response = send(HttpRequest.newBuilder(jobUri).GET());
|
|
||||||
if (response.statusCode() == 429) {
|
|
||||||
Thread.sleep(readRetryDelayMillis(response, 0));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
JsonObject body = parseResponse(response);
|
|
||||||
if (response.statusCode() != 200) {
|
|
||||||
throw apiError("查询 MineSkin 生成任务", response, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject job = object(body, "job");
|
|
||||||
String status = string(job, "status");
|
|
||||||
if ("completed".equalsIgnoreCase(status)) {
|
|
||||||
return parseGeneratedSkin(body);
|
|
||||||
}
|
|
||||||
if ("failed".equalsIgnoreCase(status)) {
|
|
||||||
throw new IllegalStateException("MineSkin 生成任务失败: " + errorMessage(body));
|
|
||||||
}
|
|
||||||
if (!"waiting".equalsIgnoreCase(status) && !"active".equalsIgnoreCase(status)) {
|
|
||||||
throw new IllegalStateException("MineSkin 返回未知任务状态: " + status);
|
|
||||||
}
|
|
||||||
Thread.sleep(POLL_INTERVAL_MILLIS);
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("MineSkin 生成任务超时,请增大 config.yml 中的 skin-bridge.mineskin.request-timeout-seconds。");
|
|
||||||
}
|
|
||||||
|
|
||||||
private void waitForSubmissionInterval() throws InterruptedException {
|
|
||||||
long waitMillis = minimumSubmitIntervalMillis - (System.currentTimeMillis() - lastSubmissionMillis);
|
|
||||||
if (waitMillis > 0L) {
|
|
||||||
Thread.sleep(waitMillis);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private HttpResponse<String> submitWithRateLimitRetry(String requestBody) throws Exception {
|
|
||||||
HttpResponse<String> response = null;
|
|
||||||
for (int attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
|
|
||||||
response = send(HttpRequest.newBuilder(queueUri)
|
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
|
|
||||||
.header("Content-Type", "application/json"));
|
|
||||||
if (response.statusCode() != 429 || attempt == MAX_RATE_LIMIT_RETRIES) {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
Thread.sleep(readRetryDelayMillis(response, attempt));
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
private long readRetryDelayMillis(HttpResponse<?> response, int attempt) {
|
|
||||||
long fallback = Math.min(30_000L, 1000L << Math.min(attempt, 5));
|
|
||||||
return response.headers().firstValue("Retry-After")
|
|
||||||
.map(String::trim)
|
|
||||||
.filter(value -> value.matches("\\d+"))
|
|
||||||
.map(value -> {
|
|
||||||
try {
|
|
||||||
return Math.min(60_000L, Long.parseLong(value) * 1000L);
|
|
||||||
} catch (NumberFormatException ignored) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.orElse(fallback);
|
|
||||||
}
|
|
||||||
|
|
||||||
private HttpResponse<String> send(HttpRequest.Builder builder) throws Exception {
|
|
||||||
HttpRequest request = builder
|
|
||||||
.timeout(Duration.ofSeconds(timeoutSeconds))
|
|
||||||
.header("Accept", "application/json")
|
|
||||||
.header("Authorization", "Bearer " + apiKey)
|
|
||||||
.header("User-Agent", userAgent)
|
|
||||||
.build();
|
|
||||||
return httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonObject parseResponse(HttpResponse<String> response) {
|
|
||||||
if (response.body() == null || response.body().isBlank()) {
|
|
||||||
throw new IllegalStateException("MineSkin 返回空响应,HTTP " + response.statusCode());
|
|
||||||
}
|
|
||||||
if (response.body().length() > 1_048_576) {
|
|
||||||
throw new IllegalStateException("MineSkin 响应超过 1 MiB 限制。");
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return JsonParser.parseString(response.body()).getAsJsonObject();
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
throw new IllegalStateException("MineSkin 返回了无效 JSON,HTTP " + response.statusCode(), exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private GeneratedSkin parseGeneratedSkin(JsonObject body) {
|
|
||||||
JsonObject skin = object(body, "skin");
|
|
||||||
JsonObject texture = object(skin, "texture");
|
|
||||||
JsonObject data = object(texture, "data");
|
|
||||||
return new GeneratedSkin(string(data, "value"), string(data, "signature"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private IllegalStateException apiError(String action, HttpResponse<String> response, JsonObject body) {
|
|
||||||
return new IllegalStateException(action + "失败,HTTP " + response.statusCode() + ": " + errorMessage(body));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String errorMessage(JsonObject body) {
|
|
||||||
for (String key : new String[]{"message", "error", "code"}) {
|
|
||||||
if (body.has(key) && body.get(key).isJsonPrimitive()) {
|
|
||||||
return body.get(key).getAsString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "未提供错误信息";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonObject object(JsonObject parent, String key) {
|
|
||||||
if (!parent.has(key) || !parent.get(key).isJsonObject()) {
|
|
||||||
throw new IllegalStateException("MineSkin 响应缺少对象字段: " + key);
|
|
||||||
}
|
|
||||||
return parent.getAsJsonObject(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String string(JsonObject parent, String key) {
|
|
||||||
if (!parent.has(key) || !parent.get(key).isJsonPrimitive()) {
|
|
||||||
throw new IllegalStateException("MineSkin 响应缺少字符串字段: " + key);
|
|
||||||
}
|
|
||||||
String value = parent.get(key).getAsString();
|
|
||||||
if (value.isBlank()) {
|
|
||||||
throw new IllegalStateException("MineSkin 响应字符串字段为空: " + key);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String normalizeEndpoint(String endpoint) {
|
|
||||||
String normalized = endpoint == null ? "" : endpoint.trim();
|
|
||||||
while (normalized.endsWith("/")) {
|
|
||||||
normalized = normalized.substring(0, normalized.length() - 1);
|
|
||||||
}
|
|
||||||
if (normalized.isBlank()) {
|
|
||||||
throw new IllegalArgumentException("MineSkin API 地址不能为空。");
|
|
||||||
}
|
|
||||||
URI uri = URI.create(normalized);
|
|
||||||
if (!"https".equalsIgnoreCase(uri.getScheme())) {
|
|
||||||
throw new IllegalArgumentException("MineSkin API 必须使用 HTTPS。");
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String normalizeVisibility(String visibility) {
|
|
||||||
String normalized = visibility == null ? "" : visibility.trim().toLowerCase(java.util.Locale.ROOT);
|
|
||||||
if (!normalized.equals("public") && !normalized.equals("unlisted") && !normalized.equals("private")) {
|
|
||||||
throw new IllegalArgumentException("MineSkin visibility 必须是 public、unlisted 或 private。");
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.skinbridge;
|
|
||||||
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
|
|
||||||
interface SkinBridgeGateway {
|
|
||||||
|
|
||||||
GeneratedSkin generateSkin(String skinUrl, SkinModel model) throws Exception;
|
|
||||||
|
|
||||||
void applySkin(Player player, GeneratedSkin skin) throws Exception;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum SkinModel {
|
|
||||||
CLASSIC,
|
|
||||||
SLIM
|
|
||||||
}
|
|
||||||
|
|
||||||
record GeneratedSkin(String value, String signature) {
|
|
||||||
}
|
|
||||||
@@ -1,818 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.skinbridge;
|
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
|
||||||
import com.destroystokyo.paper.profile.ProfileProperty;
|
|
||||||
import com.google.gson.JsonArray;
|
|
||||||
import com.google.gson.JsonElement;
|
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import com.google.gson.JsonParser;
|
|
||||||
import org.bukkit.Bukkit;
|
|
||||||
import org.bukkit.configuration.ConfigurationSection;
|
|
||||||
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 org.bukkit.event.player.PlayerQuitEvent;
|
|
||||||
import org.bukkit.scheduler.BukkitRunnable;
|
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ArrayBlockingQueue;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
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.ThreadFactory;
|
|
||||||
import java.util.concurrent.ThreadPoolExecutor;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
|
||||||
|
|
||||||
public final class SkinBridgeManager implements Listener {
|
|
||||||
|
|
||||||
private static final int WORKER_THREADS = 2;
|
|
||||||
private static final int MAX_PENDING_LOOKUPS = 100;
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
|
||||||
private final HttpClient httpClient;
|
|
||||||
private final ThreadPoolExecutor executor;
|
|
||||||
private final SkinCacheStore cacheStore;
|
|
||||||
private final ConcurrentMap<UUID, CachedLookup> cache = new ConcurrentHashMap<>();
|
|
||||||
private final ConcurrentMap<SkinCacheStore.Key, SkinCacheStore.Entry> generatedSkinCache = 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, String> loginSkinUrls = new ConcurrentHashMap<>();
|
|
||||||
private final ConcurrentMap<SkinCacheStore.Key, CompletableFuture<GeneratedSkin>> pendingGenerations = new ConcurrentHashMap<>();
|
|
||||||
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 SkinBridgeGateway gateway;
|
|
||||||
private volatile boolean debug;
|
|
||||||
private volatile boolean sendPlayerMessage;
|
|
||||||
private volatile boolean logDetectionResults;
|
|
||||||
private volatile int requestTimeoutSeconds;
|
|
||||||
private volatile int cacheMinutes;
|
|
||||||
private volatile int maxGeneratedCacheEntries;
|
|
||||||
private volatile int forceRefreshCooldownSeconds;
|
|
||||||
private volatile boolean requireCurrentTextureMatch;
|
|
||||||
private volatile long joinDelayTicks;
|
|
||||||
private volatile Set<String> excludedUuids = Set.of();
|
|
||||||
private volatile Set<String> excludedNames = Set.of();
|
|
||||||
|
|
||||||
public SkinBridgeManager(EssentialsC plugin) {
|
|
||||||
this.plugin = plugin;
|
|
||||||
this.cacheStore = new SkinCacheStore(plugin);
|
|
||||||
this.httpClient = HttpClient.newBuilder()
|
|
||||||
.connectTimeout(Duration.ofSeconds(5))
|
|
||||||
.followRedirects(HttpClient.Redirect.NEVER)
|
|
||||||
.build();
|
|
||||||
this.executor = new ThreadPoolExecutor(
|
|
||||||
WORKER_THREADS,
|
|
||||||
WORKER_THREADS,
|
|
||||||
0L,
|
|
||||||
TimeUnit.MILLISECONDS,
|
|
||||||
new ArrayBlockingQueue<>(MAX_PENDING_LOOKUPS),
|
|
||||||
new SkinBridgeThreadFactory(),
|
|
||||||
new ThreadPoolExecutor.AbortPolicy()
|
|
||||||
);
|
|
||||||
reload();
|
|
||||||
loadGeneratedSkinCache();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void reload() {
|
|
||||||
configurationGeneration.incrementAndGet();
|
|
||||||
cancelScheduledLookups();
|
|
||||||
cancelRunningLookups();
|
|
||||||
pendingLookups.clear();
|
|
||||||
pendingGenerations.clear();
|
|
||||||
FileConfiguration config = plugin.getConfig();
|
|
||||||
|
|
||||||
debug = plugin.getConfig().getBoolean("debug", false);
|
|
||||||
sendPlayerMessage = config.getBoolean("skin-bridge.send-player-message", true);
|
|
||||||
logDetectionResults = config.getBoolean("skin-bridge.log-detection-results", true);
|
|
||||||
requestTimeoutSeconds = clamp(config.getInt("skin-bridge.profile-request-timeout-seconds", 5), 1, 30);
|
|
||||||
String mineSkinEndpoint = config.getString("skin-bridge.mineskin.endpoint", "https://api.mineskin.org");
|
|
||||||
String mineSkinApiKey = config.getString("skin-bridge.mineskin.api-key", "").trim();
|
|
||||||
String mineSkinVisibility = config.getString("skin-bridge.mineskin.visibility", "unlisted");
|
|
||||||
int mineSkinTimeoutSeconds = clamp(config.getInt("skin-bridge.mineskin.request-timeout-seconds", 30), 10, 180);
|
|
||||||
long minimumSubmitIntervalMillis = clamp(
|
|
||||||
config.getLong("skin-bridge.mineskin.minimum-submit-interval-millis", 1000L), 0L, 10000L);
|
|
||||||
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);
|
|
||||||
requireCurrentTextureMatch = config.getBoolean("skin-bridge.require-current-texture-match", true);
|
|
||||||
joinDelayTicks = clamp(config.getLong("skin-bridge.join-delay-ticks", 20L), 0, 200);
|
|
||||||
excludedUuids = loadNormalizedValues(config, "skin-bridge.exclusions.uuids");
|
|
||||||
excludedNames = loadNormalizedValues(config, "skin-bridge.exclusions.names");
|
|
||||||
providers = loadProviders(config);
|
|
||||||
cache.clear();
|
|
||||||
gateway = loadGateway(mineSkinEndpoint, mineSkinApiKey, mineSkinVisibility,
|
|
||||||
mineSkinTimeoutSeconds, minimumSubmitIntervalMillis);
|
|
||||||
|
|
||||||
if (gateway == null) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 已启用,但未配置有效的 MineSkin API Key,皮肤同步不会执行。");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void shutdown() {
|
|
||||||
shuttingDown = true;
|
|
||||||
configurationGeneration.incrementAndGet();
|
|
||||||
cancelScheduledLookups();
|
|
||||||
cancelRunningLookups();
|
|
||||||
executor.shutdownNow();
|
|
||||||
cancelGeneratedCacheSave();
|
|
||||||
saveGeneratedSkinCache();
|
|
||||||
cache.clear();
|
|
||||||
generatedSkinCache.clear();
|
|
||||||
pendingLookups.clear();
|
|
||||||
pendingGenerations.clear();
|
|
||||||
forceRefreshCooldowns.clear();
|
|
||||||
loginSkinUrls.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler
|
|
||||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
|
||||||
UUID playerId = event.getPlayer().getUniqueId();
|
|
||||||
getCurrentSkinUrl(event.getPlayer()).ifPresentOrElse(
|
|
||||||
skinUrl -> loginSkinUrls.put(playerId, skinUrl),
|
|
||||||
() -> loginSkinUrls.remove(playerId)
|
|
||||||
);
|
|
||||||
queueSync(event.getPlayer(), false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventHandler
|
|
||||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
|
||||||
UUID playerId = event.getPlayer().getUniqueId();
|
|
||||||
loginSkinUrls.remove(playerId);
|
|
||||||
pendingLookups.remove(playerId);
|
|
||||||
cancelScheduledLookup(playerId);
|
|
||||||
cancelRunningLookup(playerId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public SyncResult queueSync(Player player, boolean force) {
|
|
||||||
UUID playerId = player.getUniqueId();
|
|
||||||
if (isExcluded(player)) {
|
|
||||||
cache.put(playerId, cached(null, null, State.EXCLUDED));
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.excluded", Map.of());
|
|
||||||
if (logDetectionResults) {
|
|
||||||
plugin.getLogger().info("SkinBridge 已根据排除名单跳过玩家: " + player.getName());
|
|
||||||
}
|
|
||||||
return SyncResult.EXCLUDED;
|
|
||||||
}
|
|
||||||
if (gateway == null) {
|
|
||||||
return SyncResult.DEPENDENCY_MISSING;
|
|
||||||
}
|
|
||||||
if (providers.isEmpty()) {
|
|
||||||
return SyncResult.NO_PROVIDERS;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (force) {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
long expiresAt = forceRefreshCooldowns.getOrDefault(playerId, 0L);
|
|
||||||
if (expiresAt > now) {
|
|
||||||
return SyncResult.REFRESH_COOLDOWN;
|
|
||||||
}
|
|
||||||
cache.remove(playerId);
|
|
||||||
}
|
|
||||||
|
|
||||||
CachedLookup cached = cache.get(playerId);
|
|
||||||
if (!force && cached != null && !cached.hasExpired()) {
|
|
||||||
if (cached.skin() != null) {
|
|
||||||
applySkin(playerId, cached, configurationGeneration.get());
|
|
||||||
}
|
|
||||||
return SyncResult.CACHED;
|
|
||||||
}
|
|
||||||
|
|
||||||
long lookupGeneration = configurationGeneration.get();
|
|
||||||
if (!pendingLookups.containsKey(playerId) && pendingLookups.size() >= MAX_PENDING_LOOKUPS) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 查询队列已满,已跳过玩家: " + player.getName());
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.queue-full", Map.of());
|
|
||||||
return SyncResult.QUEUE_FULL;
|
|
||||||
}
|
|
||||||
if (!registerPendingLookup(playerId, lookupGeneration)) {
|
|
||||||
return SyncResult.ALREADY_RUNNING;
|
|
||||||
}
|
|
||||||
if (force && forceRefreshCooldownSeconds > 0) {
|
|
||||||
forceRefreshCooldowns.put(playerId,
|
|
||||||
System.currentTimeMillis() + forceRefreshCooldownSeconds * 1000L);
|
|
||||||
}
|
|
||||||
|
|
||||||
String playerName = player.getName();
|
|
||||||
String loginSkinUrl = loginSkinUrls.computeIfAbsent(playerId,
|
|
||||||
ignored -> getCurrentSkinUrl(player).orElse(""));
|
|
||||||
String currentSkinUrl = loginSkinUrl.isEmpty() ? null : loginSkinUrl;
|
|
||||||
BukkitRunnable scheduledLookup = new BukkitRunnable() {
|
|
||||||
@Override
|
|
||||||
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());
|
|
||||||
return SyncResult.QUEUED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Status getStatus(Player player) {
|
|
||||||
CachedLookup cached = cache.get(player.getUniqueId());
|
|
||||||
if (cached != null && !cached.hasExpired()) {
|
|
||||||
return new Status(cached.state(), cached.providerId());
|
|
||||||
}
|
|
||||||
if (pendingLookups.containsKey(player.getUniqueId())) {
|
|
||||||
return new Status(State.PENDING, null);
|
|
||||||
}
|
|
||||||
return new Status(State.UNKNOWN, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getRemainingForceRefreshCooldownSeconds(Player player) {
|
|
||||||
long remaining = forceRefreshCooldowns.getOrDefault(player.getUniqueId(), 0L) - System.currentTimeMillis();
|
|
||||||
return remaining <= 0L ? 0 : (int) Math.ceil(remaining / 1000.0D);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isSkinGatewayAvailable() {
|
|
||||||
return gateway != null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getProviderCount() {
|
|
||||||
return providers.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getModuleDetail() {
|
|
||||||
if (gateway == null) {
|
|
||||||
return "缺少 MineSkin API Key 或配置无效";
|
|
||||||
}
|
|
||||||
if (providers.isEmpty()) {
|
|
||||||
return "未配置有效 Provider";
|
|
||||||
}
|
|
||||||
return providers.size() + " 个 Provider 已就绪";
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startLookup(UUID playerId, String playerName, String currentSkinUrl, long lookupGeneration) {
|
|
||||||
Player player = Bukkit.getPlayer(playerId);
|
|
||||||
if (executor.isShutdown() || lookupGeneration != configurationGeneration.get()
|
|
||||||
|| !isLookupActive(playerId, lookupGeneration) || player == null || !player.isOnline()) {
|
|
||||||
pendingLookups.remove(playerId, lookupGeneration);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
LookupKey lookupKey = new LookupKey(playerId, lookupGeneration);
|
|
||||||
try {
|
|
||||||
Future<?> lookupTask = executor.submit(() -> {
|
|
||||||
try {
|
|
||||||
CachedLookup resolved = resolve(playerId, playerName, currentSkinUrl);
|
|
||||||
if (lookupGeneration != configurationGeneration.get() || !isLookupActive(playerId, lookupGeneration)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
cache.put(playerId, resolved);
|
|
||||||
if (resolved.skin() != null) {
|
|
||||||
applySkin(playerId, resolved, lookupGeneration);
|
|
||||||
} else {
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.not-external", Map.of());
|
|
||||||
if (logDetectionResults) {
|
|
||||||
plugin.getLogger().info("SkinBridge 未匹配到外置皮肤站,已保留玩家皮肤: " + playerName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception exception) {
|
|
||||||
if (!isLookupActive(playerId, lookupGeneration) || exception instanceof InterruptedException) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
plugin.getLogger().warning("SkinBridge 查询 " + playerName + " 的皮肤资料失败: " + exception.getMessage());
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
|
||||||
if (debug) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 异常类型: " + exception.getClass().getName());
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
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) {
|
|
||||||
pendingLookups.remove(playerId, lookupGeneration);
|
|
||||||
plugin.getLogger().warning("SkinBridge 查询队列拒绝了玩家任务: " + playerName);
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.queue-full", Map.of());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean registerPendingLookup(UUID playerId, long lookupGeneration) {
|
|
||||||
while (true) {
|
|
||||||
Long runningGeneration = pendingLookups.putIfAbsent(playerId, lookupGeneration);
|
|
||||||
if (runningGeneration == null) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (runningGeneration == lookupGeneration) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (pendingLookups.replace(playerId, runningGeneration, lookupGeneration)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private CachedLookup resolve(UUID playerId, String playerName, String currentSkinUrl) throws Exception {
|
|
||||||
Exception lastFailure = null;
|
|
||||||
for (SkinProvider provider : providers) {
|
|
||||||
Optional<ProviderProfile> profile;
|
|
||||||
try {
|
|
||||||
profile = queryProfile(provider, playerId, playerName);
|
|
||||||
} catch (Exception exception) {
|
|
||||||
lastFailure = exception;
|
|
||||||
plugin.getLogger().warning("SkinBridge Provider " + provider.id() + " 查询失败: " + exception.getMessage());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (profile.isEmpty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
SkinBridgeGateway currentGateway = gateway;
|
|
||||||
if (currentGateway == null) {
|
|
||||||
throw new IllegalStateException("MineSkin 网关在查询期间不可用。");
|
|
||||||
}
|
|
||||||
|
|
||||||
ProviderProfile matchedProfile = profile.get();
|
|
||||||
if (requireCurrentTextureMatch
|
|
||||||
&& (currentSkinUrl == null || !currentSkinUrl.equals(matchedProfile.skinUrl()))) {
|
|
||||||
if (debug) {
|
|
||||||
plugin.getLogger().info("SkinBridge 已忽略与当前登录纹理不一致的 Provider: " + provider.name());
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (logDetectionResults) {
|
|
||||||
plugin.getLogger().info("SkinBridge 已识别玩家 " + playerName + " 的皮肤来源: " + provider.name());
|
|
||||||
}
|
|
||||||
SkinCacheStore.Key cacheKey = new SkinCacheStore.Key(matchedProfile.skinUrl(), matchedProfile.model());
|
|
||||||
GeneratedSkin generatedSkin = getOrGenerateSkin(cacheKey, currentGateway);
|
|
||||||
return cached(provider.name(), generatedSkin, State.EXTERNAL);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (lastFailure != null) {
|
|
||||||
throw new IllegalStateException("所有可用 Provider 均未能完成确认。", lastFailure);
|
|
||||||
}
|
|
||||||
return cached(null, null, State.NOT_EXTERNAL);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<ProviderProfile> queryProfile(SkinProvider provider, UUID playerId, String playerName) throws Exception {
|
|
||||||
URI requestUri = URI.create(provider.resolveProfileUrl(playerId));
|
|
||||||
HttpRequest request = HttpRequest.newBuilder(requestUri)
|
|
||||||
.timeout(Duration.ofSeconds(requestTimeoutSeconds))
|
|
||||||
.header("Accept", "application/json")
|
|
||||||
.header("User-Agent", "EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge")
|
|
||||||
.GET()
|
|
||||||
.build();
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
|
||||||
|
|
||||||
if (response.statusCode() == 204 || response.statusCode() == 404) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
if (response.statusCode() != 200) {
|
|
||||||
throw new IllegalStateException(provider.id() + " 返回 HTTP " + response.statusCode());
|
|
||||||
}
|
|
||||||
if (response.body().length() > 1_048_576) {
|
|
||||||
throw new IllegalStateException(provider.id() + " 返回的 profile 超过 1 MiB 限制。");
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject profile = JsonParser.parseString(response.body()).getAsJsonObject();
|
|
||||||
String profileId = requireString(profile, "id");
|
|
||||||
String profileName = requireString(profile, "name");
|
|
||||||
if (!normalizeUuid(profileId).equals(normalizeUuid(playerId.toString())) || !profileName.equalsIgnoreCase(playerName)) {
|
|
||||||
if (debug) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 忽略 " + provider.id() + " 的不匹配 profile: " + profileName + " / " + profileId);
|
|
||||||
}
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject textureData = findTextureData(profile);
|
|
||||||
JsonObject skin = textureData.getAsJsonObject("textures").getAsJsonObject("SKIN");
|
|
||||||
String skinUrl = requireString(skin, "url");
|
|
||||||
URI skinUri = URI.create(skinUrl);
|
|
||||||
if (!"https".equalsIgnoreCase(skinUri.getScheme())) {
|
|
||||||
throw new IllegalStateException(provider.id() + " 返回了非 HTTPS 皮肤 URL。");
|
|
||||||
}
|
|
||||||
|
|
||||||
SkinModel model = SkinModel.CLASSIC;
|
|
||||||
JsonObject metadata = skin.has("metadata") && skin.get("metadata").isJsonObject()
|
|
||||||
? skin.getAsJsonObject("metadata")
|
|
||||||
: null;
|
|
||||||
if (metadata != null && "slim".equalsIgnoreCase(metadata.has("model") ? metadata.get("model").getAsString() : "")) {
|
|
||||||
model = SkinModel.SLIM;
|
|
||||||
}
|
|
||||||
return Optional.of(new ProviderProfile(skinUrl, model));
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonObject findTextureData(JsonObject profile) {
|
|
||||||
JsonArray properties = profile.has("properties") && profile.get("properties").isJsonArray()
|
|
||||||
? profile.getAsJsonArray("properties")
|
|
||||||
: new JsonArray();
|
|
||||||
for (JsonElement element : properties) {
|
|
||||||
if (!element.isJsonObject()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
JsonObject property = element.getAsJsonObject();
|
|
||||||
if (!"textures".equals(property.has("name") ? property.get("name").getAsString() : "")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String encodedValue = requireString(property, "value");
|
|
||||||
String decodedValue = new String(Base64.getDecoder().decode(encodedValue), StandardCharsets.UTF_8);
|
|
||||||
JsonObject textureData = JsonParser.parseString(decodedValue).getAsJsonObject();
|
|
||||||
if (textureData.has("textures")
|
|
||||||
&& textureData.get("textures").isJsonObject()
|
|
||||||
&& textureData.getAsJsonObject("textures").has("SKIN")
|
|
||||||
&& textureData.getAsJsonObject("textures").get("SKIN").isJsonObject()) {
|
|
||||||
return textureData;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("profile 不包含有效的皮肤 textures 属性。");
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<String> getCurrentSkinUrl(Player player) {
|
|
||||||
try {
|
|
||||||
for (ProfileProperty property : player.getPlayerProfile().getProperties()) {
|
|
||||||
if (!"textures".equals(property.getName())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String decoded = new String(Base64.getDecoder().decode(property.getValue()), StandardCharsets.UTF_8);
|
|
||||||
JsonObject textureData = JsonParser.parseString(decoded).getAsJsonObject();
|
|
||||||
if (!textureData.has("textures") || !textureData.get("textures").isJsonObject()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
JsonObject textures = textureData.getAsJsonObject("textures");
|
|
||||||
if (!textures.has("SKIN") || !textures.get("SKIN").isJsonObject()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String skinUrl = requireString(textures.getAsJsonObject("SKIN"), "url");
|
|
||||||
if ("https".equalsIgnoreCase(URI.create(skinUrl).getScheme())) {
|
|
||||||
return Optional.of(skinUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
if (debug) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 无法解析玩家当前纹理: " + exception.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadGeneratedSkinCache() {
|
|
||||||
generatedSkinCache.putAll(cacheStore.load());
|
|
||||||
trimGeneratedSkinCache();
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void saveGeneratedSkinCache() {
|
|
||||||
if (!generatedCacheDirty) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
generatedSkinCache.entrySet().removeIf(entry -> entry.getValue().expiresAtMillis() <= now);
|
|
||||||
trimGeneratedSkinCache();
|
|
||||||
if (cacheStore.save(generatedSkinCache)) {
|
|
||||||
generatedCacheDirty = false;
|
|
||||||
} else if (!shuttingDown) {
|
|
||||||
scheduleGeneratedCacheSave();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
GeneratedSkin generated = currentGateway.generateSkin(cacheKey.skinUrl(), cacheKey.model());
|
|
||||||
cacheGeneratedSkin(cacheKey, generated);
|
|
||||||
created.complete(generated);
|
|
||||||
return generated;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
created.completeExceptionally(exception);
|
|
||||||
throw exception;
|
|
||||||
} catch (Error error) {
|
|
||||||
created.completeExceptionally(error);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
pendingGenerations.remove(cacheKey, created);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private GeneratedSkin awaitGeneratedSkin(CompletableFuture<GeneratedSkin> running) throws Exception {
|
|
||||||
try {
|
|
||||||
return running.get();
|
|
||||||
} catch (InterruptedException exception) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw exception;
|
|
||||||
} catch (ExecutionException 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) {
|
|
||||||
ConfigurationSection providersSection = config.getConfigurationSection("skin-bridge.providers");
|
|
||||||
if (providersSection == null) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<SkinProvider> loadedProviders = new ArrayList<>();
|
|
||||||
for (String key : providersSection.getKeys(false)) {
|
|
||||||
ConfigurationSection providerSection = providersSection.getConfigurationSection(key);
|
|
||||||
if (providerSection == null || !providerSection.getBoolean("enabled", false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String profileUrl = providerSection.getString("profile-url", "").trim();
|
|
||||||
if (!profileUrl.contains("{uuid}") && !profileUrl.contains("{uuid-dashed}")) {
|
|
||||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 缺少 {uuid} 或 {uuid-dashed} 占位符,已跳过。");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
URI profileUri = URI.create(profileUrl.replace("{uuid}", "00000000000000000000000000000000")
|
|
||||||
.replace("{uuid-dashed}", "00000000-0000-0000-0000-000000000000"));
|
|
||||||
if (!"https".equalsIgnoreCase(profileUri.getScheme())) {
|
|
||||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 必须使用 HTTPS,已跳过。");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String configuredName = providerSection.getString("name", key);
|
|
||||||
String providerName = configuredName == null ? key : configuredName.trim();
|
|
||||||
if (providerName.isEmpty()) {
|
|
||||||
providerName = key;
|
|
||||||
}
|
|
||||||
loadedProviders.add(new SkinProvider(key, providerName, profileUrl,
|
|
||||||
providerSection.getInt("priority", 100)));
|
|
||||||
} catch (IllegalArgumentException exception) {
|
|
||||||
plugin.getLogger().warning("SkinBridge Provider " + key + " 的 profile-url 无效,已跳过。");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
loadedProviders.sort(Comparator.comparingInt(SkinProvider::priority).thenComparing(SkinProvider::id));
|
|
||||||
return List.copyOf(loadedProviders);
|
|
||||||
}
|
|
||||||
|
|
||||||
private SkinBridgeGateway loadGateway(String endpoint, String apiKey, String visibility, int timeoutSeconds,
|
|
||||||
long minimumSubmitIntervalMillis) {
|
|
||||||
if (apiKey.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return new MineSkinGateway(httpClient, endpoint, apiKey, visibility, timeoutSeconds,
|
|
||||||
minimumSubmitIntervalMillis,
|
|
||||||
"EssentialsC/" + plugin.getPluginMeta().getVersion() + " SkinBridge");
|
|
||||||
} catch (Exception | LinkageError exception) {
|
|
||||||
plugin.getLogger().warning("加载 MineSkin SkinBridge 适配器失败: " + exception.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> loadNormalizedValues(FileConfiguration config, String path) {
|
|
||||||
Set<String> values = ConcurrentHashMap.newKeySet();
|
|
||||||
for (String value : config.getStringList(path)) {
|
|
||||||
String normalized = value == null ? "" : value.trim().toLowerCase(java.util.Locale.ROOT);
|
|
||||||
if (!normalized.isEmpty()) {
|
|
||||||
values.add(normalized);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Set.copyOf(values);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isExcluded(Player player) {
|
|
||||||
return excludedUuids.contains(player.getUniqueId().toString().toLowerCase(java.util.Locale.ROOT))
|
|
||||||
|| excludedNames.contains(player.getName().toLowerCase(java.util.Locale.ROOT));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applySkin(UUID playerId, CachedLookup resolved, long lookupGeneration) {
|
|
||||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
|
||||||
if (lookupGeneration != configurationGeneration.get()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Player player = Bukkit.getPlayer(playerId);
|
|
||||||
SkinBridgeGateway currentGateway = gateway;
|
|
||||||
if (player == null || !player.isOnline() || currentGateway == null || resolved.skin() == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
currentGateway.applySkin(player, resolved.skin());
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.synced",
|
|
||||||
Map.of("provider", resolved.providerId()));
|
|
||||||
if (debug) {
|
|
||||||
plugin.getLogger().info("SkinBridge 已应用 " + player.getName() + " 的 " + resolved.providerId() + " 皮肤。");
|
|
||||||
}
|
|
||||||
} catch (Exception exception) {
|
|
||||||
plugin.getLogger().warning("SkinBridge 应用 " + player.getName() + " 的皮肤失败: " + exception.getMessage());
|
|
||||||
sendPlayerNotification(playerId, "skin-bridge.notifications.failed", Map.of());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendPlayerNotification(UUID playerId, String messagePath, Map<String, String> placeholders) {
|
|
||||||
if (!sendPlayerMessage) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Runnable notification = () -> {
|
|
||||||
Player player = Bukkit.getPlayer(playerId);
|
|
||||||
if (player != null && player.isOnline()) {
|
|
||||||
player.sendMessage(EssentialsC.getLangManager().getPrefixedString(messagePath, placeholders));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if (Bukkit.isPrimaryThread()) {
|
|
||||||
notification.run();
|
|
||||||
} else {
|
|
||||||
Bukkit.getScheduler().runTask(plugin, notification);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private CachedLookup cached(String providerId, GeneratedSkin skin, State state) {
|
|
||||||
return new CachedLookup(providerId, skin, state, System.currentTimeMillis() + Duration.ofMinutes(cacheMinutes).toMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String requireString(JsonObject object, String key) {
|
|
||||||
if (!object.has(key) || !object.get(key).isJsonPrimitive()) {
|
|
||||||
throw new IllegalStateException("缺少字符串字段: " + key);
|
|
||||||
}
|
|
||||||
String value = object.get(key).getAsString();
|
|
||||||
if (value.isBlank()) {
|
|
||||||
throw new IllegalStateException("字符串字段为空: " + key);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String normalizeUuid(String value) {
|
|
||||||
return value.replace("-", "").toLowerCase(java.util.Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int clamp(int value, int min, int max) {
|
|
||||||
return Math.max(min, Math.min(max, value));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static long clamp(long value, long min, long max) {
|
|
||||||
return Math.max(min, Math.min(max, value));
|
|
||||||
}
|
|
||||||
|
|
||||||
private record SkinProvider(String id, String name, String profileUrl, int priority) {
|
|
||||||
private String resolveProfileUrl(UUID playerId) {
|
|
||||||
return profileUrl.replace("{uuid}", playerId.toString().replace("-", ""))
|
|
||||||
.replace("{uuid-dashed}", playerId.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private record ProviderProfile(String skinUrl, SkinModel model) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record LookupKey(UUID playerId, long generation) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record CachedLookup(String providerId, GeneratedSkin skin, State state, long expiresAtMillis) {
|
|
||||||
private boolean hasExpired() {
|
|
||||||
return System.currentTimeMillis() >= expiresAtMillis;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class SkinBridgeThreadFactory implements ThreadFactory {
|
|
||||||
@Override
|
|
||||||
public Thread newThread(Runnable runnable) {
|
|
||||||
Thread thread = new Thread(runnable, "EssentialsC-SkinBridge");
|
|
||||||
thread.setDaemon(true);
|
|
||||||
return thread;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum SyncResult {
|
|
||||||
QUEUED,
|
|
||||||
CACHED,
|
|
||||||
ALREADY_RUNNING,
|
|
||||||
EXCLUDED,
|
|
||||||
QUEUE_FULL,
|
|
||||||
DEPENDENCY_MISSING,
|
|
||||||
NO_PROVIDERS,
|
|
||||||
REFRESH_COOLDOWN
|
|
||||||
}
|
|
||||||
|
|
||||||
public record Status(State state, String providerId) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum State {
|
|
||||||
EXTERNAL,
|
|
||||||
EXCLUDED,
|
|
||||||
NOT_EXTERNAL,
|
|
||||||
PENDING,
|
|
||||||
UNKNOWN
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +1,35 @@
|
|||||||
package cn.infstar.essentialsC.teleport;
|
package cn.infstar.essentialsC.teleport;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.EssentialsC;
|
import cn.infstar.essentialsC.EssentialsC;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportEvent;
|
import net.kyori.adventure.text.Component;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportRequestReceiveEvent;
|
import net.kyori.adventure.text.event.ClickEvent;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportRequestReplyEvent;
|
import net.kyori.adventure.text.event.HoverEvent;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportRequestSendEvent;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportWarmupCancelledEvent;
|
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||||
import cn.infstar.essentialsC.api.event.TeleportWarmupEvent;
|
|
||||||
import cn.infstar.essentialsC.commands.VanishCommand;
|
|
||||||
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;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.entity.EntityDamageEvent;
|
import org.bukkit.event.entity.EntityDamageEvent;
|
||||||
|
import org.bukkit.event.player.PlayerMoveEvent;
|
||||||
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.event.player.PlayerTeleportEvent;
|
|
||||||
import org.bukkit.permissions.PermissionAttachmentInfo;
|
|
||||||
import org.bukkit.scheduler.BukkitTask;
|
import org.bukkit.scheduler.BukkitTask;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayDeque;
|
import java.util.ArrayDeque;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.Deque;
|
import java.util.Deque;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -41,23 +40,17 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
|
|
||||||
public static final String BYPASS_WARMUP_PERMISSION = "essentialsc.tpa.bypass-warmup";
|
public static final String BYPASS_WARMUP_PERMISSION = "essentialsc.tpa.bypass-warmup";
|
||||||
public static final String BYPASS_COOLDOWN_PERMISSION = "essentialsc.tpa.bypass-cooldown";
|
public static final String BYPASS_COOLDOWN_PERMISSION = "essentialsc.tpa.bypass-cooldown";
|
||||||
public static final String WARMUP_PERMISSION_PREFIX = "essentialsc.tpa.warmup.";
|
|
||||||
private static final double MOVEMENT_THRESHOLD = 0.1D;
|
|
||||||
|
|
||||||
private final EssentialsC plugin;
|
private final EssentialsC plugin;
|
||||||
private final Map<UUID, Deque<TeleportRequest>> requests = new HashMap<>();
|
private final Map<UUID, Deque<TeleportRequest>> requests = new HashMap<>();
|
||||||
private final Map<UUID, PendingTeleport> warmups = new HashMap<>();
|
private final Map<UUID, PendingTeleport> warmups = new HashMap<>();
|
||||||
private final Map<UUID, Long> sendCooldowns = new HashMap<>();
|
private final Map<UUID, Long> sendCooldowns = new HashMap<>();
|
||||||
private final Map<UUID, Long> acceptCooldowns = new HashMap<>();
|
private final Map<UUID, Long> acceptCooldowns = new HashMap<>();
|
||||||
private final Map<UUID, BukkitTask> invulnerabilityTasks = new HashMap<>();
|
|
||||||
private final Set<UUID> warmupDamagedPlayers = 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 BukkitTask cleanupTask;
|
private BukkitTask cleanupTask;
|
||||||
|
|
||||||
private int timeoutSeconds;
|
private int timeoutSeconds;
|
||||||
private int maxPendingRequests;
|
|
||||||
private boolean strictTpaRequests;
|
private boolean strictTpaRequests;
|
||||||
private boolean strictTpaHereRequests;
|
private boolean strictTpaHereRequests;
|
||||||
private int warmupSeconds;
|
private int warmupSeconds;
|
||||||
@@ -66,9 +59,8 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
private boolean cooldownsEnabled;
|
private boolean cooldownsEnabled;
|
||||||
private int sendCooldownSeconds;
|
private int sendCooldownSeconds;
|
||||||
private int acceptCooldownSeconds;
|
private int acceptCooldownSeconds;
|
||||||
|
private double warmupMoveThreshold;
|
||||||
private String warmupDisplay;
|
private String warmupDisplay;
|
||||||
private int teleportInvulnerabilitySeconds;
|
|
||||||
private boolean teleportAsync;
|
|
||||||
private boolean soundsEnabled;
|
private boolean soundsEnabled;
|
||||||
private String requestSound;
|
private String requestSound;
|
||||||
private String warmupSound;
|
private String warmupSound;
|
||||||
@@ -77,17 +69,12 @@ 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");
|
||||||
reload();
|
reload();
|
||||||
TeleportStateStore.CooldownState cooldownState = stateStore.loadCooldowns();
|
|
||||||
sendCooldowns.putAll(cooldownState.send());
|
|
||||||
acceptCooldowns.putAll(cooldownState.accept());
|
|
||||||
cleanupTask = Bukkit.getScheduler().runTaskTimer(plugin, this::cleanupExpiredState, 1200L, 1200L);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public void reload() {
|
||||||
plugin.getConfig().addDefault("tpa.timeout-seconds", 60);
|
plugin.getConfig().addDefault("tpa.timeout-seconds", 60);
|
||||||
plugin.getConfig().addDefault("tpa.max-pending-requests", 5);
|
|
||||||
plugin.getConfig().addDefault("tpa.strict-tpa-requests", false);
|
plugin.getConfig().addDefault("tpa.strict-tpa-requests", false);
|
||||||
plugin.getConfig().addDefault("tpa.strict-tpahere-requests", true);
|
plugin.getConfig().addDefault("tpa.strict-tpahere-requests", true);
|
||||||
plugin.getConfig().addDefault("tpa.warmup-seconds", 5);
|
plugin.getConfig().addDefault("tpa.warmup-seconds", 5);
|
||||||
@@ -96,20 +83,17 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
plugin.getConfig().addDefault("tpa.cooldowns.enabled", true);
|
plugin.getConfig().addDefault("tpa.cooldowns.enabled", true);
|
||||||
plugin.getConfig().addDefault("tpa.cooldowns.cooldown-times.SEND_TELEPORT_REQUEST", 0);
|
plugin.getConfig().addDefault("tpa.cooldowns.cooldown-times.SEND_TELEPORT_REQUEST", 0);
|
||||||
plugin.getConfig().addDefault("tpa.cooldowns.cooldown-times.ACCEPT_TELEPORT_REQUEST", 0);
|
plugin.getConfig().addDefault("tpa.cooldowns.cooldown-times.ACCEPT_TELEPORT_REQUEST", 0);
|
||||||
|
plugin.getConfig().addDefault("tpa.warmup-move-threshold", 0.1D);
|
||||||
plugin.getConfig().addDefault("tpa.warmup-display", "actionbar");
|
plugin.getConfig().addDefault("tpa.warmup-display", "actionbar");
|
||||||
plugin.getConfig().addDefault("tpa.teleport-invulnerability-seconds", 0);
|
|
||||||
plugin.getConfig().addDefault("tpa.teleport-async", true);
|
|
||||||
plugin.getConfig().addDefault("tpa.sounds.enabled", true);
|
plugin.getConfig().addDefault("tpa.sounds.enabled", true);
|
||||||
plugin.getConfig().addDefault("tpa.sounds.request-received", "entity.experience_orb.pickup");
|
plugin.getConfig().addDefault("tpa.sounds.request-received", "entity.experience_orb.pickup");
|
||||||
plugin.getConfig().addDefault("tpa.sounds.warmup", "block.note_block.banjo");
|
plugin.getConfig().addDefault("tpa.sounds.warmup", "block.note_block.banjo");
|
||||||
plugin.getConfig().addDefault("tpa.sounds.cancelled", "entity.item.break");
|
plugin.getConfig().addDefault("tpa.sounds.cancelled", "entity.item.break");
|
||||||
plugin.getConfig().addDefault("tpa.sounds.complete", "entity.enderman.teleport");
|
plugin.getConfig().addDefault("tpa.sounds.complete", "entity.enderman.teleport");
|
||||||
plugin.getConfig().set("tpa.warmup-move-threshold", null);
|
|
||||||
plugin.getConfig().options().copyDefaults(true);
|
plugin.getConfig().options().copyDefaults(true);
|
||||||
|
plugin.saveConfig();
|
||||||
|
|
||||||
timeoutSeconds = Math.max(0, plugin.getConfig().getInt("tpa.timeout-seconds", 60));
|
timeoutSeconds = Math.max(5, plugin.getConfig().getInt("tpa.timeout-seconds", 60));
|
||||||
maxPendingRequests = Math.max(1, Math.min(100,
|
|
||||||
plugin.getConfig().getInt("tpa.max-pending-requests", 5)));
|
|
||||||
strictTpaRequests = plugin.getConfig().getBoolean("tpa.strict-tpa-requests", false);
|
strictTpaRequests = plugin.getConfig().getBoolean("tpa.strict-tpa-requests", false);
|
||||||
strictTpaHereRequests = plugin.getConfig().getBoolean("tpa.strict-tpahere-requests", true);
|
strictTpaHereRequests = plugin.getConfig().getBoolean("tpa.strict-tpahere-requests", true);
|
||||||
warmupSeconds = Math.max(0, plugin.getConfig().getInt("tpa.warmup-seconds", 5));
|
warmupSeconds = Math.max(0, plugin.getConfig().getInt("tpa.warmup-seconds", 5));
|
||||||
@@ -118,31 +102,24 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
cooldownsEnabled = plugin.getConfig().getBoolean("tpa.cooldowns.enabled", true);
|
cooldownsEnabled = plugin.getConfig().getBoolean("tpa.cooldowns.enabled", true);
|
||||||
sendCooldownSeconds = Math.max(0, plugin.getConfig().getInt("tpa.cooldowns.cooldown-times.SEND_TELEPORT_REQUEST", 0));
|
sendCooldownSeconds = Math.max(0, plugin.getConfig().getInt("tpa.cooldowns.cooldown-times.SEND_TELEPORT_REQUEST", 0));
|
||||||
acceptCooldownSeconds = Math.max(0, plugin.getConfig().getInt("tpa.cooldowns.cooldown-times.ACCEPT_TELEPORT_REQUEST", 0));
|
acceptCooldownSeconds = Math.max(0, plugin.getConfig().getInt("tpa.cooldowns.cooldown-times.ACCEPT_TELEPORT_REQUEST", 0));
|
||||||
warmupDisplay = plugin.getConfig().getString("tpa.warmup-display", "actionbar").toLowerCase(Locale.ROOT);
|
warmupMoveThreshold = Math.max(0.0D, plugin.getConfig().getDouble("tpa.warmup-move-threshold", 0.1D));
|
||||||
teleportInvulnerabilitySeconds = Math.max(0,
|
warmupDisplay = plugin.getConfig().getString("tpa.warmup-display", "actionbar").toLowerCase();
|
||||||
plugin.getConfig().getInt("tpa.teleport-invulnerability-seconds", 0));
|
|
||||||
teleportAsync = plugin.getConfig().getBoolean("tpa.teleport-async", true);
|
|
||||||
soundsEnabled = plugin.getConfig().getBoolean("tpa.sounds.enabled", true);
|
soundsEnabled = plugin.getConfig().getBoolean("tpa.sounds.enabled", true);
|
||||||
requestSound = plugin.getConfig().getString("tpa.sounds.request-received", "entity.experience_orb.pickup");
|
requestSound = plugin.getConfig().getString("tpa.sounds.request-received", "entity.experience_orb.pickup");
|
||||||
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());
|
startCleanupTask();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
if (cleanupTask != null) {
|
|
||||||
cleanupTask.cancel();
|
|
||||||
cleanupTask = null;
|
|
||||||
}
|
|
||||||
stateStore.saveCooldowns(sendCooldowns, acceptCooldowns);
|
|
||||||
requests.clear();
|
requests.clear();
|
||||||
sendCooldowns.clear();
|
sendCooldowns.clear();
|
||||||
acceptCooldowns.clear();
|
acceptCooldowns.clear();
|
||||||
cancelAllWarmups();
|
cancelAllWarmups();
|
||||||
clearAllInvulnerability();
|
cancelCleanupTask();
|
||||||
stateStore.saveIgnoringRequests(ignoringRequests);
|
saveIgnoringRequests();
|
||||||
}
|
}
|
||||||
|
|
||||||
public CreateRequestResult createRequest(Player requester, Player target, TeleportRequest.Type type) {
|
public CreateRequestResult createRequest(Player requester, Player target, TeleportRequest.Type type) {
|
||||||
@@ -155,6 +132,13 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return new CreateRequestResult(CreateRequestStatus.ON_COOLDOWN, null, sendCooldown.seconds());
|
return new CreateRequestResult(CreateRequestStatus.ON_COOLDOWN, null, sendCooldown.seconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Optional<TeleportRequest> existingRequest = findIncoming(target, requester.getName());
|
||||||
|
if (existingRequest.isPresent()
|
||||||
|
&& existingRequest.get().type() == type
|
||||||
|
&& !existingRequest.get().hasExpired()) {
|
||||||
|
return new CreateRequestResult(CreateRequestStatus.DUPLICATE, existingRequest.get());
|
||||||
|
}
|
||||||
|
|
||||||
TeleportRequest request = new TeleportRequest(
|
TeleportRequest request = new TeleportRequest(
|
||||||
requester.getUniqueId(),
|
requester.getUniqueId(),
|
||||||
requester.getName(),
|
requester.getName(),
|
||||||
@@ -167,15 +151,7 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
TeleportRequest.Status.PENDING
|
TeleportRequest.Status.PENDING
|
||||||
);
|
);
|
||||||
|
|
||||||
if (applyCooldown) {
|
if (isIgnoringRequests(target)) {
|
||||||
TeleportRequestSendEvent sendEvent = new TeleportRequestSendEvent(requester, request);
|
|
||||||
Bukkit.getPluginManager().callEvent(sendEvent);
|
|
||||||
if (sendEvent.isCancelled()) {
|
|
||||||
return new CreateRequestResult(CreateRequestStatus.CANCELLED, request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isIgnoringRequests(target) || isVanished(target)) {
|
|
||||||
request.setStatus(TeleportRequest.Status.IGNORED);
|
request.setStatus(TeleportRequest.Status.IGNORED);
|
||||||
if (applyCooldown) {
|
if (applyCooldown) {
|
||||||
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
||||||
@@ -183,24 +159,8 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return new CreateRequestResult(CreateRequestStatus.IGNORED, request);
|
return new CreateRequestResult(CreateRequestStatus.IGNORED, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
Optional<TeleportRequest> existingRequest = findIncoming(target, requester.getName());
|
|
||||||
if (existingRequest.isPresent()
|
|
||||||
&& existingRequest.get().type() == type
|
|
||||||
&& !existingRequest.get().hasExpired()) {
|
|
||||||
if (applyCooldown) {
|
|
||||||
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
|
||||||
}
|
|
||||||
return new CreateRequestResult(CreateRequestStatus.DUPLICATE, existingRequest.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
TeleportRequestReceiveEvent receiveEvent = new TeleportRequestReceiveEvent(target, request);
|
|
||||||
Bukkit.getPluginManager().callEvent(receiveEvent);
|
|
||||||
if (receiveEvent.isCancelled()) {
|
|
||||||
return new CreateRequestResult(CreateRequestStatus.CANCELLED, request);
|
|
||||||
}
|
|
||||||
Deque<TeleportRequest> targetRequests = requests.computeIfAbsent(target.getUniqueId(), ignored -> new ArrayDeque<>());
|
Deque<TeleportRequest> targetRequests = requests.computeIfAbsent(target.getUniqueId(), ignored -> new ArrayDeque<>());
|
||||||
pruneExpiredRequests(targetRequests);
|
targetRequests.addFirst(request);
|
||||||
TeleportRequestQueuePolicy.addFirstBounded(targetRequests, request, maxPendingRequests);
|
|
||||||
if (applyCooldown) {
|
if (applyCooldown) {
|
||||||
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
||||||
}
|
}
|
||||||
@@ -226,25 +186,34 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
.findFirst();
|
.findFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Optional<TeleportRequest> findOutgoing(Player requester, String targetName) {
|
||||||
|
return requests.values().stream()
|
||||||
|
.flatMap(Deque::stream)
|
||||||
|
.filter(request -> request.requesterId().equals(requester.getUniqueId()))
|
||||||
|
.filter(request -> !request.hasExpired())
|
||||||
|
.filter(request -> targetName == null || request.targetName().equalsIgnoreCase(targetName))
|
||||||
|
.max(Comparator.comparingLong(TeleportRequest::expiresAtMillis));
|
||||||
|
}
|
||||||
|
|
||||||
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();
|
||||||
@@ -256,51 +225,36 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return TeleportResult.onCooldown(acceptCooldown.seconds());
|
return TeleportResult.onCooldown(acceptCooldown.seconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
removeIncomingByRequester(target, request.requesterName());
|
|
||||||
if (request.hasExpired()) {
|
if (request.hasExpired()) {
|
||||||
|
removeIncomingByRequester(target, request.requesterName());
|
||||||
return TeleportResult.EXPIRED;
|
return TeleportResult.EXPIRED;
|
||||||
}
|
}
|
||||||
|
|
||||||
request.setStatus(TeleportRequest.Status.ACCEPTED);
|
|
||||||
TeleportRequestReplyEvent replyEvent = new TeleportRequestReplyEvent(target, request);
|
|
||||||
Bukkit.getPluginManager().callEvent(replyEvent);
|
|
||||||
if (replyEvent.isCancelled()) {
|
|
||||||
return TeleportResult.CANCELLED;
|
|
||||||
}
|
|
||||||
Map<String, String> placeholders = placeholders(request);
|
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.accepted-target", placeholders));
|
|
||||||
|
|
||||||
Player requester = Bukkit.getPlayer(request.requesterId());
|
Player requester = Bukkit.getPlayer(request.requesterId());
|
||||||
if (requester == null || !requester.isOnline()) {
|
Player currentTarget = Bukkit.getPlayer(request.targetId());
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.player-offline", placeholders));
|
if (requester == null || currentTarget == null || !requester.isOnline() || !currentTarget.isOnline()) {
|
||||||
return TeleportResult.PLAYER_OFFLINE;
|
return TeleportResult.PLAYER_OFFLINE;
|
||||||
}
|
}
|
||||||
requester.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.accepted-sender", placeholders));
|
|
||||||
|
|
||||||
TeleportPlan plan = createTeleportPlan(request, requester, target);
|
TeleportPlan plan = createTeleportPlan(request, requester, currentTarget);
|
||||||
Player teleporter = plan.teleporter();
|
Player teleporter = plan.teleporter();
|
||||||
int playerWarmupSeconds = getTeleportWarmupSeconds(teleporter);
|
|
||||||
if (playerWarmupSeconds <= 0 || teleporter.hasPermission(BYPASS_WARMUP_PERMISSION)) {
|
|
||||||
return executeTeleport(plan, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (warmups.containsKey(teleporter.getUniqueId())) {
|
if (warmups.containsKey(teleporter.getUniqueId())) {
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.already-warming-up"));
|
return TeleportResult.ALREADY_WARMING_UP;
|
||||||
return TeleportResult.ACCEPTED_WITHOUT_TELEPORT;
|
|
||||||
}
|
|
||||||
OptionalIntCooldown teleporterCooldown = getRemainingCooldown(teleporter, acceptCooldowns);
|
|
||||||
if (teleporterCooldown.active()) {
|
|
||||||
sendAcceptCooldown(teleporter, teleporterCooldown.seconds());
|
|
||||||
return TeleportResult.ACCEPTED_WITHOUT_TELEPORT;
|
|
||||||
}
|
|
||||||
if (isMoving(teleporter)) {
|
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.warmup-stand-still"));
|
|
||||||
return TeleportResult.ACCEPTED_WITHOUT_TELEPORT;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return startWarmup(plan, playerWarmupSeconds)
|
removeIncomingByRequester(target, request.requesterName());
|
||||||
? TeleportResult.WARMING_UP
|
request.setStatus(TeleportRequest.Status.ACCEPTED);
|
||||||
: TeleportResult.CANCELLED;
|
if (warmupSeconds <= 0 || teleporter.hasPermission(BYPASS_WARMUP_PERMISSION)) {
|
||||||
|
TeleportResult result = executeTeleport(plan, true);
|
||||||
|
if (result.status() == TeleportResult.Status.SUCCESS) {
|
||||||
|
startCooldown(target, acceptCooldowns, acceptCooldownSeconds);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
startWarmup(plan);
|
||||||
|
startCooldown(target, acceptCooldowns, acceptCooldownSeconds);
|
||||||
|
return TeleportResult.WARMING_UP;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TeleportResult deny(Player target, TeleportRequest request) {
|
public TeleportResult deny(Player target, TeleportRequest request) {
|
||||||
@@ -311,31 +265,28 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return TeleportResult.EXPIRED;
|
return TeleportResult.EXPIRED;
|
||||||
}
|
}
|
||||||
request.setStatus(TeleportRequest.Status.DECLINED);
|
request.setStatus(TeleportRequest.Status.DECLINED);
|
||||||
TeleportRequestReplyEvent replyEvent = new TeleportRequestReplyEvent(target, request);
|
|
||||||
Bukkit.getPluginManager().callEvent(replyEvent);
|
|
||||||
if (replyEvent.isCancelled()) {
|
|
||||||
return TeleportResult.CANCELLED;
|
|
||||||
}
|
|
||||||
Map<String, String> placeholders = placeholders(request);
|
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.denied-target", placeholders));
|
|
||||||
Player requester = Bukkit.getPlayer(request.requesterId());
|
|
||||||
if (requester != null && requester.isOnline()) {
|
|
||||||
requester.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.denied-sender", placeholders));
|
|
||||||
} else {
|
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.player-offline", placeholders));
|
|
||||||
}
|
|
||||||
return TeleportResult.SUCCESS;
|
return TeleportResult.SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean cancel(TeleportRequest request) {
|
||||||
|
Deque<TeleportRequest> targetRequests = requests.get(request.targetId());
|
||||||
|
if (targetRequests == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean removed = targetRequests.removeIf(candidate ->
|
||||||
|
candidate.requesterName().equalsIgnoreCase(request.requesterName()));
|
||||||
|
if (targetRequests.isEmpty()) {
|
||||||
|
requests.remove(request.targetId());
|
||||||
|
}
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isIgnoringRequests(Player player) {
|
public boolean isIgnoringRequests(Player player) {
|
||||||
return ignoringRequests.contains(player.getUniqueId());
|
return ignoringRequests.contains(player.getUniqueId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isVanished(Player player) {
|
public boolean toggleIgnoringRequests(Player player) {
|
||||||
return VanishCommand.isVanished(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ToggleIgnoreResult toggleIgnoringRequests(Player player) {
|
|
||||||
UUID uuid = player.getUniqueId();
|
UUID uuid = player.getUniqueId();
|
||||||
boolean nowIgnoring;
|
boolean nowIgnoring;
|
||||||
if (ignoringRequests.contains(uuid)) {
|
if (ignoringRequests.contains(uuid)) {
|
||||||
@@ -345,64 +296,69 @@ 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) {
|
||||||
playConfiguredSound(player, requestSound, 1.0F, 1.0F);
|
playConfiguredSound(player, requestSound, 0.7F, 1.0F);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int sendTeleportAllRequest(Player requester) {
|
public int sendTeleportAllRequest(Player requester) {
|
||||||
|
return sendTeleportAllRequest(requester, ignored -> true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int sendTeleportAllRequest(Player requester, Predicate<Player> targetFilter) {
|
||||||
|
OptionalIntCooldown sendCooldown = getRemainingCooldown(requester, sendCooldowns);
|
||||||
|
if (sendCooldown.active()) {
|
||||||
|
return -sendCooldown.seconds();
|
||||||
|
}
|
||||||
|
|
||||||
int recipients = 0;
|
int recipients = 0;
|
||||||
for (Player target : Bukkit.getOnlinePlayers()) {
|
for (Player target : Bukkit.getOnlinePlayers()) {
|
||||||
if (target.getUniqueId().equals(requester.getUniqueId())) {
|
if (target.getUniqueId().equals(requester.getUniqueId())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (!targetFilter.test(target)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
recipients++;
|
recipients++;
|
||||||
CreateRequestResult result = createRequest(requester, target, TeleportRequest.Type.TPAHERE, false);
|
CreateRequestResult result = createRequest(requester, target, TeleportRequest.Type.TPAHERE, false);
|
||||||
if (result.status() != CreateRequestStatus.SUCCESS) {
|
if (result.status() != CreateRequestStatus.SUCCESS) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Map<String, String> placeholders = placeholders(result.request());
|
Map<String, String> placeholders = placeholders(result.request());
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.received-tpahere", placeholders));
|
target.sendMessage(plugin.getLangManager().getPrefixedString("tpa.messages.received-tpahere", placeholders));
|
||||||
sendResponseHint(target, placeholders);
|
sendResponseHint(target, result.request(), placeholders);
|
||||||
playRequestReceivedSound(target);
|
playRequestReceivedSound(target);
|
||||||
}
|
}
|
||||||
|
if (recipients > 0) {
|
||||||
|
startCooldown(requester, sendCooldowns, sendCooldownSeconds);
|
||||||
|
}
|
||||||
return recipients;
|
return recipients;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getRemainingSendCooldownSeconds(Player player) {
|
public int getSendCooldownSeconds(Player player) {
|
||||||
return getRemainingCooldown(player, sendCooldowns).seconds();
|
return getRemainingCooldown(player, sendCooldowns).seconds();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<Player> findOnlinePlayer(String playerName, Predicate<Player> filter) {
|
private void sendResponseHint(Player target, TeleportRequest request, Map<String, String> placeholders) {
|
||||||
Optional<Player> exactMatch = Bukkit.getOnlinePlayers().stream()
|
String requesterName = request.requesterName();
|
||||||
.map(Player.class::cast)
|
String acceptCommand = "/tpaccept " + requesterName;
|
||||||
.filter(filter)
|
String denyCommand = "/tpdeny " + requesterName;
|
||||||
.filter(player -> player.getName().equalsIgnoreCase(playerName))
|
|
||||||
.findFirst();
|
|
||||||
if (exactMatch.isPresent()) {
|
|
||||||
return exactMatch;
|
|
||||||
}
|
|
||||||
|
|
||||||
String playerNameLower = playerName.toLowerCase(Locale.ROOT);
|
Component hint = LegacyComponentSerializer.legacySection()
|
||||||
return Bukkit.getOnlinePlayers().stream()
|
.deserialize(plugin.getLangManager().getPrefixedString("tpa.messages.response-hint", placeholders));
|
||||||
.map(Player.class::cast)
|
Component accept = LegacyComponentSerializer.legacySection()
|
||||||
.filter(filter)
|
.deserialize(plugin.getLangManager().getString("tpa.messages.accept-button"))
|
||||||
.filter(player -> player.getName().toLowerCase(Locale.ROOT).startsWith(playerNameLower))
|
.clickEvent(ClickEvent.runCommand(acceptCommand))
|
||||||
.findFirst();
|
.hoverEvent(HoverEvent.showText(Component.text(acceptCommand, NamedTextColor.GREEN)));
|
||||||
}
|
Component deny = LegacyComponentSerializer.legacySection()
|
||||||
|
.deserialize(plugin.getLangManager().getString("tpa.messages.deny-button"))
|
||||||
|
.clickEvent(ClickEvent.runCommand(denyCommand))
|
||||||
|
.hoverEvent(HoverEvent.showText(Component.text(denyCommand, NamedTextColor.RED)));
|
||||||
|
|
||||||
public void sendResponseHint(Player target, Map<String, String> placeholders) {
|
target.sendMessage(hint.append(Component.space()).append(accept).append(Component.space()).append(deny));
|
||||||
target.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.response-buttons", placeholders));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getTimeoutSeconds() {
|
public int getTimeoutSeconds() {
|
||||||
@@ -440,58 +396,29 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return new TeleportPlan(
|
return new TeleportPlan(
|
||||||
requester,
|
requester,
|
||||||
strictTpaRequests ? currentTarget.getLocation().clone() : null,
|
strictTpaRequests ? currentTarget.getLocation().clone() : null,
|
||||||
strictTpaRequests ? null : currentTarget.getUniqueId(),
|
strictTpaRequests ? null : currentTarget.getUniqueId()
|
||||||
request
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return new TeleportPlan(
|
return new TeleportPlan(
|
||||||
currentTarget,
|
currentTarget,
|
||||||
strictTpaHereRequests ? request.requesterLocation().clone() : null,
|
strictTpaHereRequests ? request.requesterLocation().clone() : null,
|
||||||
strictTpaHereRequests ? null : requester.getUniqueId(),
|
strictTpaHereRequests ? null : requester.getUniqueId()
|
||||||
request
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getTeleportWarmupSeconds(Player player) {
|
private void startWarmup(TeleportPlan plan) {
|
||||||
return player.getEffectivePermissions().stream()
|
|
||||||
.filter(PermissionAttachmentInfo::getValue)
|
|
||||||
.map(PermissionAttachmentInfo::getPermission)
|
|
||||||
.filter(permission -> permission.startsWith(WARMUP_PERMISSION_PREFIX))
|
|
||||||
.map(permission -> permission.substring(WARMUP_PERMISSION_PREFIX.length()))
|
|
||||||
.mapToInt(this::parseWarmupPermission)
|
|
||||||
.filter(seconds -> seconds >= 0)
|
|
||||||
.max()
|
|
||||||
.orElse(warmupSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int parseWarmupPermission(String value) {
|
|
||||||
try {
|
|
||||||
return Integer.parseInt(value);
|
|
||||||
} catch (NumberFormatException ignored) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean startWarmup(TeleportPlan plan, int playerWarmupSeconds) {
|
|
||||||
Player teleporter = plan.teleporter();
|
Player teleporter = plan.teleporter();
|
||||||
UUID uuid = teleporter.getUniqueId();
|
UUID uuid = teleporter.getUniqueId();
|
||||||
TeleportWarmupEvent warmupEvent = new TeleportWarmupEvent(teleporter, plan.request(), playerWarmupSeconds);
|
|
||||||
Bukkit.getPluginManager().callEvent(warmupEvent);
|
|
||||||
if (warmupEvent.isCancelled()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
PendingTeleport pendingTeleport = new PendingTeleport(
|
PendingTeleport pendingTeleport = new PendingTeleport(
|
||||||
plan,
|
plan,
|
||||||
teleporter.getLocation().clone(),
|
teleporter.getLocation().clone(),
|
||||||
playerWarmupSeconds
|
warmupSeconds
|
||||||
);
|
);
|
||||||
warmupDamagedPlayers.remove(uuid);
|
|
||||||
BukkitTask task = Bukkit.getScheduler().runTaskTimer(plugin, () -> tickWarmup(uuid), 0L, 20L);
|
BukkitTask task = Bukkit.getScheduler().runTaskTimer(plugin, () -> tickWarmup(uuid), 0L, 20L);
|
||||||
pendingTeleport.setTask(task);
|
pendingTeleport.setTask(task);
|
||||||
warmups.put(uuid, pendingTeleport);
|
warmups.put(uuid, pendingTeleport);
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.warmup-start",
|
teleporter.sendMessage(plugin.getLangManager().getPrefixedString("tpa.messages.warmup-start",
|
||||||
Map.of("seconds", String.valueOf(playerWarmupSeconds))));
|
Map.of("seconds", String.valueOf(warmupSeconds))));
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void tickWarmup(UUID teleporterId) {
|
private void tickWarmup(UUID teleporterId) {
|
||||||
@@ -502,34 +429,21 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
|
|
||||||
Player teleporter = Bukkit.getPlayer(teleporterId);
|
Player teleporter = Bukkit.getPlayer(teleporterId);
|
||||||
if (teleporter == null || !teleporter.isOnline()) {
|
if (teleporter == null || !teleporter.isOnline()) {
|
||||||
cancelWarmup(teleporterId, null, false, TeleportWarmupCancelledEvent.Reason.PLAYER_QUIT);
|
cancelWarmup(teleporterId, null, false);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cancelWarmupOnDamage && warmupDamagedPlayers.contains(teleporterId)) {
|
|
||||||
cancelWarmup(teleporterId, "tpa.messages.warmup-cancelled-damage", true,
|
|
||||||
TeleportWarmupCancelledEvent.Reason.PLAYER_DAMAGE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (cancelWarmupOnMove && hasMoved(pendingTeleport.startLocation(), teleporter.getLocation())) {
|
|
||||||
cancelWarmup(teleporterId, "tpa.messages.warmup-cancelled-move", true,
|
|
||||||
TeleportWarmupCancelledEvent.Reason.PLAYER_MOVE);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pendingTeleport.remainingSeconds() <= 0) {
|
if (pendingTeleport.remainingSeconds() <= 0) {
|
||||||
sendWarmupStatus(teleporter, "tpa.messages.warmup-processing", Map.of());
|
|
||||||
cancelWarmup(teleporterId, null, false);
|
cancelWarmup(teleporterId, null, false);
|
||||||
TeleportResult result = executeTeleport(pendingTeleport.plan(), true);
|
TeleportResult result = executeTeleport(pendingTeleport.plan(), true);
|
||||||
if (result.status() == TeleportResult.Status.ON_COOLDOWN) {
|
if (result.status() == TeleportResult.Status.PLAYER_OFFLINE) {
|
||||||
sendAcceptCooldown(teleporter, result.cooldownSeconds());
|
teleporter.sendMessage(plugin.getLangManager().getPrefixedString("tpa.messages.player-offline"));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
sendWarmupStatus(teleporter, "tpa.messages.warmup-status",
|
sendWarmupStatus(teleporter, pendingTeleport.remainingSeconds());
|
||||||
Map.of("seconds", String.valueOf(pendingTeleport.remainingSeconds())));
|
playConfiguredSound(teleporter, warmupSound, 0.5F, 1.0F);
|
||||||
playConfiguredSound(teleporter, warmupSound, 1.0F, 1.0F);
|
|
||||||
pendingTeleport.decrementRemainingSeconds();
|
pendingTeleport.decrementRemainingSeconds();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -539,155 +453,47 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return TeleportResult.PLAYER_OFFLINE;
|
return TeleportResult.PLAYER_OFFLINE;
|
||||||
}
|
}
|
||||||
|
|
||||||
OptionalIntCooldown acceptCooldown = getRemainingCooldown(teleporter, acceptCooldowns);
|
|
||||||
if (acceptCooldown.active()) {
|
|
||||||
return TeleportResult.onCooldown(acceptCooldown.seconds());
|
|
||||||
}
|
|
||||||
|
|
||||||
Location destination = plan.fixedDestination();
|
Location destination = plan.fixedDestination();
|
||||||
if (destination == null && plan.dynamicTargetId() != null) {
|
if (destination == null && plan.dynamicTargetId() != null) {
|
||||||
Player dynamicTarget = Bukkit.getPlayer(plan.dynamicTargetId());
|
Player dynamicTarget = Bukkit.getPlayer(plan.dynamicTargetId());
|
||||||
if (dynamicTarget == null || !dynamicTarget.isOnline()) {
|
if (dynamicTarget == null || !dynamicTarget.isOnline()) {
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.target-offline"));
|
return TeleportResult.PLAYER_OFFLINE;
|
||||||
return TeleportResult.TARGET_OFFLINE;
|
|
||||||
}
|
}
|
||||||
destination = dynamicTarget.getLocation().clone();
|
destination = dynamicTarget.getLocation().clone();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (destination == null) {
|
if (destination == null) {
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.target-offline"));
|
return TeleportResult.PLAYER_OFFLINE;
|
||||||
return TeleportResult.TARGET_OFFLINE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TeleportEvent teleportEvent = new TeleportEvent(teleporter, plan.request(), destination);
|
teleporter.teleportAsync(destination).thenAccept(success -> {
|
||||||
Bukkit.getPluginManager().callEvent(teleportEvent);
|
if (!success || !notifyCompletion) {
|
||||||
if (teleportEvent.isCancelled()) {
|
|
||||||
return TeleportResult.CANCELLED;
|
|
||||||
}
|
|
||||||
destination = teleportEvent.getDestination();
|
|
||||||
|
|
||||||
teleporter.leaveVehicle();
|
|
||||||
teleporter.eject();
|
|
||||||
teleporter.setFallDistance(0.0F);
|
|
||||||
startCooldown(teleporter, acceptCooldowns, acceptCooldownSeconds);
|
|
||||||
if (teleportAsync) {
|
|
||||||
try {
|
|
||||||
teleporter.teleportAsync(destination, PlayerTeleportEvent.TeleportCause.PLUGIN)
|
|
||||||
.whenComplete((success, throwable) -> {
|
|
||||||
if (!plugin.isEnabled()) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Bukkit.getScheduler().runTask(plugin, () -> handleTeleportCompletion(
|
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||||
teleporter, Boolean.TRUE.equals(success), throwable, notifyCompletion));
|
if (teleporter.isOnline()) {
|
||||||
|
teleporter.sendMessage(plugin.getLangManager().getPrefixedString("tpa.messages.teleport-complete"));
|
||||||
|
playConfiguredSound(teleporter, completeSound, 0.7F, 1.0F);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
handleTeleportCompletion(teleporter, false, exception, notifyCompletion);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
boolean success = teleporter.teleport(destination, PlayerTeleportEvent.TeleportCause.PLUGIN);
|
|
||||||
handleTeleportCompletion(teleporter, success, null, notifyCompletion);
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
handleTeleportCompletion(teleporter, false, exception, notifyCompletion);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return TeleportResult.SUCCESS;
|
return TeleportResult.SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleTeleportCompletion(Player teleporter, boolean success, Throwable throwable,
|
private void sendWarmupStatus(Player player, int seconds) {
|
||||||
boolean notifyCompletion) {
|
String message = plugin.getLangManager().getString("tpa.messages.warmup-status",
|
||||||
if (!success) {
|
Map.of("seconds", String.valueOf(seconds)));
|
||||||
if (teleporter.isOnline()) {
|
if ("actionbar".equalsIgnoreCase(warmupDisplay)) {
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.teleport-failed"));
|
player.sendActionBar(LegacyComponentSerializer.legacySection().deserialize(message));
|
||||||
}
|
|
||||||
if (throwable != null) {
|
|
||||||
String detail = throwable.getMessage() == null
|
|
||||||
? throwable.getClass().getSimpleName()
|
|
||||||
: throwable.getMessage();
|
|
||||||
plugin.getLogger().warning("TPA 传送执行失败: " + detail);
|
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!"none".equalsIgnoreCase(warmupDisplay)) {
|
||||||
applyTeleportInvulnerability(teleporter);
|
player.sendMessage(message);
|
||||||
if (notifyCompletion && teleporter.isOnline()) {
|
|
||||||
teleporter.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.teleport-complete"));
|
|
||||||
playConfiguredSound(teleporter, completeSound, 1.0F, 1.0F);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyTeleportInvulnerability(Player player) {
|
|
||||||
if (teleportInvulnerabilitySeconds <= 0 || !player.isOnline()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
UUID uuid = player.getUniqueId();
|
|
||||||
BukkitTask previousTask = invulnerabilityTasks.remove(uuid);
|
|
||||||
if (previousTask != null) {
|
|
||||||
previousTask.cancel();
|
|
||||||
}
|
|
||||||
if (player.isInvulnerable() && !invulnerablePlayers.contains(uuid)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
invulnerablePlayers.add(uuid);
|
|
||||||
player.setInvulnerable(true);
|
|
||||||
BukkitTask task = Bukkit.getScheduler().runTaskLater(plugin,
|
|
||||||
() -> clearInvulnerability(uuid), teleportInvulnerabilitySeconds * 20L);
|
|
||||||
invulnerabilityTasks.put(uuid, task);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearInvulnerability(UUID uuid) {
|
|
||||||
BukkitTask task = invulnerabilityTasks.remove(uuid);
|
|
||||||
if (task != null) {
|
|
||||||
task.cancel();
|
|
||||||
}
|
|
||||||
if (!invulnerablePlayers.remove(uuid)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Player player = Bukkit.getPlayer(uuid);
|
|
||||||
if (player != null) {
|
|
||||||
player.setInvulnerable(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void clearAllInvulnerability() {
|
|
||||||
for (BukkitTask task : invulnerabilityTasks.values()) {
|
|
||||||
task.cancel();
|
|
||||||
}
|
|
||||||
invulnerabilityTasks.clear();
|
|
||||||
for (UUID uuid : new HashSet<>(invulnerablePlayers)) {
|
|
||||||
clearInvulnerability(uuid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendAcceptCooldown(Player player, int seconds) {
|
|
||||||
player.sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.accept-cooldown",
|
|
||||||
Map.of("seconds", String.valueOf(seconds))));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendWarmupStatus(Player player, String messagePath, Map<String, String> placeholders) {
|
|
||||||
net.kyori.adventure.text.Component message = plugin.getLangManager().getPrefixedComponent(messagePath, placeholders);
|
|
||||||
switch (warmupDisplay.replace("-", "_")) {
|
|
||||||
case "actionbar", "action_bar" -> player.sendActionBar(message);
|
|
||||||
case "title" -> player.showTitle(Title.title(message, net.kyori.adventure.text.Component.empty(),
|
|
||||||
Title.Times.times(Duration.ZERO, Duration.ofSeconds(1), Duration.ofMillis(250))));
|
|
||||||
case "subtitle" -> player.showTitle(Title.title(net.kyori.adventure.text.Component.empty(), message,
|
|
||||||
Title.Times.times(Duration.ZERO, Duration.ofSeconds(1), Duration.ofMillis(250))));
|
|
||||||
case "none" -> {
|
|
||||||
}
|
|
||||||
default -> player.sendMessage(message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void cancelWarmup(UUID teleporterId, String messagePath, boolean playSound) {
|
private void cancelWarmup(UUID teleporterId, String messagePath, boolean playSound) {
|
||||||
cancelWarmup(teleporterId, messagePath, playSound, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void cancelWarmup(UUID teleporterId, String messagePath, boolean playSound,
|
|
||||||
TeleportWarmupCancelledEvent.Reason reason) {
|
|
||||||
PendingTeleport pendingTeleport = warmups.remove(teleporterId);
|
PendingTeleport pendingTeleport = warmups.remove(teleporterId);
|
||||||
warmupDamagedPlayers.remove(teleporterId);
|
|
||||||
if (pendingTeleport == null) {
|
if (pendingTeleport == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -697,24 +503,17 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
|
|
||||||
Player player = Bukkit.getPlayer(teleporterId);
|
Player player = Bukkit.getPlayer(teleporterId);
|
||||||
if (player != null && player.isOnline() && messagePath != null) {
|
if (player != null && player.isOnline() && messagePath != null) {
|
||||||
player.sendMessage(plugin.getLangManager().getPrefixedComponent(messagePath));
|
player.sendMessage(plugin.getLangManager().getPrefixedString(messagePath));
|
||||||
sendWarmupStatus(player, "tpa.messages.warmup-cancelled-actionbar", Map.of());
|
|
||||||
if (playSound) {
|
if (playSound) {
|
||||||
playConfiguredSound(player, cancelSound, 1.0F, 1.0F);
|
playConfiguredSound(player, cancelSound, 0.7F, 1.0F);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (player != null && reason != null) {
|
|
||||||
int duration = pendingTeleport.initialSeconds();
|
|
||||||
Bukkit.getPluginManager().callEvent(new TeleportWarmupCancelledEvent(
|
|
||||||
player, pendingTeleport.plan().request(), duration,
|
|
||||||
Math.max(0, duration - pendingTeleport.remainingSeconds()), reason));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void cancelAllWarmups() {
|
private void cancelAllWarmups() {
|
||||||
List<UUID> warmingPlayers = new ArrayList<>(warmups.keySet());
|
List<UUID> warmingPlayers = new ArrayList<>(warmups.keySet());
|
||||||
for (UUID warmingPlayer : warmingPlayers) {
|
for (UUID warmingPlayer : warmingPlayers) {
|
||||||
cancelWarmup(warmingPlayer, null, false, TeleportWarmupCancelledEvent.Reason.PLUGIN_SHUTDOWN);
|
cancelWarmup(warmingPlayer, null, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -743,22 +542,52 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void purgeExpired() {
|
||||||
|
List<UUID> emptyQueues = new ArrayList<>();
|
||||||
|
for (Map.Entry<UUID, Deque<TeleportRequest>> entry : requests.entrySet()) {
|
||||||
|
entry.getValue().removeIf(TeleportRequest::hasExpired);
|
||||||
|
if (entry.getValue().isEmpty()) {
|
||||||
|
emptyQueues.add(entry.getKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emptyQueues.forEach(requests::remove);
|
||||||
|
}
|
||||||
|
|
||||||
public Map<String, String> placeholders(TeleportRequest request) {
|
public Map<String, String> placeholders(TeleportRequest request) {
|
||||||
Map<String, String> placeholders = new HashMap<>();
|
Map<String, String> placeholders = new HashMap<>();
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||||
private void onEntityDamage(EntityDamageEvent event) {
|
private void onPlayerMove(PlayerMoveEvent event) {
|
||||||
if (event.getDamage() <= 0) {
|
if (!cancelWarmupOnMove || !warmups.containsKey(event.getPlayer().getUniqueId())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (event.getEntity() instanceof Player player && warmups.containsKey(player.getUniqueId())) {
|
|
||||||
warmupDamagedPlayers.add(player.getUniqueId());
|
PendingTeleport pendingTeleport = warmups.get(event.getPlayer().getUniqueId());
|
||||||
|
Location start = pendingTeleport.startLocation();
|
||||||
|
Location to = event.getTo();
|
||||||
|
if (to == null || !sameWorld(start, to)) {
|
||||||
|
cancelWarmup(event.getPlayer().getUniqueId(), "tpa.messages.warmup-cancelled-move", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
double distance = Math.abs(start.getX() - to.getX())
|
||||||
|
+ Math.abs(start.getY() - to.getY())
|
||||||
|
+ Math.abs(start.getZ() - to.getZ());
|
||||||
|
if (distance > warmupMoveThreshold) {
|
||||||
|
cancelWarmup(event.getPlayer().getUniqueId(), "tpa.messages.warmup-cancelled-move", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||||
|
private void onEntityDamage(EntityDamageEvent event) {
|
||||||
|
if (cancelWarmupOnDamage && event.getEntity() instanceof Player player && warmups.containsKey(player.getUniqueId())) {
|
||||||
|
cancelWarmup(player.getUniqueId(), "tpa.messages.warmup-cancelled-damage", true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -768,66 +597,75 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
event.getPlayer().sendMessage(plugin.getLangManager().getPrefixedComponent("tpa.messages.ignore-notification"));
|
event.getPlayer().sendMessage(plugin.getLangManager().getPrefixedString("tpa.messages.ignore-notification"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler
|
@EventHandler
|
||||||
private void onPlayerQuit(PlayerQuitEvent event) {
|
private void onPlayerQuit(PlayerQuitEvent event) {
|
||||||
UUID uuid = event.getPlayer().getUniqueId();
|
cancelWarmup(event.getPlayer().getUniqueId(), null, false);
|
||||||
cancelWarmup(uuid, null, false, TeleportWarmupCancelledEvent.Reason.PLAYER_QUIT);
|
|
||||||
clearInvulnerability(uuid);
|
|
||||||
requests.remove(uuid);
|
|
||||||
requests.values().removeIf(targetRequests -> {
|
|
||||||
targetRequests.removeIf(request -> request.requesterId().equals(uuid));
|
|
||||||
return targetRequests.isEmpty();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean hasMoved(Location start, Location current) {
|
private void startCleanupTask() {
|
||||||
if (start.getWorld() == null || current.getWorld() == null
|
if (cleanupTask != null) {
|
||||||
|| !start.getWorld().getUID().equals(current.getWorld().getUID())) {
|
return;
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
double distance = Math.abs(start.getX() - current.getX())
|
cleanupTask = Bukkit.getScheduler().runTaskTimer(plugin, this::purgeExpired, 20L * 60L, 20L * 60L);
|
||||||
+ Math.abs(start.getY() - current.getY())
|
|
||||||
+ Math.abs(start.getZ() - current.getZ());
|
|
||||||
return distance > MOVEMENT_THRESHOLD;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isMoving(Player player) {
|
private void cancelCleanupTask() {
|
||||||
return player.getVelocity().length() >= MOVEMENT_THRESHOLD;
|
if (cleanupTask == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cleanupTask.cancel();
|
||||||
|
cleanupTask = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void pruneExpiredRequests(Deque<TeleportRequest> targetRequests) {
|
private boolean sameWorld(Location first, Location second) {
|
||||||
long retentionMillis = Math.max(60_000L, timeoutSeconds * 1000L);
|
return first.getWorld() != null
|
||||||
long now = System.currentTimeMillis();
|
&& second.getWorld() != null
|
||||||
targetRequests.removeIf(request -> TeleportRequestQueuePolicy.shouldPrune(
|
&& first.getWorld().getUID().equals(second.getWorld().getUID());
|
||||||
request.expiresAtMillis(), now, retentionMillis));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void cleanupExpiredState() {
|
private void loadIgnoringRequests() {
|
||||||
requests.entrySet().removeIf(entry -> {
|
ignoringRequests.clear();
|
||||||
pruneExpiredRequests(entry.getValue());
|
if (!ignoreFile.exists()) {
|
||||||
return entry.getValue().isEmpty();
|
return;
|
||||||
});
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
sendCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
|
||||||
acceptCooldowns.values().removeIf(expiresAt -> expiresAt <= now);
|
|
||||||
stateStore.saveCooldowns(sendCooldowns, acceptCooldowns);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum ToggleIgnoreResult {
|
FileConfiguration ignoreConfig = YamlConfiguration.loadConfiguration(ignoreFile);
|
||||||
ENABLED,
|
if (!ignoreConfig.isConfigurationSection("ignored")) {
|
||||||
DISABLED,
|
return;
|
||||||
SAVE_FAILED
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
ignoreConfig.save(ignoreFile);
|
||||||
|
} catch (IOException e) {
|
||||||
|
plugin.getLogger().warning("保存 teleport-ignore.yml 失败: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum CreateRequestStatus {
|
public enum CreateRequestStatus {
|
||||||
SUCCESS,
|
SUCCESS,
|
||||||
DUPLICATE,
|
DUPLICATE,
|
||||||
IGNORED,
|
IGNORED,
|
||||||
ON_COOLDOWN,
|
ON_COOLDOWN
|
||||||
CANCELLED
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public record TeleportResult(Status status, int cooldownSeconds) {
|
public record TeleportResult(Status status, int cooldownSeconds) {
|
||||||
@@ -835,10 +673,7 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
public static final TeleportResult WARMING_UP = new TeleportResult(Status.WARMING_UP, 0);
|
public static final TeleportResult WARMING_UP = new TeleportResult(Status.WARMING_UP, 0);
|
||||||
public static final TeleportResult EXPIRED = new TeleportResult(Status.EXPIRED, 0);
|
public static final TeleportResult EXPIRED = new TeleportResult(Status.EXPIRED, 0);
|
||||||
public static final TeleportResult PLAYER_OFFLINE = new TeleportResult(Status.PLAYER_OFFLINE, 0);
|
public static final TeleportResult PLAYER_OFFLINE = new TeleportResult(Status.PLAYER_OFFLINE, 0);
|
||||||
public static final TeleportResult TARGET_OFFLINE = new TeleportResult(Status.TARGET_OFFLINE, 0);
|
|
||||||
public static final TeleportResult ALREADY_WARMING_UP = new TeleportResult(Status.ALREADY_WARMING_UP, 0);
|
public static final TeleportResult ALREADY_WARMING_UP = new TeleportResult(Status.ALREADY_WARMING_UP, 0);
|
||||||
public static final TeleportResult ACCEPTED_WITHOUT_TELEPORT = new TeleportResult(Status.ACCEPTED_WITHOUT_TELEPORT, 0);
|
|
||||||
public static final TeleportResult CANCELLED = new TeleportResult(Status.CANCELLED, 0);
|
|
||||||
|
|
||||||
public static TeleportResult onCooldown(int seconds) {
|
public static TeleportResult onCooldown(int seconds) {
|
||||||
return new TeleportResult(Status.ON_COOLDOWN, seconds);
|
return new TeleportResult(Status.ON_COOLDOWN, seconds);
|
||||||
@@ -849,11 +684,8 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
WARMING_UP,
|
WARMING_UP,
|
||||||
EXPIRED,
|
EXPIRED,
|
||||||
PLAYER_OFFLINE,
|
PLAYER_OFFLINE,
|
||||||
TARGET_OFFLINE,
|
|
||||||
ALREADY_WARMING_UP,
|
ALREADY_WARMING_UP,
|
||||||
ACCEPTED_WITHOUT_TELEPORT,
|
ON_COOLDOWN
|
||||||
ON_COOLDOWN,
|
|
||||||
CANCELLED
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -945,8 +777,7 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record TeleportPlan(Player teleporter, Location fixedDestination, UUID dynamicTargetId,
|
private record TeleportPlan(Player teleporter, Location fixedDestination, UUID dynamicTargetId) {
|
||||||
TeleportRequest request) {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private record OptionalIntCooldown(boolean active, int seconds) {
|
private record OptionalIntCooldown(boolean active, int seconds) {
|
||||||
@@ -958,14 +789,12 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
private static final class PendingTeleport {
|
private static final class PendingTeleport {
|
||||||
private final TeleportPlan plan;
|
private final TeleportPlan plan;
|
||||||
private final Location startLocation;
|
private final Location startLocation;
|
||||||
private final int initialSeconds;
|
|
||||||
private int remainingSeconds;
|
private int remainingSeconds;
|
||||||
private BukkitTask task;
|
private BukkitTask task;
|
||||||
|
|
||||||
private PendingTeleport(TeleportPlan plan, Location startLocation, int remainingSeconds) {
|
private PendingTeleport(TeleportPlan plan, Location startLocation, int remainingSeconds) {
|
||||||
this.plan = plan;
|
this.plan = plan;
|
||||||
this.startLocation = startLocation;
|
this.startLocation = startLocation;
|
||||||
this.initialSeconds = remainingSeconds;
|
|
||||||
this.remainingSeconds = remainingSeconds;
|
this.remainingSeconds = remainingSeconds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -981,10 +810,6 @@ public final class TeleportRequestManager implements Listener {
|
|||||||
return remainingSeconds;
|
return remainingSeconds;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int initialSeconds() {
|
|
||||||
return initialSeconds;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void decrementRemainingSeconds() {
|
private void decrementRemainingSeconds() {
|
||||||
remainingSeconds--;
|
remainingSeconds--;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.teleport;
|
|
||||||
|
|
||||||
import java.util.Deque;
|
|
||||||
|
|
||||||
final class TeleportRequestQueuePolicy {
|
|
||||||
|
|
||||||
private TeleportRequestQueuePolicy() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static <T> void addFirstBounded(Deque<T> queue, T value, int maximumSize) {
|
|
||||||
while (queue.size() >= maximumSize) {
|
|
||||||
queue.removeLast();
|
|
||||||
}
|
|
||||||
queue.addFirst(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean shouldPrune(long expiresAtMillis, long nowMillis, long retentionMillis) {
|
|
||||||
return expiresAtMillis <= nowMillis - retentionMillis;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,14 +1,13 @@
|
|||||||
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;
|
||||||
import org.bukkit.command.CommandMap;
|
import org.bukkit.command.CommandMap;
|
||||||
import org.bukkit.command.PluginIdentifiableCommand;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.entity.Entity;
|
import org.bukkit.entity.Entity;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@@ -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;
|
||||||
@@ -44,9 +41,9 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
private final Map<UUID, BossBar> activeBars = new java.util.HashMap<>();
|
private final Map<UUID, BossBar> activeBars = new java.util.HashMap<>();
|
||||||
|
|
||||||
private BukkitTask updateTask;
|
private BukkitTask updateTask;
|
||||||
|
private Mode mode;
|
||||||
private boolean pluginCommandEnabled;
|
private boolean pluginCommandEnabled;
|
||||||
private boolean nativeCommandAvailable;
|
private boolean nativeCommandAvailable;
|
||||||
private boolean nativeDetectionInitialized;
|
|
||||||
private String titleFormat;
|
private String titleFormat;
|
||||||
private String enabledSelfMessage;
|
private String enabledSelfMessage;
|
||||||
private String disabledSelfMessage;
|
private String disabledSelfMessage;
|
||||||
@@ -57,9 +54,12 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
private String noTargetsMessage;
|
private String noTargetsMessage;
|
||||||
private String nativeDetectedMessage;
|
private String nativeDetectedMessage;
|
||||||
private String pluginEnabledMessage;
|
private String pluginEnabledMessage;
|
||||||
|
private String pluginForcedButNativeExistsMessage;
|
||||||
|
private String modeChangedReloadMessage;
|
||||||
|
|
||||||
public TpsBarManager(EssentialsC plugin) {
|
public TpsBarManager(EssentialsC plugin) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
addConfigDefaults();
|
||||||
reloadSettings();
|
reloadSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,8 +75,11 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void reloadSettings() {
|
public void reloadSettings() {
|
||||||
|
FileConfiguration config = plugin.getConfig();
|
||||||
var lang = EssentialsC.getLangManager();
|
var lang = EssentialsC.getLangManager();
|
||||||
|
Mode previousMode = this.mode;
|
||||||
|
|
||||||
|
this.mode = Mode.fromString(config.getString("tpsbar.mode", "auto"));
|
||||||
this.titleFormat = lang.getString("tpsbar.title-format");
|
this.titleFormat = lang.getString("tpsbar.title-format");
|
||||||
this.enabledSelfMessage = lang.getString("tpsbar.messages.enabled-self");
|
this.enabledSelfMessage = lang.getString("tpsbar.messages.enabled-self");
|
||||||
this.disabledSelfMessage = lang.getString("tpsbar.messages.disabled-self");
|
this.disabledSelfMessage = lang.getString("tpsbar.messages.disabled-self");
|
||||||
@@ -87,15 +90,26 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
this.noTargetsMessage = lang.getString("tpsbar.messages.no-targets");
|
this.noTargetsMessage = lang.getString("tpsbar.messages.no-targets");
|
||||||
this.nativeDetectedMessage = lang.getString("tpsbar.messages.native-detected");
|
this.nativeDetectedMessage = lang.getString("tpsbar.messages.native-detected");
|
||||||
this.pluginEnabledMessage = lang.getString("tpsbar.messages.plugin-enabled");
|
this.pluginEnabledMessage = lang.getString("tpsbar.messages.plugin-enabled");
|
||||||
|
this.pluginForcedButNativeExistsMessage = lang.getString("tpsbar.messages.plugin-forced-but-native-exists");
|
||||||
|
this.modeChangedReloadMessage = lang.getString("tpsbar.messages.mode-changed-reload");
|
||||||
|
|
||||||
if (!nativeDetectionInitialized) {
|
|
||||||
this.nativeCommandAvailable = detectNativeTpsBar();
|
this.nativeCommandAvailable = detectNativeTpsBar();
|
||||||
this.nativeDetectionInitialized = true;
|
this.pluginCommandEnabled = switch (mode) {
|
||||||
|
case OFF -> false;
|
||||||
|
case AUTO -> !nativeCommandAvailable;
|
||||||
|
case ON -> !nativeCommandAvailable;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (previousMode != null && previousMode != mode) {
|
||||||
|
plugin.getLogger().info(stripColor(modeChangedReloadMessage));
|
||||||
}
|
}
|
||||||
this.pluginCommandEnabled = !nativeCommandAvailable;
|
|
||||||
|
|
||||||
if (nativeCommandAvailable) {
|
if (nativeCommandAvailable) {
|
||||||
|
if (mode == Mode.AUTO) {
|
||||||
plugin.getLogger().info(stripColor(nativeDetectedMessage));
|
plugin.getLogger().info(stripColor(nativeDetectedMessage));
|
||||||
|
} else if (mode == Mode.ON) {
|
||||||
|
plugin.getLogger().warning(stripColor(pluginForcedButNativeExistsMessage));
|
||||||
|
}
|
||||||
} else if (pluginCommandEnabled) {
|
} else if (pluginCommandEnabled) {
|
||||||
plugin.getLogger().info(stripColor(pluginEnabledMessage));
|
plugin.getLogger().info(stripColor(pluginEnabledMessage));
|
||||||
}
|
}
|
||||||
@@ -285,11 +299,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) {
|
||||||
@@ -306,21 +320,21 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
try {
|
try {
|
||||||
CommandMap commandMap = Bukkit.getCommandMap();
|
CommandMap commandMap = Bukkit.getCommandMap();
|
||||||
org.bukkit.command.Command command = commandMap.getCommand("tpsbar");
|
org.bukkit.command.Command command = commandMap.getCommand("tpsbar");
|
||||||
if (command == null) {
|
return command != null;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (command instanceof PluginIdentifiableCommand pluginCommand
|
|
||||||
&& pluginCommand.getPlugin().equals(plugin)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return !command.getClass().getName().startsWith("cn.infstar.essentialsC.");
|
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void addConfigDefaults() {
|
||||||
|
FileConfiguration config = plugin.getConfig();
|
||||||
|
config.addDefault("tpsbar.mode", "auto");
|
||||||
|
config.options().copyDefaults(true);
|
||||||
|
plugin.saveConfig();
|
||||||
|
}
|
||||||
|
|
||||||
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 +346,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) {
|
||||||
@@ -357,4 +371,20 @@ public final class TpsBarManager implements Listener, TpsBarService {
|
|||||||
return Math.max(min, Math.min(max, value));
|
return Math.max(min, Math.min(max, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private enum Mode {
|
||||||
|
OFF,
|
||||||
|
AUTO,
|
||||||
|
ON;
|
||||||
|
|
||||||
|
private static Mode fromString(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return AUTO;
|
||||||
|
}
|
||||||
|
return switch (value.toLowerCase(Locale.ROOT)) {
|
||||||
|
case "off", "false", "disabled" -> OFF;
|
||||||
|
case "on", "enabled", "plugin" -> ON;
|
||||||
|
default -> AUTO;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.util;
|
|
||||||
|
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.AtomicMoveNotSupportedException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
|
|
||||||
public final class AtomicYamlWriter {
|
|
||||||
|
|
||||||
private AtomicYamlWriter() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void save(FileConfiguration configuration, File targetFile) throws IOException {
|
|
||||||
Path target = targetFile.toPath().toAbsolutePath();
|
|
||||||
Path parent = target.toAbsolutePath().getParent();
|
|
||||||
if (parent != null) {
|
|
||||||
Files.createDirectories(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
String temporaryPrefix = targetFile.getName();
|
|
||||||
if (temporaryPrefix.length() < 3) {
|
|
||||||
temporaryPrefix = (temporaryPrefix + "___").substring(0, 3);
|
|
||||||
}
|
|
||||||
Path temporary = Files.createTempFile(parent, temporaryPrefix, ".tmp");
|
|
||||||
try {
|
|
||||||
Files.writeString(temporary, configuration.saveToString(), StandardCharsets.UTF_8);
|
|
||||||
try {
|
|
||||||
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
} catch (AtomicMoveNotSupportedException ignored) {
|
|
||||||
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
Files.deleteIfExists(temporary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
# ============================================================================
|
|
||||||
# EssentialsC - 便捷菜单布局
|
|
||||||
# ============================================================================
|
|
||||||
# 模块总开关位于 modules.yml:modules.blocks.enabled
|
|
||||||
# 菜单名称与物品文本位于 lang/<语言>.yml 的 blocks-menu 节点。
|
|
||||||
|
|
||||||
config-version: 1
|
|
||||||
layout-version: 2
|
|
||||||
|
|
||||||
# 每个菜单项包含:
|
|
||||||
# slot 槽位编号,范围为 0 - 35
|
|
||||||
# material Bukkit Material 名称
|
|
||||||
# permission 显示并使用该项目所需的权限
|
|
||||||
# command 点击后执行的 EssentialsC 命令键
|
|
||||||
|
|
||||||
sections:
|
|
||||||
# 功能方块命令
|
|
||||||
blocks:
|
|
||||||
items:
|
|
||||||
workbench:
|
|
||||||
slot: 10
|
|
||||||
material: CRAFTING_TABLE
|
|
||||||
permission: essentialsc.command.workbench
|
|
||||||
command: workbench
|
|
||||||
enderchest:
|
|
||||||
slot: 11
|
|
||||||
material: ENDER_CHEST
|
|
||||||
permission: essentialsc.command.enderchest
|
|
||||||
command: enderchest
|
|
||||||
anvil:
|
|
||||||
slot: 12
|
|
||||||
material: ANVIL
|
|
||||||
permission: essentialsc.command.anvil
|
|
||||||
command: anvil
|
|
||||||
grindstone:
|
|
||||||
slot: 19
|
|
||||||
material: GRINDSTONE
|
|
||||||
permission: essentialsc.command.grindstone
|
|
||||||
command: grindstone
|
|
||||||
smithingtable:
|
|
||||||
slot: 20
|
|
||||||
material: SMITHING_TABLE
|
|
||||||
permission: essentialsc.command.smithingtable
|
|
||||||
command: smithingtable
|
|
||||||
stonecutter:
|
|
||||||
slot: 21
|
|
||||||
material: STONECUTTER
|
|
||||||
permission: essentialsc.command.stonecutter
|
|
||||||
command: stonecutter
|
|
||||||
loom:
|
|
||||||
slot: 28
|
|
||||||
material: LOOM
|
|
||||||
permission: essentialsc.command.loom
|
|
||||||
command: loom
|
|
||||||
cartographytable:
|
|
||||||
slot: 29
|
|
||||||
material: CARTOGRAPHY_TABLE
|
|
||||||
permission: essentialsc.command.cartographytable
|
|
||||||
command: cartographytable
|
|
||||||
|
|
||||||
# 玩家快捷功能
|
|
||||||
shortcuts:
|
|
||||||
items:
|
|
||||||
nightvision:
|
|
||||||
slot: 14
|
|
||||||
material: TINTED_GLASS
|
|
||||||
permission: essentialsc.command.nightvision
|
|
||||||
command: nightvision
|
|
||||||
glow:
|
|
||||||
slot: 15
|
|
||||||
material: GLOWSTONE
|
|
||||||
permission: essentialsc.command.glow
|
|
||||||
command: glow
|
|
||||||
+102
-87
@@ -1,124 +1,139 @@
|
|||||||
# EssentialsC 主配置
|
# EssentialsC 主配置文件
|
||||||
# 其他配置:modules.yml、maintenance.yml、blocks-menu.yml
|
|
||||||
# 消息与颜色:lang/<语言>.yml
|
|
||||||
# 修改后使用 /essc reload 重载;命令注册状态发生变化时建议重启服务器。
|
|
||||||
|
|
||||||
|
# 配置文件版本号
|
||||||
config-version: 2
|
config-version: 2
|
||||||
|
|
||||||
|
# 语言文件名称,对应插件数据目录下 lang/<语言名>.yml
|
||||||
language: "zh_CN"
|
language: "zh_CN"
|
||||||
|
|
||||||
# 输出 EssentialsC 及所有功能模块的详细调试日志。
|
# 是否输出更详细的调试日志。
|
||||||
debug: false
|
debug: false
|
||||||
|
|
||||||
# 管理模式
|
|
||||||
admin-mode:
|
admin-mode:
|
||||||
# 原版飞行速度为 0.1;0.2 表示两倍速度。
|
# 原版默认飞行速度为 0.1,这里 0.2 表示两倍飞行速度
|
||||||
fly-speed: 0.2
|
fly-speed: 0.2
|
||||||
# 状态提示刷新间隔,单位为 tick。
|
|
||||||
actionbar:
|
actionbar:
|
||||||
|
# 管理模式状态提示的刷新间隔,单位为 tick
|
||||||
interval-ticks: 40
|
interval-ticks: 40
|
||||||
|
|
||||||
# JEI 配方同步修复;是否加载由 modules.yml 控制。
|
|
||||||
jei-sync:
|
jei-sync:
|
||||||
# 玩家加入后延迟多少 tick 检测客户端品牌。
|
# 是否启用 JEI 配方同步修复
|
||||||
|
enabled: true
|
||||||
|
# 是否输出调试日志
|
||||||
|
debug: false
|
||||||
|
# 玩家加入后延迟多少 tick 再检测客户端品牌,避免品牌信息尚未同步完成。
|
||||||
brand-check-delay-ticks: 20
|
brand-check-delay-ticks: 20
|
||||||
|
# 是否在玩家加入时发送同步提示
|
||||||
send-player-message: true
|
send-player-message: true
|
||||||
|
|
||||||
# 生物掉落
|
|
||||||
mob-drops:
|
mob-drops:
|
||||||
enderman:
|
enderman:
|
||||||
# 允许末影人掉落搬运的方块。
|
# 是否允许末影人掉落方块
|
||||||
allow-drops: true
|
enabled: true
|
||||||
|
|
||||||
|
tpsbar:
|
||||||
|
# 可选值:off / auto / on
|
||||||
|
# auto: 若服务端没有原生 /tpsbar,则启用插件实现
|
||||||
|
# on: 始终启用插件实现;若服务端已有原生命令,则自动跳过以避免冲突
|
||||||
|
mode: auto
|
||||||
|
|
||||||
# TPA 传送请求
|
|
||||||
tpa:
|
tpa:
|
||||||
# 请求有效时间,单位为秒。
|
# TPA 请求有效时间,单位为秒
|
||||||
timeout-seconds: 60
|
timeout-seconds: 60
|
||||||
# 每名接收者最多保留的待处理请求数;超出时移除最早请求。
|
# 是否让 /tpa 接受后传送到接受时目标所在的位置快照,而不是传送完成时目标当前位置。
|
||||||
max-pending-requests: 5
|
|
||||||
|
|
||||||
# 位置规则
|
|
||||||
# /tpa:使用目标接受请求时的位置快照。
|
|
||||||
strict-tpa-requests: false
|
strict-tpa-requests: false
|
||||||
# /tpahere:使用请求者发起请求时的位置快照。
|
# 是否让 /tpahere 接受后传送到请求发起时的位置,而不是请求者当前所在位置。
|
||||||
|
# 该行为与 HuskHomes 的 strict_tpa_here_requests 默认值一致。
|
||||||
strict-tpahere-requests: true
|
strict-tpahere-requests: true
|
||||||
|
# 接受请求后的传送预热时间,单位为秒。设置为 0 可关闭预热。
|
||||||
# 传送预热
|
|
||||||
warmup-seconds: 5
|
warmup-seconds: 5
|
||||||
|
# 预热期间移动是否取消传送。
|
||||||
cancel-warmup-on-move: true
|
cancel-warmup-on-move: true
|
||||||
|
# 预热期间受到伤害是否取消传送。
|
||||||
cancel-warmup-on-damage: true
|
cancel-warmup-on-damage: true
|
||||||
# chat / actionbar / title / subtitle / none
|
|
||||||
warmup-display: actionbar
|
|
||||||
# 异步传送会先加载目标区块,推荐 Paper / Leaves 服务器保持开启。
|
|
||||||
teleport-async: true
|
|
||||||
# 传送完成后的无敌时间,单位为秒;0 表示关闭。
|
|
||||||
teleport-invulnerability-seconds: 0
|
|
||||||
|
|
||||||
# 冷却时间;单位为秒,0 表示关闭对应冷却。
|
|
||||||
cooldowns:
|
cooldowns:
|
||||||
|
# 是否启用 TPA 冷却系统。
|
||||||
enabled: true
|
enabled: true
|
||||||
cooldown-times:
|
cooldown-times:
|
||||||
|
# 发送传送请求后的冷却时间,单位为秒。0 表示关闭。
|
||||||
SEND_TELEPORT_REQUEST: 0
|
SEND_TELEPORT_REQUEST: 0
|
||||||
|
# 接受传送请求后的冷却时间,单位为秒。0 表示关闭。
|
||||||
ACCEPT_TELEPORT_REQUEST: 0
|
ACCEPT_TELEPORT_REQUEST: 0
|
||||||
|
# 判断移动取消的曼哈顿距离阈值。0.1 与 HuskHomes 行为接近,可避免只转头就取消。
|
||||||
# 音效
|
warmup-move-threshold: 0.1
|
||||||
|
# 预热倒计时显示位置:actionbar / chat / none。
|
||||||
|
warmup-display: actionbar
|
||||||
sounds:
|
sounds:
|
||||||
|
# 是否播放 TPA 相关音效。
|
||||||
enabled: true
|
enabled: true
|
||||||
|
# 收到请求时播放的音效。
|
||||||
request-received: "entity.experience_orb.pickup"
|
request-received: "entity.experience_orb.pickup"
|
||||||
|
# 预热倒计时时播放的音效。
|
||||||
warmup: "block.note_block.banjo"
|
warmup: "block.note_block.banjo"
|
||||||
|
# 预热被取消时播放的音效。
|
||||||
cancelled: "entity.item.break"
|
cancelled: "entity.item.break"
|
||||||
|
# 传送完成时播放的音效。
|
||||||
complete: "entity.enderman.teleport"
|
complete: "entity.enderman.teleport"
|
||||||
|
|
||||||
# SkinBridge 外置皮肤站检测与同步;同时受 modules.yml 中的模块开关控制。
|
blocks-menu:
|
||||||
skin-bridge:
|
# 菜单布局版本,用于后续自动迁移槽位布局
|
||||||
# 是否加载由 modules.yml 控制;加载前必须填写 MineSkin API Key。
|
layout-version: 2
|
||||||
# 是否向玩家发送检测与同步结果。
|
sections:
|
||||||
send-player-message: true
|
blocks:
|
||||||
# 是否在控制台记录每次来源检测结果。
|
items:
|
||||||
log-detection-results: true
|
workbench:
|
||||||
# 玩家加入后延迟多少 tick 开始检测。
|
# 物品所在槽位
|
||||||
join-delay-ticks: 20
|
slot: 10
|
||||||
# 检测结果与生成皮肤的内存缓存时间,单位为分钟。
|
# 菜单图标材质
|
||||||
cache-minutes: 120
|
material: CRAFTING_TABLE
|
||||||
# 持久化 MineSkin 纹理缓存的最大条目数,超出时优先清理最早过期的记录。
|
# 所需权限
|
||||||
max-generated-cache-entries: 500
|
permission: essentialsc.command.workbench
|
||||||
# 强制刷新同一玩家皮肤的冷却时间,单位为秒。
|
# 点击后执行的命令键
|
||||||
force-refresh-cooldown-seconds: 30
|
command: workbench
|
||||||
# 仅当 Provider 纹理与玩家登录时携带的纹理一致时,才确认其来自该皮肤站。
|
enderchest:
|
||||||
require-current-texture-match: true
|
slot: 11
|
||||||
# 查询皮肤站 Profile 的超时时间,单位为秒。
|
material: ENDER_CHEST
|
||||||
profile-request-timeout-seconds: 5
|
permission: essentialsc.command.enderchest
|
||||||
|
command: enderchest
|
||||||
# 排除名单中的玩家不会查询皮肤站,也不会修改当前皮肤。
|
anvil:
|
||||||
exclusions:
|
slot: 12
|
||||||
uuids: []
|
material: ANVIL
|
||||||
names: []
|
permission: essentialsc.command.anvil
|
||||||
|
command: anvil
|
||||||
mineskin:
|
grindstone:
|
||||||
endpoint: "https://api.mineskin.org"
|
slot: 19
|
||||||
# 只应填写在服务器运行目录中,禁止提交真实密钥。
|
material: GRINDSTONE
|
||||||
api-key: ""
|
permission: essentialsc.command.grindstone
|
||||||
# 可选值:public / unlisted / private
|
command: grindstone
|
||||||
visibility: "unlisted"
|
smithingtable:
|
||||||
# 等待 MineSkin 队列完成的最长时间,单位为秒。
|
slot: 20
|
||||||
request-timeout-seconds: 30
|
material: SMITHING_TABLE
|
||||||
# 两次 MineSkin 生成任务之间的最小间隔,单位为毫秒。
|
permission: essentialsc.command.smithingtable
|
||||||
minimum-submit-interval-millis: 1000
|
command: smithingtable
|
||||||
|
stonecutter:
|
||||||
# 数值越小,Provider 查询优先级越高;name 会显示在日志和状态命令中。
|
slot: 21
|
||||||
providers:
|
material: STONECUTTER
|
||||||
infstar-mc:
|
permission: essentialsc.command.stonecutter
|
||||||
enabled: true
|
command: stonecutter
|
||||||
name: "InfstarMC"
|
loom:
|
||||||
priority: 10
|
slot: 28
|
||||||
profile-url: "https://skin.infstar.cn/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
material: LOOM
|
||||||
littleskin:
|
permission: essentialsc.command.loom
|
||||||
enabled: true
|
command: loom
|
||||||
name: "LittleSkin"
|
cartographytable:
|
||||||
priority: 20
|
slot: 29
|
||||||
profile-url: "https://littleskin.cn/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
material: CARTOGRAPHY_TABLE
|
||||||
custom-blessing-skin:
|
permission: essentialsc.command.cartographytable
|
||||||
# 自建 Blessing Skin 示例。启用前请修改 name 和 profile-url。
|
command: cartographytable
|
||||||
enabled: false
|
shortcuts:
|
||||||
name: "Blessing Skin"
|
items:
|
||||||
priority: 30
|
nightvision:
|
||||||
profile-url: "https://skin.example.com/api/yggdrasil/sessionserver/session/minecraft/profile/{uuid}?unsigned=false"
|
slot: 14
|
||||||
|
material: TINTED_GLASS
|
||||||
|
permission: essentialsc.command.nightvision
|
||||||
|
command: nightvision
|
||||||
|
glow:
|
||||||
|
slot: 15
|
||||||
|
material: GLOWSTONE
|
||||||
|
permission: essentialsc.command.glow
|
||||||
|
command: glow
|
||||||
|
|||||||
+188
-235
@@ -1,286 +1,239 @@
|
|||||||
# English language file
|
# English language file
|
||||||
# MiniMessage format with green success, red errors, and gray details.
|
|
||||||
|
|
||||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
prefix: "&6[EssentialsC] &r"
|
||||||
|
|
||||||
messages:
|
messages:
|
||||||
no-permission: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to use this command.</#FF7E5E> <gray>Required: {permission}</gray>'
|
no-permission: "&cYou don't have permission to use this command!\n&7Required permission: {permission}"
|
||||||
player-only: '<#FF3300>Error:</#FF3300> <#FF7E5E>This command can only be run by players.</#FF7E5E>'
|
player-only: "&cThis command can only be executed by players!"
|
||||||
console-name: 'Console'
|
config-reloaded: "&aConfiguration reloaded."
|
||||||
config-reloaded: '<#00FB9A>Configuration reloaded.</#00FB9A>'
|
version: "&fEssentialsC v{version}"
|
||||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
paper-version: "&7Running on Paper {version}"
|
||||||
paper-version: '<gray>Running on Paper {version}</gray>'
|
unknown-subcommand: "&cUnknown subcommand: {command}"
|
||||||
unknown-subcommand: '<#FF3300>Error:</#FF3300> <#FF7E5E>Unknown subcommand: {command}</#FF7E5E>'
|
help-usage: "&7Use &f/essc help &7to view available commands."
|
||||||
help-usage: '<gray>Use <white>/essc help</white> to view available commands.</gray>'
|
module-disabled: "&cThis feature module is currently disabled. Please contact an administrator."
|
||||||
module-disabled: '<#FF3300>Error:</#FF3300> <#FF7E5E>This feature module is currently disabled.</#FF7E5E>'
|
blocks-menu-empty: "&cYou do not currently have any available shortcut menu entries."
|
||||||
blocks-menu-empty: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have any available shortcut menu entries.</#FF7E5E>'
|
|
||||||
|
|
||||||
hat-success: '<#00FB9A>You are now wearing <bold>{item}</bold> on your head.</#00FB9A>'
|
hat-success: "&aYou are now wearing {item} on your head!"
|
||||||
hat-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not wear that item on your head.</#FF7E5E>'
|
hat-failed: "&cFailed to wear the item on your head!"
|
||||||
hat-no-item: '<#FF3300>Error:</#FF3300> <#FF7E5E>You need to hold an item.</#FF7E5E>'
|
hat-no-item: "&cYou need to hold an item in your hand!"
|
||||||
suicide-message: '<#FF7E5E>{player} died by suicide.</#FF7E5E>'
|
suicide-message: "&e{player} has committed suicide!"
|
||||||
fly-enabled: '<#00FB9A>Flight mode enabled.</#00FB9A>'
|
fly-enabled: "&aFlight mode enabled!"
|
||||||
fly-disabled: '<#FF7E5E>Flight mode disabled.</#FF7E5E>'
|
fly-disabled: "&cFlight mode disabled!"
|
||||||
fly-permission-removed: '<#FF7E5E>Your flight permission was removed, so flight mode was disabled.</#FF7E5E>'
|
nightvision-enabled: "&aNight vision enabled!"
|
||||||
nightvision-enabled: '<#00FB9A>Night vision enabled.</#00FB9A>'
|
nightvision-disabled: "&cNight vision disabled!"
|
||||||
nightvision-disabled: '<#FF7E5E>Night vision disabled.</#FF7E5E>'
|
nightvision-usage: "&cUsage: /nightvision [on|off|toggle]"
|
||||||
nightvision-permission-removed: '<#FF7E5E>Your night vision permission was removed, so night vision was disabled.</#FF7E5E>'
|
glow-enabled: "&aGlowing enabled!"
|
||||||
nightvision-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /nightvision [on|off|toggle]</#FF7E5E>'
|
glow-disabled: "&cGlowing disabled!"
|
||||||
glow-enabled: '<#00FB9A>Glowing enabled.</#00FB9A>'
|
glow-usage: "&cUsage: /glow [on|off|toggle]"
|
||||||
glow-disabled: '<#FF7E5E>Glowing disabled.</#FF7E5E>'
|
vanish-enabled: "&aYou are now vanished!"
|
||||||
glow-permission-removed: '<#FF7E5E>Your glowing permission was removed, so glowing was disabled.</#FF7E5E>'
|
vanish-disabled: "&cYou are no longer vanished!"
|
||||||
glow-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /glow [on|off|toggle]</#FF7E5E>'
|
seen-usage: "&cUsage: /seen <player>"
|
||||||
vanish-enabled: '<#00FB9A>You are now vanished.</#00FB9A>'
|
seen-usage-console: "&cUsage: /seen <player>"
|
||||||
vanish-disabled: '<#FF7E5E>You are no longer vanished.</#FF7E5E>'
|
player-not-found: "&cPlayer not found: {player}"
|
||||||
vanish-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save vanish state; no changes were applied.</#FF7E5E>'
|
no-permission-others: "&cYou don't have permission to affect other players!"
|
||||||
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-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /seen [player]</#FF7E5E>'
|
|
||||||
seen-header: '<#00FB9A>Player information:</#00FB9A> <white>{player}</white>'
|
|
||||||
seen-status-online: '<gray>Status: <#00FB9A>Online</#00FB9A></gray>'
|
|
||||||
seen-status-offline: '<gray>Status: <#FF7E5E>Offline</#FF7E5E></gray>'
|
|
||||||
seen-world: '<gray>World: <white>{world}</white></gray>'
|
|
||||||
seen-last-online: '<gray>Last online: <white>{time}</white></gray>'
|
|
||||||
seen-first-joined: '<gray>First joined: <white>{time}</white></gray>'
|
|
||||||
player-not-found: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not find the player {player}.</#FF7E5E>'
|
|
||||||
no-permission-others: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to affect other players.</#FF7E5E>'
|
|
||||||
|
|
||||||
anvil-opened: '<#00FB9A>Opened an anvil.</#00FB9A>'
|
anvil-opened: "&aAnvil opened!"
|
||||||
enchantingtable-opened: '<#00FB9A>Opened an enchanting table.</#00FB9A>'
|
enchantingtable-opened: "&aEnchanting table opened!"
|
||||||
heal-self: '<#00FB9A>Your health and hunger have been restored.</#00FB9A>'
|
heal-self: "&aYour health and hunger have been restored!"
|
||||||
heal-other: '<#00FB9A>You healed <bold>{player}</bold>.</#00FB9A>'
|
heal-other: "&aYou have healed player {player}!"
|
||||||
heal-by-other: '<#00FB9A>You were healed by <bold>{admin}</bold>.</#00FB9A>'
|
heal-by-other: "&aYou have been healed by admin {admin}!"
|
||||||
heal-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /heal [player]</#FF7E5E>'
|
feed-self: "&aYour hunger has been restored!"
|
||||||
feed-self: '<#00FB9A>Your hunger has been restored.</#00FB9A>'
|
feed-other: "&aYou have fed player {player}!"
|
||||||
feed-other: '<#00FB9A>You fed <bold>{player}</bold>.</#00FB9A>'
|
feed-by-other: "&aYou have been fed by admin {admin}!"
|
||||||
feed-by-other: '<#00FB9A>You were fed by <bold>{admin}</bold>.</#00FB9A>'
|
repair-hand-success: "&aItem in hand repaired!"
|
||||||
feed-usage-console: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /feed [player]</#FF7E5E>'
|
repair-all-success: "&aRepaired {count} items!"
|
||||||
repair-hand-success: '<#00FB9A>Repaired the item in your hand.</#00FB9A>'
|
repair-not-damaged: "&cThis item is not damaged!"
|
||||||
repair-all-success: '<#00FB9A>Repaired <bold>{count}</bold> item(s).</#00FB9A>'
|
repair-no-item-in-hand: "&cYou don't have an item in your hand!"
|
||||||
repair-not-damaged: '<#FF3300>Error:</#FF3300> <#FF7E5E>This item is not damaged.</#FF7E5E>'
|
repair-no-items: "&cNo repairable items in inventory!"
|
||||||
repair-no-item-in-hand: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have an item in your hand.</#FF7E5E>'
|
no-permission-repair-all: "&cYou don't have permission to repair all items!"
|
||||||
repair-no-items: '<#FF3300>Error:</#FF3300> <#FF7E5E>There are no repairable items in your inventory.</#FF7E5E>'
|
|
||||||
no-permission-repair-all: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have permission to repair all items.</#FF7E5E>'
|
|
||||||
|
|
||||||
mobdrop-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save config: {error}</#FF7E5E>'
|
mobdrop-save-failed: "&cFailed to save config: {error}"
|
||||||
mobdrop-toggled: '<#00FB9A>Enderman drops are now {status}.</#00FB9A>'
|
mobdrop-toggled: "&aEnderman drops are now {status}&a."
|
||||||
shulkerbox-nested: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot put a shulker box inside another shulker box.</#FF7E5E>'
|
shulkerbox-nested: "&cYou cannot put a shulker box inside another shulker box."
|
||||||
shulkerbox-unstack-first: '<#FF3300>Error:</#FF3300> <#FF7E5E>Please unstack the shulker box before quick opening it.</#FF7E5E>'
|
shulkerbox-unstack-first: "&cPlease unstack the shulker box before using quick open."
|
||||||
shulkerbox-open-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to open the shulker box. Please try again.</#FF7E5E>'
|
jei-sync-fabric: "&6JEI-FIX&8(&bFabric&8): &eSynchronizing recipes..."
|
||||||
shulkerbox-session-invalid: '<#FF3300>Error:</#FF3300> <#FF7E5E>The shulker box session became invalid. Saving was stopped to prevent item duplication.</#FF7E5E>'
|
jei-sync-neoforge: "&6JEI-FIX&8(&bNeoForge&8): &eSynchronizing recipes..."
|
||||||
jei-sync-fabric: '<#00FB9A>Synchronizing recipes for your <bold>Fabric</bold> client…</#00FB9A>'
|
|
||||||
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: "&6========== &eEssentialsC Help &6=========="
|
||||||
version: '<gray>Plugin version: <white>{version}</white></gray>'
|
version: "&7Plugin Version: &f{version}"
|
||||||
section-blocks: '<#00FB9A>Functional Block Commands</#00FB9A>'
|
section-blocks: "&6Functional Block Commands:"
|
||||||
section-other: '<#00FB9A>Other Commands</#00FB9A>'
|
section-other: "&6Other Commands:"
|
||||||
footer: '<gray>Each command requires the corresponding permission.</gray>'
|
footer: "&7Each command requires the corresponding permission."
|
||||||
|
|
||||||
commands:
|
commands:
|
||||||
reload: '<white>/essc reload</white> <gray>- Reload plugin configuration</gray>'
|
workbench: " &f/workbench &7- Open a crafting table"
|
||||||
version: '<white>/essc version</white> <gray>- View plugin and server versions</gray>'
|
anvil: " &f/anvil &7- Open an anvil"
|
||||||
workbench: '<white>/workbench</white> <gray>- Open a crafting table</gray>'
|
enchantingtable: " &f/enchantingtable &7- Open an enchanting table"
|
||||||
anvil: '<white>/anvil</white> <gray>- Open an anvil</gray>'
|
cartographytable: " &f/cartographytable &7- Open a cartography table"
|
||||||
enchantingtable: '<white>/enchantingtable</white> <gray>- Open an enchanting table</gray>'
|
grindstone: " &f/grindstone &7- Open a grindstone"
|
||||||
cartographytable: '<white>/cartographytable</white> <gray>- Open a cartography table</gray>'
|
loom: " &f/loom &7- Open a loom"
|
||||||
grindstone: '<white>/grindstone</white> <gray>- Open a grindstone</gray>'
|
smithingtable: " &f/smithingtable &7- Open a smithing table"
|
||||||
loom: '<white>/loom</white> <gray>- Open a loom</gray>'
|
stonecutter: " &f/stonecutter &7- Open a stonecutter"
|
||||||
smithingtable: '<white>/smithingtable</white> <gray>- Open a smithing table</gray>'
|
enderchest: " &f/enderchest &7- Open your ender chest"
|
||||||
stonecutter: '<white>/stonecutter</white> <gray>- Open a stonecutter</gray>'
|
blocks: " &f/blocks &7- Open the shortcut menu"
|
||||||
enderchest: '<white>/enderchest</white> <gray>- Open your ender chest</gray>'
|
hat: " &f/hat &7- Wear the held item as a hat"
|
||||||
blocks: '<white>/blocks</white> <gray>- Open the shortcut menu</gray>'
|
suicide: " &f/suicide &7- Commit suicide"
|
||||||
hat: '<white>/hat</white> <gray>- Wear the held item as a hat</gray>'
|
fly: " &f/fly &7- Toggle flight mode"
|
||||||
suicide: '<white>/suicide</white> <gray>- Die by suicide</gray>'
|
nightvision: " &f/nightvision &7- Toggle night vision"
|
||||||
fly: '<white>/fly</white> <gray>- Toggle flight mode</gray>'
|
glow: " &f/glow &7- Toggle glowing"
|
||||||
nightvision: '<white>/nightvision</white> <gray>- Toggle night vision</gray>'
|
heal: " &f/heal &7- Restore health and hunger"
|
||||||
glow: '<white>/glow</white> <gray>- Toggle glowing</gray>'
|
vanish: " &f/vanish &7- Toggle vanish mode"
|
||||||
heal: '<white>/heal [player]</white> <gray>- Restore health and hunger</gray>'
|
seen: " &f/seen &7- View player information"
|
||||||
vanish: '<white>/vanish</white> <gray>- Toggle vanish mode</gray>'
|
feed: " &f/feed &7- Restore hunger"
|
||||||
seen: '<white>/seen [player]</white> <gray>- View player information</gray>'
|
repair: " &f/repair &7- Repair held or all items"
|
||||||
feed: '<white>/feed [player]</white> <gray>- Restore hunger</gray>'
|
tpa: " &f/tpa <player> &7- Request to teleport to a player"
|
||||||
repair: '<white>/repair</white> <gray>- Repair held or all items</gray>'
|
tpahere: " &f/tpahere <player> &7- Request a player teleport to you"
|
||||||
tpa: '<white>/tpa [player]</white> <gray>- Request to teleport to a player</gray>'
|
tpaall: " &f/tpaall &7- Request all players teleport to you"
|
||||||
tpahere: '<white>/tpahere [player]</white> <gray>- Request a player teleport to you</gray>'
|
tpaccept: " &f/tpaccept [player] &7- Accept a teleport request"
|
||||||
tpaall: '<white>/tpaall</white> <gray>- Request all players teleport to you</gray>'
|
tpdeny: " &f/tpdeny [player] &7- Deny a teleport request"
|
||||||
tpaccept: '<white>/tpaccept [player]</white> <gray>- Accept a teleport request</gray>'
|
tpignore: " &f/tpignore &7- Toggle ignoring teleport requests"
|
||||||
tpdeny: '<white>/tpdeny [player]</white> <gray>- Deny a teleport request</gray>'
|
admin: " &f/essc admin &7- Toggle admin mode"
|
||||||
tpignore: '<white>/tpignore</white> <gray>- Toggle ignoring teleport requests</gray>'
|
tpsbar: " &f/tpsbar [player] &7- Toggle TPS boss bar"
|
||||||
skin: '<white>/essc skin [status|refresh] [player]</white> <gray>- View or refresh SkinBridge status</gray>'
|
maintenance: " &f/maintenance <on|off|status|reload|add|remove|list> &7- Manage maintenance mode"
|
||||||
admin: '<white>/essc admin</white> <gray>- Toggle admin mode</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:
|
||||||
usage-tpa: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpa [player]</#FF7E5E>'
|
usage-tpa: "&cUsage: /tpa <player>"
|
||||||
usage-tpahere: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpahere [player]</#FF7E5E>'
|
usage-tpahere: "&cUsage: /tpahere <player>"
|
||||||
usage-tpaall: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpaall</#FF7E5E>'
|
usage-tpaall: "&cUsage: /tpaall"
|
||||||
usage-tpaccept: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpaccept [player]</#FF7E5E>'
|
usage-tpaccept: "&cUsage: /tpaccept [player]"
|
||||||
usage-tpdeny: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpdeny [player]</#FF7E5E>'
|
usage-tpdeny: "&cUsage: /tpdeny [player]"
|
||||||
self: '<#FF3300>Error:</#FF3300> <#FF7E5E>You cannot send a teleport request to yourself.</#FF7E5E>'
|
self: "&cYou cannot send a teleport request to yourself."
|
||||||
sent-tpa: '<#00FB9A>You sent a teleport request asking to teleport to</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold><#00FB9A>.</#00FB9A>'
|
sent-tpa: "&aSent a teleport request to {target}. It expires in {seconds} seconds."
|
||||||
sent-tpahere: '<#00FB9A>You sent a teleport request asking</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold> <#00FB9A>to teleport to you.</#00FB9A>'
|
sent-tpahere: "&aInvited {target} to teleport to you. The request expires in {seconds} seconds."
|
||||||
ignoring-requests: '<#FF3300>Error:</#FF3300> <#FF7E5E>You are currently ignoring teleport requests.</#FF7E5E> <#FF7E5E><click:run_command:/tpignore><hover:show_text:"<#FF7E5E>Click to listen for incoming teleport requests</#FF7E5E>">[Stop Ignoring...]</hover></click></#FF7E5E>'
|
duplicate-request: "&eYou already have a pending request of this type for {target}."
|
||||||
send-cooldown: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must wait {seconds}s before doing that again.</#FF7E5E>'
|
ignoring-requests: "&cYou are currently ignoring teleport requests."
|
||||||
accept-cooldown: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must wait {seconds}s before doing that again.</#FF7E5E>'
|
send-cooldown: "&cPlease wait {seconds} seconds before sending another teleport request."
|
||||||
received-tpa: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>has requested to teleport to you.</#00FB9A>'
|
accept-cooldown: "&cPlease wait {seconds} seconds before accepting another teleport request."
|
||||||
received-tpahere: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>has requested that you teleport to them.</#00FB9A>'
|
received-tpa: "&e{requester} wants to teleport to you."
|
||||||
response-buttons: '<gray>Options:</gray> <#00FB9A><click:run_command:''/tpaccept {requester}''><hover:show_text:"<#00FB9A>Accept teleport request\n<dark_gray>Click to accept {requester}''s request</dark_gray></#00FB9A>">[✔ Accept…]</hover></click></#00FB9A> <#FF3300><click:run_command:''/tpdeny {requester}''><hover:show_text:"<#FF3300>Decline teleport request\n<dark_gray>Click to decline {requester}''s request</dark_gray></#FF3300>">[❌ Decline…]</hover></click></#FF3300>'
|
received-tpahere: "&e{requester} invited you to teleport to them."
|
||||||
no-request: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have a pending teleport request.</#FF7E5E>'
|
response-hint: "&7Type &f/tpaccept {requester} &7to accept or &f/tpdeny {requester} &7to deny."
|
||||||
invalid-request: '<#FF3300>Error:</#FF3300> <#FF7E5E>You do not have a pending teleport request from {requester}.</#FF7E5E>'
|
accept-button: "&a[Accept]"
|
||||||
accepted-target: '<#00FB9A>You accepted {requester}''s teleport request!</#00FB9A>'
|
deny-button: "&c[Deny]"
|
||||||
accepted-sender: '<#00FB9A>{target} has accepted your teleport request!</#00FB9A>'
|
no-request: "&cYou do not have any pending teleport requests."
|
||||||
denied-target: '<#FF7E5E>You declined {requester}''s teleport request.</#FF7E5E>'
|
accepted-target: "&aAccepted {requester}'s teleport request."
|
||||||
denied-sender: '<#FF7E5E>{target} has declined your teleport request.</#FF7E5E>'
|
accepted-sender: "&a{target} accepted your teleport request."
|
||||||
expired: '<#FF3300>Error:</#FF3300> <#FF7E5E>Your pending teleport request has expired.</#FF7E5E>'
|
denied-target: "&cDenied {requester}'s teleport request."
|
||||||
player-offline: '<#FF3300>Error:</#FF3300> <#FF7E5E>The sender of your pending teleport request is no longer online.</#FF7E5E>'
|
denied-sender: "&c{target} denied your teleport request."
|
||||||
target-offline: '<#FF3300>Error:</#FF3300> <#FF7E5E>The teleport target could not be found.</#FF7E5E>'
|
expired: "&cYour pending teleport request has expired."
|
||||||
already-warming-up: '<#FF3300>Error:</#FF3300> <#FF7E5E>A related player is already warming up for teleportation.</#FF7E5E>'
|
expired-sender: "&cYour teleport request to {target} expired."
|
||||||
warmup-start: '<#00FB9A>You will be teleported in</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold> <#00FB9A>seconds, please stand still…</#00FB9A>'
|
expired-target: "&cThe teleport request from {requester} expired."
|
||||||
warmup-status: '<#00FB9A>Teleporting in</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold><#00FB9A>…</#00FB9A>'
|
player-offline: "&cTeleport failed because a player in the request is now offline."
|
||||||
warmup-processing: '<#00FB9A>Teleporting…</#00FB9A>'
|
already-warming-up: "&cA related player is already warming up for teleportation."
|
||||||
warmup-cancelled-move: '<#FF7E5E>Teleportation cancelled—you moved!</#FF7E5E>'
|
warmup-start: "&eTeleporting in {seconds} seconds. Do not move or take damage."
|
||||||
warmup-cancelled-damage: '<#FF7E5E>Teleportation cancelled—you took damage!</#FF7E5E>'
|
warmup-status: "&eTeleporting in {seconds} seconds"
|
||||||
warmup-cancelled-actionbar: '<#FF7E5E>Teleportation cancelled!</#FF7E5E>'
|
warmup-cancelled-move: "&cTeleport cancelled because you moved during warmup."
|
||||||
warmup-stand-still: '<#FF3300>Error:</#FF3300> <#FF7E5E>You must be standing still before starting a teleport!</#FF7E5E>'
|
warmup-cancelled-damage: "&cTeleport cancelled because you took damage during warmup."
|
||||||
teleport-complete: '<#00FB9A>Teleportation complete!</#00FB9A>'
|
teleport-complete: "&aTeleport complete."
|
||||||
teleport-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Teleportation could not be completed. Please try again.</#FF7E5E>'
|
ignore-enabled: "&eYou are now ignoring teleport requests."
|
||||||
ignore-enabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>ignoring</#00FB9A></bold> <#00FB9A>incoming teleport requests.</#00FB9A>'
|
ignore-disabled: "&aYou are now accepting teleport requests."
|
||||||
ignore-disabled: '<#00FB9A>Now</#00FB9A> <bold><#00FB9A>listening</#00FB9A></bold> <#00FB9A>to incoming teleport requests.</#00FB9A>'
|
ignore-notification: "&7You are currently ignoring teleport requests."
|
||||||
ignore-save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save the teleport request ignore state; no changes were applied.</#FF7E5E>'
|
tpaall-sent: "&aSent teleport requests to all players."
|
||||||
ignore-notification: '<gray>You are currently ignoring teleport requests.</gray>'
|
tpaall-no-targets: "&cThere are no online players who can receive the request."
|
||||||
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>'
|
|
||||||
|
|
||||||
skin-bridge:
|
|
||||||
notifications:
|
|
||||||
detecting: '<#00FB9A>Detecting your skin source…</#00FB9A>'
|
|
||||||
synced: '<#00FB9A>Skin synchronized through <bold>{provider}</bold>.</#00FB9A>'
|
|
||||||
excluded: '<gray>You are excluded from SkinBridge detection; your current skin was kept.</gray>'
|
|
||||||
queue-full: '<#FFC43B>Skin detection is busy; this check was skipped.</#FFC43B>'
|
|
||||||
not-external: '<gray>No external skin provider matched; your current skin was kept.</gray>'
|
|
||||||
failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Skin detection or synchronization failed. Please try again later.</#FF7E5E>'
|
|
||||||
messages:
|
|
||||||
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /essc skin [status|refresh] [player]</#FF7E5E>'
|
|
||||||
dependency-missing: '<#FF3300>Error:</#FF3300> <#FF7E5E>No valid MineSkin API key is configured in config.yml.</#FF7E5E>'
|
|
||||||
no-providers: '<#FF3300>Error:</#FF3300> <#FF7E5E>No valid SkinBridge provider is enabled.</#FF7E5E>'
|
|
||||||
status-external: '<#00FB9A>{player} is identified as an external skin provider player.</#00FB9A> <gray>Provider: <white>{provider}</white></gray>'
|
|
||||||
status-excluded: '<gray>{player} is excluded from SkinBridge detection.</gray>'
|
|
||||||
status-not-external: '<gray>{player} does not match any configured external skin provider.</gray>'
|
|
||||||
status-pending: '<#FFC43B>SkinBridge is still detecting {player}''s login source.</#FFC43B>'
|
|
||||||
status-unknown: '<gray>{player} has not been checked by SkinBridge yet.</gray>'
|
|
||||||
refresh-queued: '<#00FB9A>SkinBridge is detecting and refreshing {player}''s skin.</#00FB9A>'
|
|
||||||
refresh-cached: '<gray>{player} is using a valid skin cache entry.</gray>'
|
|
||||||
refresh-running: '<#FFC43B>SkinBridge is already processing {player}.</#FFC43B>'
|
|
||||||
refresh-excluded: '<gray>{player} is excluded from SkinBridge detection; no skin was changed.</gray>'
|
|
||||||
refresh-cooldown: '<#FFC43B>Wait {seconds} seconds before refreshing {player} again.</#FFC43B>'
|
|
||||||
queue-full: '<#FFC43B>The SkinBridge lookup queue is full. Please try again later.</#FFC43B>'
|
|
||||||
|
|
||||||
blocks-menu:
|
blocks-menu:
|
||||||
title: '<#00FB9A><bold>Shortcut Menu</bold></#00FB9A>'
|
title: "&6&lEssentialsC &8- &e&lShortcut Menu"
|
||||||
items:
|
items:
|
||||||
workbench:
|
workbench:
|
||||||
name: '<#00FB9A>Workbench</#00FB9A>'
|
name: "&eWorkbench"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/workbench</gray>'
|
- "&7/workbench"
|
||||||
- '<gray>Open a crafting table</gray>'
|
- "&7Open a crafting table"
|
||||||
enderchest:
|
enderchest:
|
||||||
name: '<#00FB9A>Ender Chest</#00FB9A>'
|
name: "&eEnder Chest"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/enderchest</gray>'
|
- "&7/enderchest"
|
||||||
- '<gray>Open your ender chest</gray>'
|
- "&7Open your ender chest"
|
||||||
anvil:
|
anvil:
|
||||||
name: '<#00FB9A>Anvil</#00FB9A>'
|
name: "&eAnvil"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/anvil</gray>'
|
- "&7/anvil"
|
||||||
- '<gray>Open an anvil</gray>'
|
- "&7Open an anvil"
|
||||||
grindstone:
|
grindstone:
|
||||||
name: '<#00FB9A>Grindstone</#00FB9A>'
|
name: "&eGrindstone"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/grindstone</gray>'
|
- "&7/grindstone"
|
||||||
- '<gray>Open a grindstone</gray>'
|
- "&7Open a grindstone"
|
||||||
smithingtable:
|
smithingtable:
|
||||||
name: '<#00FB9A>Smithing Table</#00FB9A>'
|
name: "&eSmithing Table"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/smithingtable</gray>'
|
- "&7/smithingtable"
|
||||||
- '<gray>Open a smithing table</gray>'
|
- "&7Open a smithing table"
|
||||||
stonecutter:
|
stonecutter:
|
||||||
name: '<#00FB9A>Stonecutter</#00FB9A>'
|
name: "&eStonecutter"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/stonecutter</gray>'
|
- "&7/stonecutter"
|
||||||
- '<gray>Open a stonecutter</gray>'
|
- "&7Open a stonecutter"
|
||||||
loom:
|
loom:
|
||||||
name: '<#00FB9A>Loom</#00FB9A>'
|
name: "&eLoom"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/loom</gray>'
|
- "&7/loom"
|
||||||
- '<gray>Open a loom</gray>'
|
- "&7Open a loom"
|
||||||
cartographytable:
|
cartographytable:
|
||||||
name: '<#00FB9A>Cartography Table</#00FB9A>'
|
name: "&eCartography Table"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/cartographytable</gray>'
|
- "&7/cartographytable"
|
||||||
- '<gray>Open a cartography table</gray>'
|
- "&7Open a cartography table"
|
||||||
nightvision:
|
nightvision:
|
||||||
name: '<#00FB9A>Night Vision</#00FB9A>'
|
name: "&bNight Vision"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/nightvision</gray>'
|
- "&7/nightvision"
|
||||||
- '<gray>Toggle night vision</gray>'
|
- "&7Toggle night vision"
|
||||||
glow:
|
glow:
|
||||||
name: '<#00FB9A>Glow</#00FB9A>'
|
name: "&eGlow"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/glow</gray>'
|
- "&7/glow"
|
||||||
- '<gray>Toggle your glowing effect</gray>'
|
- "&7Toggle your glowing effect"
|
||||||
|
|
||||||
admin-mode:
|
admin-mode:
|
||||||
actionbar: '<#FF7E5E><bold>Admin Mode</bold></#FF7E5E>'
|
actionbar: "&c&lAdmin Mode"
|
||||||
messages:
|
messages:
|
||||||
enabled: '<#00FB9A>Admin mode enabled; normal inventory has been saved.</#00FB9A>'
|
enabled: "&aAdmin mode enabled, normal inventory has been saved."
|
||||||
disabled: '<#FF7E5E>Admin mode disabled; normal inventory has been restored.</#FF7E5E>'
|
disabled: "&cAdmin mode disabled, normal inventory has been restored."
|
||||||
crash-restored: '<#FFC43B>The previous admin mode session has been restored safely.</#FFC43B>'
|
crash-restored: "&eThe previous admin mode session has been restored safely."
|
||||||
save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not safely save your inventory; admin mode was not enabled.</#FF7E5E>'
|
|
||||||
|
|
||||||
tpsbar:
|
tpsbar:
|
||||||
title-format: '<#00FB9A>TPS</#00FB9A><gray>: {tps_1m} | </gray><#00FB9A>MSPT</#00FB9A><gray>: {mspt} | </gray><#00FB9A>Ping</#00FB9A><gray>: {ping}</gray>'
|
title-format: "&eTPS&7: {tps_1m} &8| &eMSPT&7: {mspt} &8| &ePing&7: {ping}"
|
||||||
messages:
|
messages:
|
||||||
enabled-self: '<#00FB9A>TPSBar enabled.</#00FB9A>'
|
enabled-self: "&aTPSBar enabled."
|
||||||
disabled-self: '<#FF7E5E>TPSBar disabled.</#FF7E5E>'
|
disabled-self: "&cTPSBar disabled."
|
||||||
enabled-other: '<#00FB9A>Enabled TPSBar for {player}.</#00FB9A>'
|
enabled-other: "&aEnabled TPSBar for {player}."
|
||||||
disabled-other: '<#FF7E5E>Disabled TPSBar for {player}.</#FF7E5E>'
|
disabled-other: "&cDisabled TPSBar for {player}."
|
||||||
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /tpsbar [player]</#FF7E5E>'
|
usage: "&cUsage: /tpsbar [player]"
|
||||||
player-not-found: '<#FF3300>Error:</#FF3300> <#FF7E5E>Could not find the player {player}.</#FF7E5E>'
|
player-not-found: "&cPlayer not found: {player}"
|
||||||
no-targets: '<#FF3300>Error:</#FF3300> <#FF7E5E>No matching players were found to toggle.</#FF7E5E>'
|
no-targets: "&cNo matching players were found to toggle."
|
||||||
native-detected: '<gray>Detected a native /tpsbar command on this server; skipped plugin implementation.</gray>'
|
native-detected: "&7Detected a native /tpsbar command on this server, skipped plugin implementation."
|
||||||
plugin-enabled: '<gray>No native /tpsbar command was detected; plugin implementation enabled.</gray>'
|
plugin-enabled: "&7No native /tpsbar command was detected, plugin implementation enabled."
|
||||||
|
plugin-forced-but-native-exists: "&eThe configuration requests the plugin TPSBar, but a native /tpsbar already exists, so the plugin implementation was skipped to avoid conflicts."
|
||||||
|
mode-changed-reload: "&eTPSBar mode has been updated, but command registration changes require a server restart to fully take effect."
|
||||||
|
|
||||||
mobdrops-menu:
|
mobdrops-menu:
|
||||||
title: '<#00FB9A><bold>Mob Drop Control</bold></#00FB9A>'
|
title: "&6&lMob Drop Control"
|
||||||
status:
|
status:
|
||||||
enabled: '<#00FB9A>Enabled</#00FB9A>'
|
enabled: "&aEnabled"
|
||||||
disabled: '<#FF7E5E>Disabled</#FF7E5E>'
|
disabled: "&cDisabled"
|
||||||
enderman:
|
enderman:
|
||||||
name: '<#00FB9A>Enderman Drops</#00FB9A>'
|
name: "&dEnderman Drops"
|
||||||
status: '<gray>Current status: {status}</gray>'
|
status: "&7Current status: {status}"
|
||||||
toggle: '<gray>Click to toggle</gray>'
|
toggle: "&eClick to toggle"
|
||||||
|
|
||||||
maintenance:
|
maintenance:
|
||||||
status:
|
status:
|
||||||
enabled: '<#FF7E5E>Enabled</#FF7E5E>'
|
enabled: "&cEnabled"
|
||||||
disabled: '<#00FB9A>Disabled</#00FB9A>'
|
disabled: "&aDisabled"
|
||||||
address-hidden: 'hidden'
|
|
||||||
messages:
|
messages:
|
||||||
enabled: '<#00FB9A>Maintenance mode enabled.</#00FB9A>'
|
enabled: "&aMaintenance mode enabled."
|
||||||
disabled: '<#FF7E5E>Maintenance mode disabled.</#FF7E5E>'
|
disabled: "&cMaintenance mode disabled."
|
||||||
reloaded: '<#00FB9A>Maintenance configuration reloaded.</#00FB9A>'
|
reloaded: "&aMaintenance configuration reloaded."
|
||||||
save-failed: '<#FF3300>Error:</#FF3300> <#FF7E5E>Failed to save maintenance configuration; no changes were applied.</#FF7E5E>'
|
status: "&7Maintenance mode status: {status} &8| &7Whitelist: &f{whitelist_count}"
|
||||||
status: '<gray>Maintenance mode status: {status} | Whitelist: <white>{whitelist_count}</white></gray>'
|
usage: "&cUsage: /maintenance <on|off|status|reload|add|remove|list>"
|
||||||
usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance [on|off|status|reload|add|remove|list]</#FF7E5E>'
|
add-usage: "&cUsage: /maintenance add <player|uuid>"
|
||||||
add-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance add [player|uuid]</#FF7E5E>'
|
remove-usage: "&cUsage: /maintenance remove <player|uuid>"
|
||||||
remove-usage: '<#FF3300>Error:</#FF3300> <#FF7E5E>Usage: /maintenance remove [player|uuid]</#FF7E5E>'
|
whitelist-added: "&aAdded {player} to the maintenance whitelist."
|
||||||
whitelist-added: '<#00FB9A>Added {player} to the maintenance whitelist.</#00FB9A>'
|
whitelist-removed: "&aRemoved {player} from the maintenance whitelist."
|
||||||
whitelist-removed: '<#00FB9A>Removed {player} from the maintenance whitelist.</#00FB9A>'
|
whitelist-exists: "&e{player} is already on the maintenance whitelist."
|
||||||
whitelist-exists: '<#FFC43B>{player} is already on the maintenance whitelist.</#FFC43B>'
|
whitelist-missing: "&c{player} is not on the maintenance whitelist."
|
||||||
whitelist-missing: '<#FF3300>Error:</#FF3300> <#FF7E5E>{player} is not on the maintenance whitelist.</#FF7E5E>'
|
whitelist-empty: "&7The maintenance whitelist is empty."
|
||||||
whitelist-empty: '<gray>The maintenance whitelist is empty.</gray>'
|
whitelist-list: "&7Maintenance whitelist ({count}): &f{entries}"
|
||||||
whitelist-list: '<gray>Maintenance whitelist ({count}): <white>{entries}</white></gray>'
|
login-blocked: "&e{player} was blocked by maintenance mode. &7UUID: {uuid} &8| &7IP: {address}"
|
||||||
login-blocked: '<#FFC43B>{player} was blocked by maintenance mode.</#FFC43B> <gray>UUID: {uuid} | IP: {address}</gray>'
|
|
||||||
|
|||||||
+188
-235
@@ -1,286 +1,239 @@
|
|||||||
# 简体中文语言文件
|
# 简体中文语言文件
|
||||||
# 支持 MiniMessage 格式,默认使用绿色成功、红色错误和灰色说明。
|
|
||||||
|
|
||||||
prefix: '<#00FB9A><bold>[EssentialsC]</bold></#00FB9A><gray>: </gray>'
|
prefix: "&7[&6EssentialsC&7]&f:&r"
|
||||||
|
|
||||||
messages:
|
messages:
|
||||||
no-permission: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限执行此命令.</#FF7E5E> <gray>需要权限: {permission}</gray>'
|
no-permission: "&c你没有权限执行此命令!\n&7需要权限:{permission}"
|
||||||
player-only: '<#FF3300>错误:</#FF3300> <#FF7E5E>此命令只能由玩家执行.</#FF7E5E>'
|
player-only: "&c此命令只能由玩家执行!"
|
||||||
console-name: '控制台'
|
config-reloaded: "&a配置已重载。"
|
||||||
config-reloaded: '<#00FB9A>配置已重载.</#00FB9A>'
|
version: "&fEssentialsC v{version}"
|
||||||
version: '<#00FB9A>EssentialsC v{version}</#00FB9A>'
|
paper-version: "&7当前运行于 Paper {version}"
|
||||||
paper-version: '<gray>当前运行于 Paper {version}</gray>'
|
unknown-subcommand: "&c未知子命令:{command}"
|
||||||
unknown-subcommand: '<#FF3300>错误:</#FF3300> <#FF7E5E>未知子命令: {command}</#FF7E5E>'
|
help-usage: "&7使用 &f/essc help &7查看可用命令。"
|
||||||
help-usage: '<gray>使用 <white>/essc help</white> 查看可用命令.</gray>'
|
module-disabled: "&c该功能模块当前已关闭,请联系管理员。"
|
||||||
module-disabled: '<#FF3300>错误:</#FF3300> <#FF7E5E>该功能模块当前已关闭.</#FF7E5E>'
|
blocks-menu-empty: "&c你当前没有可用的便捷菜单项目。"
|
||||||
blocks-menu-empty: '<#FF3300>错误:</#FF3300> <#FF7E5E>你当前没有可用的便捷菜单项目.</#FF7E5E>'
|
|
||||||
|
|
||||||
hat-success: '<#00FB9A>你已将 <bold>{item}</bold> 戴在头上.</#00FB9A>'
|
hat-success: "&a你已将 {item} 戴在头上!"
|
||||||
hat-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法将该物品戴在头上.</#FF7E5E>'
|
hat-failed: "&c无法将该物品戴在头上!"
|
||||||
hat-no-item: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要手持一个物品.</#FF7E5E>'
|
hat-no-item: "&c你需要手持一个物品!"
|
||||||
suicide-message: '<#FF7E5E>{player} 自杀了.</#FF7E5E>'
|
suicide-message: "&e{player} 自杀了!"
|
||||||
fly-enabled: '<#00FB9A>飞行模式已开启.</#00FB9A>'
|
fly-enabled: "&a飞行模式已开启!"
|
||||||
fly-disabled: '<#FF7E5E>飞行模式已关闭.</#FF7E5E>'
|
fly-disabled: "&c飞行模式已关闭!"
|
||||||
fly-permission-removed: '<#FF7E5E>你的飞行权限已被移除,飞行模式已关闭.</#FF7E5E>'
|
nightvision-enabled: "&a夜视已开启!"
|
||||||
nightvision-enabled: '<#00FB9A>夜视已开启.</#00FB9A>'
|
nightvision-disabled: "&c夜视已关闭!"
|
||||||
nightvision-disabled: '<#FF7E5E>夜视已关闭.</#FF7E5E>'
|
nightvision-usage: "&c用法:/nightvision [on|off|toggle]"
|
||||||
nightvision-permission-removed: '<#FF7E5E>你的夜视权限已被移除,夜视已关闭.</#FF7E5E>'
|
glow-enabled: "&a发光已开启!"
|
||||||
nightvision-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /nightvision [on|off|toggle]</#FF7E5E>'
|
glow-disabled: "&c发光已关闭!"
|
||||||
glow-enabled: '<#00FB9A>发光已开启.</#00FB9A>'
|
glow-usage: "&c用法:/glow [on|off|toggle]"
|
||||||
glow-disabled: '<#FF7E5E>发光已关闭.</#FF7E5E>'
|
vanish-enabled: "&a你已进入隐身模式!"
|
||||||
glow-permission-removed: '<#FF7E5E>你的发光权限已被移除,发光已关闭.</#FF7E5E>'
|
vanish-disabled: "&c你已退出隐身模式!"
|
||||||
glow-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /glow [on|off|toggle]</#FF7E5E>'
|
seen-usage: "&c用法:/seen <玩家>"
|
||||||
vanish-enabled: '<#00FB9A>你已进入隐身模式.</#00FB9A>'
|
seen-usage-console: "&c用法:/seen <玩家>"
|
||||||
vanish-disabled: '<#FF7E5E>你已退出隐身模式.</#FF7E5E>'
|
player-not-found: "&c未找到玩家:{player}"
|
||||||
vanish-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存隐身状态,本次操作未生效.</#FF7E5E>'
|
no-permission-others: "&c你没有权限影响其他玩家!"
|
||||||
vanish-permission-removed: '<#FFC43B>你的隐身权限已被移除,隐身模式已自动关闭.</#FFC43B>'
|
|
||||||
seen-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
|
||||||
seen-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /seen [玩家]</#FF7E5E>'
|
|
||||||
seen-header: '<#00FB9A>玩家信息:</#00FB9A> <white>{player}</white>'
|
|
||||||
seen-status-online: '<gray>状态: <#00FB9A>在线</#00FB9A></gray>'
|
|
||||||
seen-status-offline: '<gray>状态: <#FF7E5E>离线</#FF7E5E></gray>'
|
|
||||||
seen-world: '<gray>所在世界: <white>{world}</white></gray>'
|
|
||||||
seen-last-online: '<gray>最后在线: <white>{time}</white></gray>'
|
|
||||||
seen-first-joined: '<gray>首次加入: <white>{time}</white></gray>'
|
|
||||||
player-not-found: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到玩家 {player}.</#FF7E5E>'
|
|
||||||
no-permission-others: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限影响其他玩家.</#FF7E5E>'
|
|
||||||
|
|
||||||
anvil-opened: '<#00FB9A>已打开铁砧.</#00FB9A>'
|
anvil-opened: "&a已打开铁砧!"
|
||||||
enchantingtable-opened: '<#00FB9A>已打开附魔台.</#00FB9A>'
|
enchantingtable-opened: "&a已打开附魔台!"
|
||||||
heal-self: '<#00FB9A>你的生命值和饥饿值已恢复.</#00FB9A>'
|
heal-self: "&a你的生命值和饥饿值已恢复!"
|
||||||
heal-other: '<#00FB9A>你已治疗玩家 <bold>{player}</bold>.</#00FB9A>'
|
heal-other: "&a你已治疗玩家 {player}!"
|
||||||
heal-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 治疗了你.</#00FB9A>'
|
heal-by-other: "&a管理员 {admin} 治疗了你!"
|
||||||
heal-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /heal [玩家]</#FF7E5E>'
|
feed-self: "&a你的饥饿值已恢复!"
|
||||||
feed-self: '<#00FB9A>你的饥饿值已恢复.</#00FB9A>'
|
feed-other: "&a你已喂饱玩家 {player}!"
|
||||||
feed-other: '<#00FB9A>你已喂饱玩家 <bold>{player}</bold>.</#00FB9A>'
|
feed-by-other: "&a管理员 {admin} 喂饱了你!"
|
||||||
feed-by-other: '<#00FB9A>管理员 <bold>{admin}</bold> 喂饱了你.</#00FB9A>'
|
repair-hand-success: "&a手中物品已修复!"
|
||||||
feed-usage-console: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /feed [玩家]</#FF7E5E>'
|
repair-all-success: "&a已修复 {count} 个物品!"
|
||||||
repair-hand-success: '<#00FB9A>手中物品已修复.</#00FB9A>'
|
repair-not-damaged: "&c该物品没有损坏!"
|
||||||
repair-all-success: '<#00FB9A>已修复 <bold>{count}</bold> 个物品.</#00FB9A>'
|
repair-no-item-in-hand: "&c你手中没有物品!"
|
||||||
repair-not-damaged: '<#FF3300>错误:</#FF3300> <#FF7E5E>该物品没有损坏.</#FF7E5E>'
|
repair-no-items: "&c背包中没有可修复的物品!"
|
||||||
repair-no-item-in-hand: '<#FF3300>错误:</#FF3300> <#FF7E5E>你手中没有物品.</#FF7E5E>'
|
no-permission-repair-all: "&c你没有权限修复全部物品!"
|
||||||
repair-no-items: '<#FF3300>错误:</#FF3300> <#FF7E5E>背包中没有可修复的物品.</#FF7E5E>'
|
|
||||||
no-permission-repair-all: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有权限修复全部物品.</#FF7E5E>'
|
|
||||||
|
|
||||||
mobdrop-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>保存配置失败: {error}</#FF7E5E>'
|
mobdrop-save-failed: "&c保存配置失败:{error}"
|
||||||
mobdrop-toggled: '<#00FB9A>末影人掉落已切换为 {status}.</#00FB9A>'
|
mobdrop-toggled: "&a末影人掉落已切换为 {status}&a。"
|
||||||
shulkerbox-nested: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能将潜影盒放入另一个潜影盒.</#FF7E5E>'
|
shulkerbox-nested: "&c不能将潜影盒放入另一个潜影盒。"
|
||||||
shulkerbox-unstack-first: '<#FF3300>错误:</#FF3300> <#FF7E5E>请先将潜影盒拆分为单个后再快捷打开.</#FF7E5E>'
|
shulkerbox-unstack-first: "&c请先将潜影盒拆分为单个后再快捷打开。"
|
||||||
shulkerbox-open-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒打开失败,请稍后重试.</#FF7E5E>'
|
jei-sync-fabric: "&6JEI-FIX&8(&bFabric&8): &e正在同步配方..."
|
||||||
shulkerbox-session-invalid: '<#FF3300>错误:</#FF3300> <#FF7E5E>潜影盒会话异常,已停止保存以避免物品复制.</#FF7E5E>'
|
jei-sync-neoforge: "&6JEI-FIX&8(&bNeoForge&8): &e正在同步配方..."
|
||||||
jei-sync-fabric: '<#00FB9A>正在为 <bold>Fabric</bold> 客户端同步配方…</#00FB9A>'
|
|
||||||
jei-sync-neoforge: '<#00FB9A>正在为 <bold>NeoForge</bold> 客户端同步配方…</#00FB9A>'
|
|
||||||
|
|
||||||
help:
|
help:
|
||||||
title: '<#00FB9A><bold>EssentialsC</bold></#00FB9A> <gray>命令帮助</gray>'
|
title: "&6========== &eEssentialsC 帮助 &6=========="
|
||||||
version: '<gray>插件版本: <white>{version}</white></gray>'
|
version: "&7插件版本:&f{version}"
|
||||||
section-blocks: '<#00FB9A>功能方块命令</#00FB9A>'
|
section-blocks: "&6功能方块命令:"
|
||||||
section-other: '<#00FB9A>其他命令</#00FB9A>'
|
section-other: "&6其他命令:"
|
||||||
footer: '<gray>每个命令都需要对应权限.</gray>'
|
footer: "&7每个命令都需要对应权限。"
|
||||||
|
|
||||||
commands:
|
commands:
|
||||||
reload: '<white>/essc reload</white> <gray>- 重载插件配置</gray>'
|
workbench: " &f/workbench &7- 打开工作台"
|
||||||
version: '<white>/essc version</white> <gray>- 查看插件与服务端版本</gray>'
|
anvil: " &f/anvil &7- 打开铁砧"
|
||||||
workbench: '<white>/workbench</white> <gray>- 打开工作台</gray>'
|
enchantingtable: " &f/enchantingtable &7- 打开附魔台"
|
||||||
anvil: '<white>/anvil</white> <gray>- 打开铁砧</gray>'
|
cartographytable: " &f/cartographytable &7- 打开制图台"
|
||||||
enchantingtable: '<white>/enchantingtable</white> <gray>- 打开附魔台</gray>'
|
grindstone: " &f/grindstone &7- 打开砂轮"
|
||||||
cartographytable: '<white>/cartographytable</white> <gray>- 打开制图台</gray>'
|
loom: " &f/loom &7- 打开织布机"
|
||||||
grindstone: '<white>/grindstone</white> <gray>- 打开砂轮</gray>'
|
smithingtable: " &f/smithingtable &7- 打开锻造台"
|
||||||
loom: '<white>/loom</white> <gray>- 打开织布机</gray>'
|
stonecutter: " &f/stonecutter &7- 打开切石机"
|
||||||
smithingtable: '<white>/smithingtable</white> <gray>- 打开锻造台</gray>'
|
enderchest: " &f/enderchest &7- 打开末影箱"
|
||||||
stonecutter: '<white>/stonecutter</white> <gray>- 打开切石机</gray>'
|
blocks: " &f/blocks &7- 打开便捷菜单"
|
||||||
enderchest: '<white>/enderchest</white> <gray>- 打开末影箱</gray>'
|
hat: " &f/hat &7- 将手持物品戴在头上"
|
||||||
blocks: '<white>/blocks</white> <gray>- 打开便捷菜单</gray>'
|
suicide: " &f/suicide &7- 自杀"
|
||||||
hat: '<white>/hat</white> <gray>- 将手持物品戴在头上</gray>'
|
fly: " &f/fly &7- 切换飞行模式"
|
||||||
suicide: '<white>/suicide</white> <gray>- 自杀</gray>'
|
nightvision: " &f/nightvision &7- 切换夜视"
|
||||||
fly: '<white>/fly</white> <gray>- 切换飞行模式</gray>'
|
glow: " &f/glow &7- 切换发光"
|
||||||
nightvision: '<white>/nightvision</white> <gray>- 切换夜视</gray>'
|
heal: " &f/heal &7- 恢复生命值和饥饿值"
|
||||||
glow: '<white>/glow</white> <gray>- 切换发光</gray>'
|
vanish: " &f/vanish &7- 切换隐身模式"
|
||||||
heal: '<white>/heal [玩家]</white> <gray>- 恢复生命值和饥饿值</gray>'
|
seen: " &f/seen &7- 查看玩家信息"
|
||||||
vanish: '<white>/vanish</white> <gray>- 切换隐身模式</gray>'
|
feed: " &f/feed &7- 恢复饥饿值"
|
||||||
seen: '<white>/seen [玩家]</white> <gray>- 查看玩家信息</gray>'
|
repair: " &f/repair &7- 修复手中或全部物品"
|
||||||
feed: '<white>/feed [玩家]</white> <gray>- 恢复饥饿值</gray>'
|
tpa: " &f/tpa <玩家> &7- 请求传送到玩家身边"
|
||||||
repair: '<white>/repair</white> <gray>- 修复手中或全部物品</gray>'
|
tpahere: " &f/tpahere <玩家> &7- 请求玩家传送到你身边"
|
||||||
tpa: '<white>/tpa [玩家]</white> <gray>- 请求传送到玩家身边</gray>'
|
tpaall: " &f/tpaall &7- 向所有玩家发送传送到你身边的请求"
|
||||||
tpahere: '<white>/tpahere [玩家]</white> <gray>- 请求玩家传送到你身边</gray>'
|
tpaccept: " &f/tpaccept [玩家] &7- 接受传送请求"
|
||||||
tpaall: '<white>/tpaall</white> <gray>- 向所有玩家发送传送到你身边的请求</gray>'
|
tpdeny: " &f/tpdeny [玩家] &7- 拒绝传送请求"
|
||||||
tpaccept: '<white>/tpaccept [玩家]</white> <gray>- 接受传送请求</gray>'
|
tpignore: " &f/tpignore &7- 切换是否忽略传送请求"
|
||||||
tpdeny: '<white>/tpdeny [玩家]</white> <gray>- 拒绝传送请求</gray>'
|
admin: " &f/essc admin &7- 切换管理模式"
|
||||||
tpignore: '<white>/tpignore</white> <gray>- 切换是否忽略传送请求</gray>'
|
tpsbar: " &f/tpsbar [玩家] &7- 切换 TPS 状态栏"
|
||||||
skin: '<white>/essc skin [status|refresh] [玩家]</white> <gray>- 查看或刷新皮肤桥接状态</gray>'
|
maintenance: " &f/maintenance <on|off|status|reload|add|remove|list> &7- 管理维护模式"
|
||||||
admin: '<white>/essc admin</white> <gray>- 切换管理模式</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:
|
||||||
usage-tpa: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpa [玩家]</#FF7E5E>'
|
usage-tpa: "&c用法:/tpa <玩家>"
|
||||||
usage-tpahere: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpahere [玩家]</#FF7E5E>'
|
usage-tpahere: "&c用法:/tpahere <玩家>"
|
||||||
usage-tpaall: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpaall</#FF7E5E>'
|
usage-tpaall: "&c用法:/tpaall"
|
||||||
usage-tpaccept: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpaccept [玩家]</#FF7E5E>'
|
usage-tpaccept: "&c用法:/tpaccept [玩家]"
|
||||||
usage-tpdeny: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpdeny [玩家]</#FF7E5E>'
|
usage-tpdeny: "&c用法:/tpdeny [玩家]"
|
||||||
self: '<#FF3300>错误:</#FF3300> <#FF7E5E>不能向自己发送传送请求</#FF7E5E>'
|
self: "&c你不能向自己发送传送请求。"
|
||||||
sent-tpa: '<#00FB9A>已发送传送请求,请求传送到</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold>'
|
sent-tpa: "&a已向 {target} 发送传送请求,{seconds} 秒后过期。"
|
||||||
sent-tpahere: '<#00FB9A>已发送传送请求,请求</#00FB9A> <bold><#00FB9A>{target}</#00FB9A></bold> <#00FB9A>传送到你的位置</#00FB9A>'
|
sent-tpahere: "&a已邀请 {target} 传送到你身边,{seconds} 秒后过期。"
|
||||||
ignoring-requests: '<#FF3300>错误:</#FF3300> <#FF7E5E>你已忽略传送请求</#FF7E5E> <#FF7E5E><click:run_command:/tpignore><hover:show_text:"<#FF7E5E>点击恢复接收传送请求</#FF7E5E>">[恢复接收]</hover></click></#FF7E5E>'
|
duplicate-request: "&e你已经向 {target} 发送过同类型传送请求,请等待对方处理。"
|
||||||
send-cooldown: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要等待 {seconds}s 才能再次进行此操作</#FF7E5E>'
|
ignoring-requests: "&c你当前正在忽略传送请求。"
|
||||||
accept-cooldown: '<#FF3300>错误:</#FF3300> <#FF7E5E>你需要等待 {seconds}s 才能再次进行此操作</#FF7E5E>'
|
send-cooldown: "&c请等待 {seconds} 秒后再发送传送请求。"
|
||||||
received-tpa: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>请求传送到你的位置</#00FB9A>'
|
accept-cooldown: "&c请等待 {seconds} 秒后再接受传送请求。"
|
||||||
received-tpahere: '<bold><#00FB9A>{requester}</#00FB9A></bold> <#00FB9A>请求你传送到他的位置</#00FB9A>'
|
received-tpa: "&e{requester} 请求传送到你身边。"
|
||||||
response-buttons: '<gray>选项:</gray> <#00FB9A><click:run_command:''/tpaccept {requester}''><hover:show_text:''<#00FB9A>接受传送请求\n<dark_gray>点击接受 {requester} 的请求</dark_gray></#00FB9A>''>[✔ 接受]</hover></click></#00FB9A> <#FF3300><click:run_command:''/tpdeny {requester}''><hover:show_text:''<#FF3300>拒绝传送请求\n<dark_gray>点击拒绝 {requester} 的请求</dark_gray></#FF3300>''>[❌ 拒绝]</hover></click></#FF3300>'
|
received-tpahere: "&e{requester} 邀请你传送到对方身边。"
|
||||||
no-request: '<#FF3300>错误:</#FF3300> <#FF7E5E>你没有待处理的传送请求</#FF7E5E>'
|
response-hint: "&7输入 &f/tpaccept {requester} &7接受,或 &f/tpdeny {requester} &7拒绝。"
|
||||||
invalid-request: '<#FF3300>错误:</#FF3300> <#FF7E5E>目前没有来自 {requester} 的传送请求</#FF7E5E>'
|
accept-button: "&a[接受]"
|
||||||
accepted-target: '<#00FB9A>已接受 {requester} 的传送请求</#00FB9A>'
|
deny-button: "&c[拒绝]"
|
||||||
accepted-sender: '<#00FB9A>{target} 接受了你的传送请求</#00FB9A>'
|
no-request: "&c你没有待处理的传送请求。"
|
||||||
denied-target: '<#FF7E5E>已拒绝 {requester} 的传送请求</#FF7E5E>'
|
accepted-target: "&a你已接受 {requester} 的传送请求。"
|
||||||
denied-sender: '<#FF7E5E>{target} 拒绝了你的传送请求</#FF7E5E>'
|
accepted-sender: "&a{target} 已接受你的传送请求。"
|
||||||
expired: '<#FF3300>错误:</#FF3300> <#FF7E5E>传送请求已过期</#FF7E5E>'
|
denied-target: "&c你已拒绝 {requester} 的传送请求。"
|
||||||
player-offline: '<#FF3300>错误:</#FF3300> <#FF7E5E>你待处理的传送请求目标玩家不在线</#FF7E5E>'
|
denied-sender: "&c{target} 拒绝了你的传送请求。"
|
||||||
target-offline: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到目标玩家</#FF7E5E>'
|
expired: "&c你的待处理传送请求已过期。"
|
||||||
already-warming-up: '<#FF3300>错误:</#FF3300> <#FF7E5E>相关玩家已有一个正在预热的传送</#FF7E5E>'
|
expired-sender: "&c你发给 {target} 的传送请求已过期。"
|
||||||
warmup-start: '<#00FB9A>你将在</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold> <#00FB9A>秒后被传送,请不要移动…</#00FB9A>'
|
expired-target: "&c来自 {requester} 的传送请求已过期。"
|
||||||
warmup-status: '<#00FB9A>将在</#00FB9A> <bold><#00FB9A>{seconds}</#00FB9A></bold><#00FB9A>秒后传送…</#00FB9A>'
|
player-offline: "&c无法完成传送,请求中的玩家已离线。"
|
||||||
warmup-processing: '<#00FB9A>传送中…</#00FB9A>'
|
already-warming-up: "&c相关玩家已有一个正在预热的传送。"
|
||||||
warmup-cancelled-move: '<#FF7E5E>传送取消: 你移动了!</#FF7E5E>'
|
warmup-start: "&e传送将在 {seconds} 秒后开始,请不要移动或受到伤害。"
|
||||||
warmup-cancelled-damage: '<#FF7E5E>传送取消: 你受到了伤害!</#FF7E5E>'
|
warmup-status: "&e传送倒计时:{seconds} 秒"
|
||||||
warmup-cancelled-actionbar: '<#FF7E5E>传送取消!</#FF7E5E>'
|
warmup-cancelled-move: "&c传送已取消:你在预热期间移动了。"
|
||||||
warmup-stand-still: '<#FF3300>错误:</#FF3300> <#FF7E5E>在传送时你不能移动!</#FF7E5E>'
|
warmup-cancelled-damage: "&c传送已取消:你在预热期间受到了伤害。"
|
||||||
teleport-complete: '<#00FB9A>传送完成!</#00FB9A>'
|
teleport-complete: "&a传送完成。"
|
||||||
teleport-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法完成传送,请稍后重试</#FF7E5E>'
|
ignore-enabled: "&e你已开始忽略传送请求。"
|
||||||
ignore-enabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>忽略</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
ignore-disabled: "&a你已恢复接收传送请求。"
|
||||||
ignore-disabled: '<#00FB9A>你已</#00FB9A> <bold><#00FB9A>恢复接收</#00FB9A></bold> <#00FB9A>传送请求</#00FB9A>'
|
ignore-notification: "&7你当前正在忽略传送请求。"
|
||||||
ignore-save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法保存传送请求忽略状态,本次操作未生效.</#FF7E5E>'
|
tpaall-sent: "&a已向所有玩家发送传送请求。"
|
||||||
ignore-notification: '<gray>你当前正在忽略传送请求.</gray>'
|
tpaall-no-targets: "&c没有可接收请求的在线玩家。"
|
||||||
tpaall-sent: '<#00FB9A>你已向所有玩家发送传送请求,请求他们传送到你的位置</#00FB9A>'
|
|
||||||
tpaall-no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>当前没有其他在线玩家.</#FF7E5E>'
|
|
||||||
|
|
||||||
skin-bridge:
|
|
||||||
notifications:
|
|
||||||
detecting: '<#00FB9A>正在检测你的皮肤来源…</#00FB9A>'
|
|
||||||
synced: '<#00FB9A>已通过 <bold>{provider}</bold> 同步皮肤.</#00FB9A>'
|
|
||||||
excluded: '<gray>你位于 SkinBridge 排除名单中,已保留当前皮肤.</gray>'
|
|
||||||
queue-full: '<#FFC43B>当前皮肤检测任务较多,已跳过本次检测.</#FFC43B>'
|
|
||||||
not-external: '<gray>未匹配外置皮肤站,已保留当前皮肤.</gray>'
|
|
||||||
failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>皮肤检测或同步失败,请稍后重试.</#FF7E5E>'
|
|
||||||
messages:
|
|
||||||
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /essc skin [status|refresh] [玩家]</#FF7E5E>'
|
|
||||||
dependency-missing: '<#FF3300>错误:</#FF3300> <#FF7E5E>未在 config.yml 中配置有效的 MineSkin API Key.</#FF7E5E>'
|
|
||||||
no-providers: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有启用有效的 SkinBridge Provider.</#FF7E5E>'
|
|
||||||
status-external: '<#00FB9A>{player} 已识别为外置皮肤站玩家.</#00FB9A> <gray>Provider: <white>{provider}</white></gray>'
|
|
||||||
status-excluded: '<gray>{player} 位于 SkinBridge 排除名单中.</gray>'
|
|
||||||
status-not-external: '<gray>{player} 未匹配任何已配置的外置皮肤站.</gray>'
|
|
||||||
status-pending: '<#FFC43B>{player} 的皮肤站来源正在检测中.</#FFC43B>'
|
|
||||||
status-unknown: '<gray>{player} 尚未进行 SkinBridge 检测.</gray>'
|
|
||||||
refresh-queued: '<#00FB9A>已开始重新检测并刷新 {player} 的皮肤.</#00FB9A>'
|
|
||||||
refresh-cached: '<gray>{player} 正在使用有效的皮肤缓存.</gray>'
|
|
||||||
refresh-running: '<#FFC43B>{player} 的皮肤检测任务仍在运行.</#FFC43B>'
|
|
||||||
refresh-excluded: '<gray>{player} 位于 SkinBridge 排除名单中,未修改皮肤.</gray>'
|
|
||||||
refresh-cooldown: '<#FFC43B>请等待 {seconds} 秒后再刷新 {player} 的皮肤.</#FFC43B>'
|
|
||||||
queue-full: '<#FFC43B>SkinBridge 查询队列已满,请稍后重试.</#FFC43B>'
|
|
||||||
|
|
||||||
blocks-menu:
|
blocks-menu:
|
||||||
title: '<#00FB9A><bold>便捷菜单</bold></#00FB9A>'
|
title: "&6&lEssentialsC &8- &e&l便捷菜单"
|
||||||
items:
|
items:
|
||||||
workbench:
|
workbench:
|
||||||
name: '<#00FB9A>工作台</#00FB9A>'
|
name: "&e工作台"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/workbench</gray>'
|
- "&7/workbench"
|
||||||
- '<gray>打开工作台</gray>'
|
- "&7打开工作台"
|
||||||
enderchest:
|
enderchest:
|
||||||
name: '<#00FB9A>末影箱</#00FB9A>'
|
name: "&e末影箱"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/enderchest</gray>'
|
- "&7/enderchest"
|
||||||
- '<gray>打开末影箱</gray>'
|
- "&7打开末影箱"
|
||||||
anvil:
|
anvil:
|
||||||
name: '<#00FB9A>铁砧</#00FB9A>'
|
name: "&e铁砧"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/anvil</gray>'
|
- "&7/anvil"
|
||||||
- '<gray>打开铁砧</gray>'
|
- "&7打开铁砧"
|
||||||
grindstone:
|
grindstone:
|
||||||
name: '<#00FB9A>砂轮</#00FB9A>'
|
name: "&e砂轮"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/grindstone</gray>'
|
- "&7/grindstone"
|
||||||
- '<gray>打开砂轮</gray>'
|
- "&7打开砂轮"
|
||||||
smithingtable:
|
smithingtable:
|
||||||
name: '<#00FB9A>锻造台</#00FB9A>'
|
name: "&e锻造台"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/smithingtable</gray>'
|
- "&7/smithingtable"
|
||||||
- '<gray>打开锻造台</gray>'
|
- "&7打开锻造台"
|
||||||
stonecutter:
|
stonecutter:
|
||||||
name: '<#00FB9A>切石机</#00FB9A>'
|
name: "&e切石机"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/stonecutter</gray>'
|
- "&7/stonecutter"
|
||||||
- '<gray>打开切石机</gray>'
|
- "&7打开切石机"
|
||||||
loom:
|
loom:
|
||||||
name: '<#00FB9A>织布机</#00FB9A>'
|
name: "&e织布机"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/loom</gray>'
|
- "&7/loom"
|
||||||
- '<gray>打开织布机</gray>'
|
- "&7打开织布机"
|
||||||
cartographytable:
|
cartographytable:
|
||||||
name: '<#00FB9A>制图台</#00FB9A>'
|
name: "&e制图台"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/cartographytable</gray>'
|
- "&7/cartographytable"
|
||||||
- '<gray>打开制图台</gray>'
|
- "&7打开制图台"
|
||||||
nightvision:
|
nightvision:
|
||||||
name: '<#00FB9A>夜视开关</#00FB9A>'
|
name: "&b夜视开关"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/nightvision</gray>'
|
- "&7/nightvision"
|
||||||
- '<gray>切换夜视效果</gray>'
|
- "&7切换夜视效果"
|
||||||
glow:
|
glow:
|
||||||
name: '<#00FB9A>发光开关</#00FB9A>'
|
name: "&e发光开关"
|
||||||
lore:
|
lore:
|
||||||
- '<gray>/glow</gray>'
|
- "&7/glow"
|
||||||
- '<gray>切换自身发光效果</gray>'
|
- "&7切换自身发光效果"
|
||||||
|
|
||||||
admin-mode:
|
admin-mode:
|
||||||
actionbar: '<#FF7E5E><bold>管理模式</bold></#FF7E5E>'
|
actionbar: "&c&l管理模式"
|
||||||
messages:
|
messages:
|
||||||
enabled: '<#00FB9A>管理模式已开启,普通背包已保存.</#00FB9A>'
|
enabled: "&a管理模式已开启,普通背包已保存。"
|
||||||
disabled: '<#FF7E5E>管理模式已关闭,普通背包已恢复.</#FF7E5E>'
|
disabled: "&c管理模式已关闭,普通背包已恢复。"
|
||||||
crash-restored: '<#FFC43B>上一次管理模式会话已安全恢复.</#FFC43B>'
|
crash-restored: "&e上一次管理模式会话已安全恢复。"
|
||||||
save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>无法安全保存当前背包,管理模式未开启.</#FF7E5E>'
|
|
||||||
|
|
||||||
tpsbar:
|
tpsbar:
|
||||||
title-format: '<#00FB9A>TPS</#00FB9A><gray>: {tps_1m} | </gray><#00FB9A>MSPT</#00FB9A><gray>: {mspt} | </gray><#00FB9A>Ping</#00FB9A><gray>: {ping}</gray>'
|
title-format: "&eTPS&7: {tps_1m} &8| &eMSPT&7: {mspt} &8| &ePing&7: {ping}"
|
||||||
messages:
|
messages:
|
||||||
enabled-self: '<#00FB9A>已开启 TPSBar.</#00FB9A>'
|
enabled-self: "&a已开启 TPSBar。"
|
||||||
disabled-self: '<#FF7E5E>已关闭 TPSBar.</#FF7E5E>'
|
disabled-self: "&c已关闭 TPSBar。"
|
||||||
enabled-other: '<#00FB9A>已为 {player} 开启 TPSBar.</#00FB9A>'
|
enabled-other: "&a已为 {player} 开启 TPSBar。"
|
||||||
disabled-other: '<#FF7E5E>已为 {player} 关闭 TPSBar.</#FF7E5E>'
|
disabled-other: "&c已为 {player} 关闭 TPSBar。"
|
||||||
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /tpsbar [玩家]</#FF7E5E>'
|
usage: "&c用法:/tpsbar [玩家]"
|
||||||
player-not-found: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有找到玩家 {player}.</#FF7E5E>'
|
player-not-found: "&c未找到玩家:{player}"
|
||||||
no-targets: '<#FF3300>错误:</#FF3300> <#FF7E5E>没有匹配到可切换的玩家.</#FF7E5E>'
|
no-targets: "&c没有匹配到可切换的玩家。"
|
||||||
native-detected: '<gray>检测到服务端已内置 /tpsbar,已跳过插件实现.</gray>'
|
native-detected: "&7检测到服务端已内置 /tpsbar,已跳过插件实现。"
|
||||||
plugin-enabled: '<gray>未检测到服务端内置 /tpsbar,已启用插件实现.</gray>'
|
plugin-enabled: "&7未检测到服务端内置 /tpsbar,已启用插件实现。"
|
||||||
|
plugin-forced-but-native-exists: "&e配置要求启用插件版 TPSBar,但服务端已存在原生 /tpsbar,已跳过插件实现以避免冲突。"
|
||||||
|
mode-changed-reload: "&eTPSBar 模式已更新,但命令注册状态需要重启服务器后才会完全生效。"
|
||||||
|
|
||||||
mobdrops-menu:
|
mobdrops-menu:
|
||||||
title: '<#00FB9A><bold>生物掉落控制</bold></#00FB9A>'
|
title: "&6&l生物掉落控制"
|
||||||
status:
|
status:
|
||||||
enabled: '<#00FB9A>开启</#00FB9A>'
|
enabled: "&a开启"
|
||||||
disabled: '<#FF7E5E>关闭</#FF7E5E>'
|
disabled: "&c关闭"
|
||||||
enderman:
|
enderman:
|
||||||
name: '<#00FB9A>末影人掉落</#00FB9A>'
|
name: "&d末影人掉落"
|
||||||
status: '<gray>当前状态: {status}</gray>'
|
status: "&7当前状态:{status}"
|
||||||
toggle: '<gray>点击切换</gray>'
|
toggle: "&e点击切换"
|
||||||
|
|
||||||
maintenance:
|
maintenance:
|
||||||
status:
|
status:
|
||||||
enabled: '<#FF7E5E>开启</#FF7E5E>'
|
enabled: "&c开启"
|
||||||
disabled: '<#00FB9A>关闭</#00FB9A>'
|
disabled: "&a关闭"
|
||||||
address-hidden: '已隐藏'
|
|
||||||
messages:
|
messages:
|
||||||
enabled: '<#00FB9A>维护模式已开启.</#00FB9A>'
|
enabled: "&a维护模式已开启。"
|
||||||
disabled: '<#FF7E5E>维护模式已关闭.</#FF7E5E>'
|
disabled: "&c维护模式已关闭。"
|
||||||
reloaded: '<#00FB9A>维护模式配置已重载.</#00FB9A>'
|
reloaded: "&a维护模式配置已重载。"
|
||||||
save-failed: '<#FF3300>错误:</#FF3300> <#FF7E5E>维护模式配置保存失败,操作未生效.</#FF7E5E>'
|
status: "&7维护模式当前状态:{status} &8| &7白名单:&f{whitelist_count}"
|
||||||
status: '<gray>维护模式当前状态: {status} | 白名单: <white>{whitelist_count}</white></gray>'
|
usage: "&c用法:/maintenance <on|off|status|reload|add|remove|list>"
|
||||||
usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance [on|off|status|reload|add|remove|list]</#FF7E5E>'
|
add-usage: "&c用法:/maintenance add <玩家|UUID>"
|
||||||
add-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance add [玩家|UUID]</#FF7E5E>'
|
remove-usage: "&c用法:/maintenance remove <玩家|UUID>"
|
||||||
remove-usage: '<#FF3300>错误:</#FF3300> <#FF7E5E>用法: /maintenance remove [玩家|UUID]</#FF7E5E>'
|
whitelist-added: "&a已将 {player} 加入维护白名单。"
|
||||||
whitelist-added: '<#00FB9A>已将 {player} 加入维护白名单.</#00FB9A>'
|
whitelist-removed: "&a已将 {player} 移出维护白名单。"
|
||||||
whitelist-removed: '<#00FB9A>已将 {player} 移出维护白名单.</#00FB9A>'
|
whitelist-exists: "&e{player} 已在维护白名单中。"
|
||||||
whitelist-exists: '<#FFC43B>{player} 已在维护白名单中.</#FFC43B>'
|
whitelist-missing: "&c{player} 不在维护白名单中。"
|
||||||
whitelist-missing: '<#FF3300>错误:</#FF3300> <#FF7E5E>{player} 不在维护白名单中.</#FF7E5E>'
|
whitelist-empty: "&7维护白名单为空。"
|
||||||
whitelist-empty: '<gray>维护白名单为空.</gray>'
|
whitelist-list: "&7维护白名单({count}):&f{entries}"
|
||||||
whitelist-list: '<gray>维护白名单 ({count}): <white>{entries}</white></gray>'
|
login-blocked: "&e{player} 被维护模式拦截。&7UUID:{uuid} &8| &7IP:{address}"
|
||||||
login-blocked: '<#FFC43B>{player} 被维护模式拦截.</#FFC43B> <gray>UUID: {uuid} | IP: {address}</gray>'
|
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ notify:
|
|||||||
enabled: true
|
enabled: true
|
||||||
# 拥有该权限的在线玩家会收到拦截通知。
|
# 拥有该权限的在线玩家会收到拦截通知。
|
||||||
permission: "essentialsc.maintenance.notify"
|
permission: "essentialsc.maintenance.notify"
|
||||||
# 是否在通知中显示玩家 IP 地址;出于隐私考虑默认关闭。
|
|
||||||
include-address: false
|
|
||||||
|
|
||||||
whitelist:
|
whitelist:
|
||||||
# 这些 UUID 可以在维护模式下进入服务器。
|
# 这些 UUID 可以在维护模式下进入服务器。
|
||||||
@@ -34,7 +32,7 @@ kick-message:
|
|||||||
- "&7请稍后再进入"
|
- "&7请稍后再进入"
|
||||||
|
|
||||||
bossbar:
|
bossbar:
|
||||||
# 维护模式开启时是否向所有在线玩家显示 BossBar。
|
# 维护模式开启时是否向无绕过权限的在线玩家显示 BossBar。
|
||||||
enabled: true
|
enabled: true
|
||||||
title: "&c服务器正在维护"
|
title: "&c服务器正在维护"
|
||||||
# 可选值:PINK / BLUE / RED / GREEN / YELLOW / PURPLE / WHITE
|
# 可选值:PINK / BLUE / RED / GREEN / YELLOW / PURPLE / WHITE
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# EssentialsC 模块配置
|
# EssentialsC 模块配置
|
||||||
#
|
#
|
||||||
# modules.yml 用于控制功能模块是否在运行时加载。
|
# modules.yml 用于控制功能模块是否在运行时加载。
|
||||||
# 各功能的详细设置位于 config.yml、maintenance.yml 与 blocks-menu.yml。
|
# config.yml 仍然用于控制已启用模块内部的具体行为。
|
||||||
#
|
#
|
||||||
# 修改模块开关后可使用 /essc reload 刷新运行期服务和监听器。
|
# 修改模块开关后可使用 /essc reload 刷新运行期服务和监听器。
|
||||||
# 直连命令的完整热增删仍建议通过重启服务器完成。
|
# 直连命令的完整热增删仍建议通过重启服务器完成。
|
||||||
@@ -12,21 +12,21 @@ modules:
|
|||||||
blocks:
|
blocks:
|
||||||
# 工作台、铁砧等便捷方块命令、/essc blocks 菜单和潜影盒快捷打开。
|
# 工作台、铁砧等便捷方块命令、/essc blocks 菜单和潜影盒快捷打开。
|
||||||
enabled: true
|
enabled: true
|
||||||
|
player:
|
||||||
|
# 玩家常用命令:飞行、夜视、发光、治疗、喂食、修复、帽子、自杀、隐身、查询玩家和 TPA。
|
||||||
|
enabled: true
|
||||||
admin-mode:
|
admin-mode:
|
||||||
# /essc admin 管理模式,以及独立背包和状态管理。
|
# /essc admin 管理模式,以及独立背包和状态管理。
|
||||||
enabled: true
|
enabled: true
|
||||||
tpsbar:
|
tpsbar:
|
||||||
# 插件版 TPSBar。检测到服务端原生命令时会自动避免冲突。
|
# 插件版 TPSBar。config.yml 中的 tpsbar.mode 仍会决定遇到原生 /tpsbar 时的行为。
|
||||||
enabled: true
|
enabled: true
|
||||||
jei-sync:
|
jei-sync:
|
||||||
# Fabric / NeoForge JEI 配方同步兼容修复。
|
# Fabric / NeoForge JEI 配方同步兼容修复。
|
||||||
enabled: true
|
enabled: true
|
||||||
mob-drops:
|
mob-drops:
|
||||||
# 末影人掉落控制菜单和监听器;具体掉落状态可在游戏内切换。
|
# 末影人掉落控制菜单和监听器。默认关闭,用于保留过去标准版的行为。
|
||||||
enabled: false
|
enabled: false
|
||||||
maintenance:
|
maintenance:
|
||||||
# 维护模式。开启维护后可替换 MOTD,并阻止无绕过权限的玩家进入。
|
# 维护模式。开启维护后可替换 MOTD,并阻止无绕过权限的玩家进入。
|
||||||
enabled: true
|
enabled: true
|
||||||
skin-bridge:
|
|
||||||
# 查询外置 Yggdrasil profile,并通过 MineSkin 与 Paper Profile API 同步皮肤。
|
|
||||||
enabled: false
|
|
||||||
|
|||||||
@@ -3,17 +3,10 @@ description: 适用于 Paper 服务端的轻量基础功能插件。
|
|||||||
version: ${version}
|
version: ${version}
|
||||||
|
|
||||||
main: cn.infstar.essentialsC.EssentialsC
|
main: cn.infstar.essentialsC.EssentialsC
|
||||||
api-version: '1.21.11'
|
api-version: '1.21'
|
||||||
load: POSTWORLD
|
load: POSTWORLD
|
||||||
folia-supported: false
|
folia-supported: false
|
||||||
|
|
||||||
dependencies:
|
|
||||||
server:
|
|
||||||
LuckPerms:
|
|
||||||
load: BEFORE
|
|
||||||
required: false
|
|
||||||
join-classpath: true
|
|
||||||
|
|
||||||
authors: [ Coldsmiles_7 ]
|
authors: [ Coldsmiles_7 ]
|
||||||
website: www.infstar.cn
|
website: www.infstar.cn
|
||||||
|
|
||||||
@@ -69,9 +62,6 @@ permissions:
|
|||||||
essentialsc.command.vanish:
|
essentialsc.command.vanish:
|
||||||
description: 允许使用 /vanish
|
description: 允许使用 /vanish
|
||||||
default: op
|
default: op
|
||||||
essentialsc.vanish.see:
|
|
||||||
description: 允许看见隐身玩家
|
|
||||||
default: op
|
|
||||||
essentialsc.command.seen:
|
essentialsc.command.seen:
|
||||||
description: 允许使用 /seen
|
description: 允许使用 /seen
|
||||||
default: op
|
default: op
|
||||||
@@ -129,22 +119,6 @@ permissions:
|
|||||||
essentialsc.command.maintenance:
|
essentialsc.command.maintenance:
|
||||||
description: 允许管理维护模式
|
description: 允许管理维护模式
|
||||||
default: op
|
default: op
|
||||||
essentialsc.command.skin:
|
|
||||||
description: 允许使用 SkinBridge 管理命令
|
|
||||||
default: op
|
|
||||||
children:
|
|
||||||
essentialsc.command.skin.status: true
|
|
||||||
essentialsc.command.skin.refresh: true
|
|
||||||
essentialsc.command.skin.others: true
|
|
||||||
essentialsc.command.skin.status:
|
|
||||||
description: 允许查看 SkinBridge 状态
|
|
||||||
default: op
|
|
||||||
essentialsc.command.skin.refresh:
|
|
||||||
description: 允许强制刷新自己的皮肤
|
|
||||||
default: op
|
|
||||||
essentialsc.command.skin.others:
|
|
||||||
description: 允许查看或刷新其他玩家的皮肤
|
|
||||||
default: op
|
|
||||||
essentialsc.maintenance.bypass:
|
essentialsc.maintenance.bypass:
|
||||||
description: 允许在维护模式下进入服务器
|
description: 允许在维护模式下进入服务器
|
||||||
default: op
|
default: op
|
||||||
@@ -178,7 +152,6 @@ permissions:
|
|||||||
essentialsc.command.heal: true
|
essentialsc.command.heal: true
|
||||||
essentialsc.command.heal.others: true
|
essentialsc.command.heal.others: true
|
||||||
essentialsc.command.vanish: true
|
essentialsc.command.vanish: true
|
||||||
essentialsc.vanish.see: true
|
|
||||||
essentialsc.command.seen: true
|
essentialsc.command.seen: true
|
||||||
essentialsc.command.feed: true
|
essentialsc.command.feed: true
|
||||||
essentialsc.command.feed.others: true
|
essentialsc.command.feed.others: true
|
||||||
@@ -198,10 +171,6 @@ permissions:
|
|||||||
essentialsc.command.tpsbar: true
|
essentialsc.command.tpsbar: true
|
||||||
essentialsc.command.tpsbar.others: true
|
essentialsc.command.tpsbar.others: true
|
||||||
essentialsc.command.maintenance: true
|
essentialsc.command.maintenance: true
|
||||||
essentialsc.command.skin: true
|
|
||||||
essentialsc.command.skin.status: true
|
|
||||||
essentialsc.command.skin.refresh: true
|
|
||||||
essentialsc.command.skin.others: true
|
|
||||||
essentialsc.maintenance.bypass: true
|
essentialsc.maintenance.bypass: true
|
||||||
essentialsc.maintenance.notify: true
|
essentialsc.maintenance.notify: true
|
||||||
essentialsc.shulkerbox.open: true
|
essentialsc.shulkerbox.open: true
|
||||||
|
|||||||
@@ -1,86 +0,0 @@
|
|||||||
package cn.infstar.essentialsC;
|
|
||||||
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
|
||||||
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.InputStreamReader;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class ConfigurationResourcesTest {
|
|
||||||
|
|
||||||
@ParameterizedTest
|
|
||||||
@ValueSource(strings = {
|
|
||||||
"config.yml",
|
|
||||||
"modules.yml",
|
|
||||||
"maintenance.yml",
|
|
||||||
"blocks-menu.yml",
|
|
||||||
"paper-plugin.yml",
|
|
||||||
"lang/zh_CN.yml",
|
|
||||||
"lang/en_US.yml"
|
|
||||||
})
|
|
||||||
void bundledYamlIsValid(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));
|
|
||||||
|
|
||||||
if (resourcePath.equals("config.yml")) {
|
|
||||||
assertEquals(2, configuration.getInt("config-version"));
|
|
||||||
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")) {
|
|
||||||
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 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,23 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.compat.jei;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
|
|
||||||
class RecipeGroupingTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void groupsValuesInOnePassAndPreservesOrder() {
|
|
||||||
List<String> recipes = List.of("crafting:first", "smelting:second", "crafting:third");
|
|
||||||
|
|
||||||
Map<String, List<String>> grouped = RecipeGrouping.groupBy(
|
|
||||||
recipes, value -> value.substring(0, value.indexOf(':')));
|
|
||||||
|
|
||||||
assertEquals(List.of("crafting", "smelting"), grouped.keySet().stream().toList());
|
|
||||||
assertEquals(List.of("crafting:first", "crafting:third"), grouped.get("crafting"));
|
|
||||||
assertEquals(List.of("smelting:second"), grouped.get("smelting"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,32 +0,0 @@
|
|||||||
package cn.infstar.essentialsC.teleport;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayDeque;
|
|
||||||
import java.util.Deque;
|
|
||||||
|
|
||||||
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 TeleportRequestQueuePolicyTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void keepsNewestRequestsWithinConfiguredLimit() {
|
|
||||||
Deque<String> requests = new ArrayDeque<>();
|
|
||||||
|
|
||||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "first", 2);
|
|
||||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "second", 2);
|
|
||||||
TeleportRequestQueuePolicy.addFirstBounded(requests, "third", 2);
|
|
||||||
|
|
||||||
assertEquals(java.util.List.of("third", "second"), java.util.List.copyOf(requests));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void retainsRecentlyExpiredRequestsForUserFeedback() {
|
|
||||||
long now = 120_000L;
|
|
||||||
|
|
||||||
assertFalse(TeleportRequestQueuePolicy.shouldPrune(90_000L, now, 60_000L));
|
|
||||||
assertTrue(TeleportRequestQueuePolicy.shouldPrune(60_000L, now, 60_000L));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+14
-44
@@ -1,7 +1,6 @@
|
|||||||
package cn.infstar.essentialsC.v1_21_11.jei;
|
package cn.infstar.essentialsC.v1_21_11.jei;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
import cn.infstar.essentialsC.compat.jei.RecipeGrouping;
|
|
||||||
import io.netty.buffer.Unpooled;
|
import io.netty.buffer.Unpooled;
|
||||||
import net.minecraft.core.registries.BuiltInRegistries;
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
@@ -23,9 +22,6 @@ import java.util.logging.Logger;
|
|||||||
|
|
||||||
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
private DiscardedPayload fabricPayloadCache;
|
|
||||||
private DiscardedPayload neoForgePayloadCache;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
@@ -37,10 +33,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (fabricPayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(fabricPayloadCache));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -49,17 +41,20 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var list = new ArrayList<FabricRecipeEntry>();
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
var seen = new HashSet<RecipeSerializer<?>>();
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
var groupedRecipes = RecipeGrouping.groupBy(
|
|
||||||
recipeMap.values(), holder -> holder.value().getSerializer());
|
|
||||||
|
|
||||||
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
if (!seen.add(serializer)) {
|
if (!seen.add(serializer)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<RecipeHolder<?>> recipes = groupedRecipes.get(serializer);
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (recipes != null && !recipes.isEmpty()) {
|
if (!recipes.isEmpty()) {
|
||||||
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
}
|
}
|
||||||
@@ -71,18 +66,13 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getFabricCodec().encode(buffer, payload);
|
getFabricCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
fabricPayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -101,11 +91,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (neoForgePayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(neoForgePayloadCache));
|
|
||||||
sendTags(serverPlayer, server);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -120,38 +105,23 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getNeoForgeStreamCodec().encode(buffer, payload);
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
neoForgePayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
sendTags(serverPlayer, server);
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void clearCache() {
|
|
||||||
fabricPayloadCache = null;
|
|
||||||
neoForgePayloadCache = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendTags(ServerPlayer serverPlayer, MinecraftServer server) {
|
|
||||||
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
|
||||||
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import org.gradle.api.attributes.java.TargetJvmVersion
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
id 'io.papermc.paperweight.userdev'
|
id 'io.papermc.paperweight.userdev'
|
||||||
@@ -15,20 +13,15 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api project(':compat-api')
|
api project(':compat-api')
|
||||||
paperweight.paperDevBundle('26.1.2.build.74-stable')
|
paperweight.paperDevBundle('26.1.2.build.72-stable')
|
||||||
}
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
}
|
}
|
||||||
|
|
||||||
configurations.configureEach {
|
|
||||||
attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 25)
|
|
||||||
}
|
|
||||||
|
|
||||||
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
tasks.withType(JavaCompile).configureEach {
|
||||||
options.encoding = 'UTF-8'
|
options.encoding = 'UTF-8'
|
||||||
options.release.set(21)
|
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-44
@@ -1,7 +1,6 @@
|
|||||||
package cn.infstar.essentialsC.v26_1_2.jei;
|
package cn.infstar.essentialsC.v26_1_2.jei;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
import cn.infstar.essentialsC.compat.jei.RecipeGrouping;
|
|
||||||
import io.netty.buffer.Unpooled;
|
import io.netty.buffer.Unpooled;
|
||||||
import net.minecraft.core.registries.BuiltInRegistries;
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
@@ -23,9 +22,6 @@ import java.util.logging.Logger;
|
|||||||
|
|
||||||
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
private DiscardedPayload fabricPayloadCache;
|
|
||||||
private DiscardedPayload neoForgePayloadCache;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
@@ -37,10 +33,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (fabricPayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(fabricPayloadCache));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -49,17 +41,20 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var list = new ArrayList<FabricRecipeEntry>();
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
var seen = new HashSet<RecipeSerializer<?>>();
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
var groupedRecipes = RecipeGrouping.groupBy(
|
|
||||||
recipeMap.values(), holder -> holder.value().getSerializer());
|
|
||||||
|
|
||||||
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
if (!seen.add(serializer)) {
|
if (!seen.add(serializer)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<RecipeHolder<?>> recipes = groupedRecipes.get(serializer);
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (recipes != null && !recipes.isEmpty()) {
|
if (!recipes.isEmpty()) {
|
||||||
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
}
|
}
|
||||||
@@ -71,18 +66,13 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getFabricCodec().encode(buffer, payload);
|
getFabricCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
fabricPayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -101,11 +91,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (neoForgePayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(neoForgePayloadCache));
|
|
||||||
sendTags(serverPlayer, server);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -120,38 +105,23 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getNeoForgeStreamCodec().encode(buffer, payload);
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
neoForgePayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
sendTags(serverPlayer, server);
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void clearCache() {
|
|
||||||
fabricPayloadCache = null;
|
|
||||||
neoForgePayloadCache = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendTags(ServerPlayer serverPlayer, MinecraftServer server) {
|
|
||||||
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
|
||||||
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import org.gradle.api.attributes.java.TargetJvmVersion
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
id 'io.papermc.paperweight.userdev'
|
id 'io.papermc.paperweight.userdev'
|
||||||
@@ -15,20 +13,15 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api project(':compat-api')
|
api project(':compat-api')
|
||||||
paperweight.paperDevBundle('26.2.build.87-stable')
|
paperweight.paperDevBundle('26.2.build.31-alpha')
|
||||||
}
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
}
|
}
|
||||||
|
|
||||||
configurations.configureEach {
|
|
||||||
attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 25)
|
|
||||||
}
|
|
||||||
|
|
||||||
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.getMOJANG_PRODUCTION()
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
tasks.withType(JavaCompile).configureEach {
|
||||||
options.encoding = 'UTF-8'
|
options.encoding = 'UTF-8'
|
||||||
options.release.set(21)
|
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-44
@@ -1,7 +1,6 @@
|
|||||||
package cn.infstar.essentialsC.v26_2.jei;
|
package cn.infstar.essentialsC.v26_2.jei;
|
||||||
|
|
||||||
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
import cn.infstar.essentialsC.compat.jei.JeiRecipeSyncAdapter;
|
||||||
import cn.infstar.essentialsC.compat.jei.RecipeGrouping;
|
|
||||||
import io.netty.buffer.Unpooled;
|
import io.netty.buffer.Unpooled;
|
||||||
import net.minecraft.core.registries.BuiltInRegistries;
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
@@ -23,9 +22,6 @@ import java.util.logging.Logger;
|
|||||||
|
|
||||||
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
||||||
|
|
||||||
private DiscardedPayload fabricPayloadCache;
|
|
||||||
private DiscardedPayload neoForgePayloadCache;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
public void sendFabricRecipeSync(Player player, Logger logger, boolean debug) {
|
||||||
@@ -37,10 +33,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (fabricPayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(fabricPayloadCache));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -49,17 +41,20 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var list = new ArrayList<FabricRecipeEntry>();
|
var list = new ArrayList<FabricRecipeEntry>();
|
||||||
var seen = new HashSet<RecipeSerializer<?>>();
|
var seen = new HashSet<RecipeSerializer<?>>();
|
||||||
var groupedRecipes = RecipeGrouping.groupBy(
|
|
||||||
recipeMap.values(), holder -> holder.value().getSerializer());
|
|
||||||
|
|
||||||
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
for (RecipeSerializer<?> serializer : BuiltInRegistries.RECIPE_SERIALIZER) {
|
||||||
if (!seen.add(serializer)) {
|
if (!seen.add(serializer)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<RecipeHolder<?>> recipes = groupedRecipes.get(serializer);
|
List<RecipeHolder<?>> recipes = new ArrayList<>();
|
||||||
|
for (RecipeHolder<?> holder : recipeMap.values()) {
|
||||||
|
if (holder.value().getSerializer() == serializer) {
|
||||||
|
recipes.add(holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (recipes != null && !recipes.isEmpty()) {
|
if (!recipes.isEmpty()) {
|
||||||
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
RecipeSerializer<?> entrySerializer = recipes.get(0).value().getSerializer();
|
||||||
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
list.add(new FabricRecipeEntry(entrySerializer, recipes));
|
||||||
}
|
}
|
||||||
@@ -71,18 +66,13 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getFabricCodec().encode(buffer, payload);
|
getFabricCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
Identifier id = Identifier.fromNamespaceAndPath("fabric", "recipe_sync");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
fabricPayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -101,11 +91,6 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (neoForgePayloadCache != null) {
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(neoForgePayloadCache));
|
|
||||||
sendTags(serverPlayer, server);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
RecipeMap recipeMap = server.getRecipeManager().recipes;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
@@ -120,38 +105,23 @@ public final class JeiRecipeSyncAdapterImpl implements JeiRecipeSyncAdapter {
|
|||||||
|
|
||||||
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
var payload = createNeoForgePayload(allRecipeTypes, recipeMap);
|
||||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), server.registryAccess());
|
||||||
byte[] bytes;
|
|
||||||
try {
|
|
||||||
getNeoForgeStreamCodec().encode(buffer, payload);
|
getNeoForgeStreamCodec().encode(buffer, payload);
|
||||||
bytes = new byte[buffer.writerIndex()];
|
|
||||||
|
byte[] bytes = new byte[buffer.writerIndex()];
|
||||||
buffer.getBytes(0, bytes);
|
buffer.getBytes(0, bytes);
|
||||||
} finally {
|
|
||||||
buffer.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
Identifier id = Identifier.fromNamespaceAndPath("neoforge", "recipe_content");
|
||||||
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
DiscardedPayload discardedPayload = new DiscardedPayload(id, bytes);
|
||||||
neoForgePayloadCache = discardedPayload;
|
|
||||||
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
serverPlayer.connection.send(new ClientboundCustomPayloadPacket(discardedPayload));
|
||||||
sendTags(serverPlayer, server);
|
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
||||||
|
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
||||||
|
));
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
logger.info("已发送 NeoForge 配方同步 [" + id + "], 大小: " + bytes.length + " bytes");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void clearCache() {
|
|
||||||
fabricPayloadCache = null;
|
|
||||||
neoForgePayloadCache = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendTags(ServerPlayer serverPlayer, MinecraftServer server) {
|
|
||||||
serverPlayer.connection.send(new net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket(
|
|
||||||
net.minecraft.tags.TagNetworkSerialization.serializeTagsToNetwork(server.registries())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings({"unchecked", "deprecation"})
|
@SuppressWarnings({"unchecked", "deprecation"})
|
||||||
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
private net.minecraft.network.codec.StreamCodec<RegistryFriendlyByteBuf, FabricRecipeSyncPayload> getFabricCodec() {
|
||||||
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
return FabricRecipeEntry.CODEC.apply(net.minecraft.network.codec.ByteBufCodecs.list())
|
||||||
|
|||||||
Reference in New Issue
Block a user