Files
ItxiaohuiServerAdvancements/src/main/java/top/itxiaohui/serveradvancements/config/ConfigurationManager.java
T

242 lines
16 KiB
Java

package top.itxiaohui.serveradvancements.config;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import top.itxiaohui.serveradvancements.model.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import org.bukkit.entity.EntityType;
public final class ConfigurationManager {
private static final Pattern ID_PATTERN = Pattern.compile("[a-z0-9._/-]+");
private final JavaPlugin plugin;
private LinkedHashMap<String, AchievementDefinition> definitions = new LinkedHashMap<>();
private ValidationResult lastValidation = new ValidationResult(List.of(), List.of());
private long revision;
public ConfigurationManager(JavaPlugin plugin) { this.plugin = plugin; }
public LoadResult load() {
File file = new File(plugin.getDataFolder(), "advancements.yml");
LinkedHashMap<String, AchievementDefinition> loaded = new LinkedHashMap<>();
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
YamlConfiguration yaml;
try { yaml = StrictYaml.read(file.toPath(), true); }
catch (IOException error) { return new LoadResult(loaded, new ValidationResult(List.of(error.getMessage()), List.of())); }
ConfigurationSection root = yaml.getConfigurationSection("achievements");
if (root == null) {
errors.add("advancements.yml: 缺少 achievements 节点");
return new LoadResult(loaded, new ValidationResult(errors, warnings));
}
for (String id : root.getKeys(false)) {
ConfigurationSection section = root.getConfigurationSection(id);
if (section == null) continue;
try {
AchievementDefinition definition = parse(id, section);
List<String> localErrors = validateOne(definition);
if (localErrors.isEmpty()) loaded.put(id, definition);
else localErrors.forEach(error -> errors.add("advancements.yml 成就 " + id + ": " + error));
} catch (RuntimeException exception) {
errors.add("advancements.yml 成就 " + id + ": " + exception.getMessage());
}
}
validateGraph(loaded, errors);
if (loaded.values().stream().anyMatch(definition -> definition.x() != 0 || definition.y() != 0))
warnings.add("display.x/y 仅作为定义排序提示;原版客户端自动计算节点坐标");
ValidationResult result = new ValidationResult(List.copyOf(errors), List.copyOf(warnings));
return new LoadResult(loaded, result);
}
public boolean apply(LoadResult result) {
lastValidation = result.validation();
if (!result.validation().valid()) return false;
definitions = result.definitions();
revision++;
return true;
}
public void applyValidSubset(LoadResult result) {
lastValidation = result.validation();
definitions = result.definitions();
revision++;
}
private AchievementDefinition parse(String id, ConfigurationSection section) {
List<ConditionDefinition> conditions = new ArrayList<>();
for (Map<?, ?> raw : section.getMapList("conditions")) {
Map<String, Object> values = new LinkedHashMap<>();
raw.forEach((key, value) -> values.put(String.valueOf(key), value));
String type = String.valueOf(values.remove("type"));
conditions.add(new ConditionDefinition(ConditionType.parse(type), values));
}
ConfigurationSection reward = section.getConfigurationSection("rewards");
List<RewardDefinition.RewardItem> items = new ArrayList<>();
if (reward != null) {
for (Map<?, ?> raw : reward.getMapList("items")) {
items.add(new RewardDefinition.RewardItem(String.valueOf(raw.get("item")), strictInt(raw.get("amount"), 1)));
}
}
RewardDefinition rewards = new RewardDefinition(
reward == null ? 0 : strictInt(reward.get("experience"), 0),
List.copyOf(items), reward == null ? List.of() : List.copyOf(reward.getStringList("commands")),
reward != null && reward.getBoolean("allow-reclaim", plugin.getConfig().getBoolean("defaults.allow-reward-reclaim", false)),
reward == null ? "" : reward.getString("completion-message", ""));
ConfigurationSection display = section.getConfigurationSection("display");
return new AchievementDefinition(id, section.getString("name", id), section.getString("description", ""),
section.getString("icon", "minecraft:stone"), AdvancementFrame.parse(section.getString("frame", "task")),
section.getString("parent", "root").equals(rootId()) ? "root" : section.getString("parent", "root"), display == null ? 0 : display.getDouble("x"),
display == null ? 0 : display.getDouble("y"), List.copyOf(conditions),
section.getBoolean("hidden", false),
section.getBoolean("show-toast", plugin.getConfig().getBoolean("defaults.show-toast", true)),
section.getBoolean("announce-chat", plugin.getConfig().getBoolean("defaults.announce-chat", false)),
section.getBoolean("enabled", true), rewards);
}
private int strictInt(Object value, int fallback) {
if (value == null) return fallback;
if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue()) || number.doubleValue() != number.intValue())
throw new IllegalArgumentException("整数配置非法: " + value);
return number.intValue();
}
public String rootId() { return plugin.getConfig().getString("root.id", "root"); }
public long revision() { return revision; }
public static boolean validId(String id) {
return id != null && id.length() <= 128 && ID_PATTERN.matcher(id).matches()
&& Arrays.stream(id.split("/", -1)).noneMatch(part -> part.isEmpty() || part.equals(".") || part.equals(".."));
}
private List<String> validateOne(AchievementDefinition definition) {
List<String> errors = new ArrayList<>();
if (!validId(definition.id()) || definition.id().equals("root") || definition.id().equals(rootId()))
errors.add("ID 非法,只允许小写字母、数字、._/-");
Material icon = Material.matchMaterial(definition.icon());
if (NamespacedKey.fromString(definition.icon()) == null || icon == null || !icon.isItem()) errors.add("图标不是有效物品: " + definition.icon());
if (definition.conditions().isEmpty()) errors.add("至少需要一个条件");
if (definition.conditions().size() > 64 || definition.name().length() > 256 || definition.description().length() > 2048
|| !Double.isFinite(definition.x()) || !Double.isFinite(definition.y())) errors.add("条件数量、显示文字长度或坐标非法");
for (ConditionDefinition condition : definition.conditions()) {
errors.addAll(top.itxiaohui.serveradvancements.condition.AutomaticConditions.validate(condition));
if (!Double.isFinite(condition.target()) || condition.target() <= 0) errors.add("条件 " + condition.type() + " 的目标必须为正有限数且单位有效");
String materialKey = switch (condition.type()) {
case MINE_BLOCK -> condition.string("block", "");
case COLLECT_ITEM, OBTAIN_ITEM, CRAFT_ITEM -> condition.string("item", "");
default -> null;
};
if (materialKey != null) {
Material material = Material.matchMaterial(materialKey);
if (NamespacedKey.fromString(materialKey) == null || material == null
|| (condition.type() == ConditionType.MINE_BLOCK ? !material.isBlock() : !material.isItem()))
errors.add("条件 " + condition.type() + " 的物品/方块无效: " + materialKey);
}
if (condition.type() == ConditionType.KILL_MOB || condition.type() == ConditionType.BREED_MOB) {
String entity = condition.string("entity", "");
if (!entity.equals("*")) {
if (Arrays.stream(EntityType.values()).noneMatch(type -> type.isAlive() && type.getKey().toString().equals(entity))) errors.add("生物 ID 无效: " + entity);
}
}
if (condition.type() == ConditionType.VISIT_DIMENSION && NamespacedKey.fromString(condition.string("dimension", "")) == null) errors.add("维度 ID 无效");
if (condition.type() == ConditionType.REACH_LOCATION) {
if (condition.string("world", "").isBlank()) errors.add("区域必须指定 world");
for (String axis : List.of("x", "y", "z")) if (!condition.parameters().containsKey(axis) || !Double.isFinite(condition.number(axis, Double.NaN))) errors.add("区域必须指定有限坐标 " + axis);
if (!Double.isFinite(condition.number("radius", 5)) || condition.number("radius", 5) < 0) errors.add("区域半径非法");
}
}
if (definition.rewards().experience() < 0 || definition.rewards().experience() > 1_000_000) errors.add("经验奖励必须为 0 到 1000000");
if (definition.rewards().items().size() > 64 || definition.rewards().commands().size() > 64) errors.add("奖励条目过多");
for (String command : definition.rewards().commands()) if (command.isBlank() || command.length() > 1024 || command.contains("\n") || command.contains("\r")) errors.add("奖励命令为空、超长或包含换行");
for (RewardDefinition.RewardItem item : definition.rewards().items()) {
Material material = Material.matchMaterial(item.material());
if (material == null || !material.isItem() || item.amount() < 1 || item.amount() > 4096)
errors.add("奖励物品无效: " + item.material() + " x" + item.amount());
}
return errors;
}
private void validateGraph(Map<String, AchievementDefinition> map, List<String> errors) {
Map<String, Set<String>> dependencies = new HashMap<>();
Map<String, List<String>> consumers = new HashMap<>();
Set<String> invalid = new HashSet<>(); Map<String, Integer> indegree = new HashMap<>();
for (AchievementDefinition definition : map.values()) {
Set<String> required = new HashSet<>();
if (!definition.parent().equals("root")) required.add(definition.parent());
for (ConditionDefinition c : definition.conditions()) if (c.type() == ConditionType.COMPLETE_ACHIEVEMENT) required.add(c.string("achievement", ""));
dependencies.put(definition.id(), required); indegree.put(definition.id(), required.size());
for (String dependency : required) {
consumers.computeIfAbsent(dependency, ignored -> new ArrayList<>()).add(definition.id());
AchievementDefinition parent = map.get(dependency);
if (parent == null || definition.enabled() && !parent.enabled()) invalid.add(definition.id());
}
}
Deque<String> ready = new ArrayDeque<>(); indegree.forEach((id, count) -> { if (count == 0) ready.add(id); });
Set<String> visited = new HashSet<>(); Map<String, Integer> depth = new HashMap<>();
while (!ready.isEmpty()) {
String id = ready.remove(); visited.add(id);
int level = map.get(id).parent().equals("root") ? 1 : depth.getOrDefault(map.get(id).parent(), 0) + 1;
depth.put(id, level); if (level > 256) invalid.add(id);
for (String consumer : consumers.getOrDefault(id, List.of())) if (indegree.compute(consumer, (key, count) -> count - 1) == 0) ready.add(consumer);
}
for (String id : map.keySet()) if (!visited.contains(id)) invalid.add(id);
ready.addAll(invalid);
while (!ready.isEmpty()) for (String consumer : consumers.getOrDefault(ready.remove(), List.of())) if (invalid.add(consumer)) ready.add(consumer);
for (String id : invalid) { errors.add("成就 " + id + ": 依赖缺失、禁用、循环或树深度超过 256,已隔离"); map.remove(id); }
}
public Map<String, AchievementDefinition> definitions() { return Collections.unmodifiableMap(definitions); }
public AchievementDefinition get(String id) { return definitions.get(id); }
public ValidationResult lastValidation() { return lastValidation; }
public boolean createSkeleton(String id) throws IOException {
if (!validId(id) || id.equals("root") || id.equals(rootId())) return false;
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements"); if (root == null) root = yaml.createSection("achievements");
if (root.contains(id)) return false;
ConfigurationSection node = root.createSection(id);
node.set("name", id); node.set("description", "请编辑成就描述"); node.set("icon", "minecraft:stone"); node.set("frame", "task"); node.set("parent", "root");
node.set("enabled", false); node.set("conditions", List.of(Map.of("type", "manual")));
ConfigurationSection display = node.createSection("display"); display.set("x", 1); display.set("y", 0);
ConfigurationSection reward = node.createSection("rewards"); reward.set("experience", 0); reward.set("items", List.of()); reward.set("commands", List.of());
StrictYaml.save(yaml, file.toPath());
return true;
}
public DeleteResult delete(String id) throws IOException {
if (id.equals("root") || id.equals(rootId()) || !validId(id)) return new DeleteResult(false, "根进度不可删除或 ID 非法");
for (AchievementDefinition definition : definitions.values()) {
if (definition.parent().equals(id)) return new DeleteResult(false, "仍有子成就: " + definition.id());
}
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements");
if (root == null || !root.contains(id)) return new DeleteResult(false, "成就不存在");
for (String other : root.getKeys(false)) {
ConfigurationSection node = root.getConfigurationSection(other); if (node == null) continue;
if (node.getString("parent", "root").equals(id)) return new DeleteResult(false, "磁盘配置仍有子成就: " + other);
for (Map<?, ?> c : node.getMapList("conditions")) if ("complete_achievement".equals(c.get("type")) && id.equals(c.get("achievement"))) return new DeleteResult(false, "仍被条件引用: " + other);
}
root.set(id, null); StrictYaml.save(yaml, file.toPath());
return new DeleteResult(true, "");
}
public boolean setEnabled(String id, boolean enabled) throws IOException {
File file = new File(plugin.getDataFolder(), "advancements.yml");
YamlConfiguration yaml = StrictYaml.read(file.toPath(), true);
ConfigurationSection root = yaml.getConfigurationSection("achievements");
ConfigurationSection node = root == null ? null : root.getConfigurationSection(id);
if (node == null) return false;
node.set("enabled", enabled); StrictYaml.save(yaml, file.toPath());
return true;
}
public record LoadResult(LinkedHashMap<String, AchievementDefinition> definitions, ValidationResult validation) {}
public record DeleteResult(boolean success, String reason) {}
}