405 lines
18 KiB
Java
405 lines
18 KiB
Java
package Sdf1_login;
|
||
|
||
import com.google.gson.JsonElement;
|
||
import com.google.gson.JsonObject;
|
||
import com.google.gson.JsonParser;
|
||
import org.bukkit.entity.Player;
|
||
import org.bukkit.plugin.java.JavaPlugin;
|
||
|
||
import java.io.File;
|
||
import java.io.IOException;
|
||
import java.nio.file.Files;
|
||
import java.nio.file.Paths;
|
||
import java.time.LocalDateTime;
|
||
import java.time.format.DateTimeFormatter;
|
||
import java.util.HashSet;
|
||
import java.util.List;
|
||
import java.util.Locale;
|
||
import java.util.Set;
|
||
|
||
/**
|
||
* 125 续15l-2 用户协议拒签名单 deny.json 管理器。
|
||
*
|
||
* 职责:
|
||
* 1. 玩家进入(CustomScreenManager.checkAndShowPending 入口)时检查 用户协议/deny.json
|
||
* 是否命中当前玩家名(精确匹配或 * 通配符);命中则不弹自定义屏幕,直接按
|
||
* 正常拒签话术踢出(沿用 用户协议/action.json 的 denyAction,默认 kick)。
|
||
* 2. 监听 ban/通配封禁.json 中 endtime=0(永久)或 endtime-starttime≥10年 的条目,
|
||
* 把对应通配模式懒加载到内存;玩家进入时重新扫一遍该文件(指纹未变则直接复用
|
||
* 上次内存结果,不读磁盘)——这是“玩家加入时懒重载”语义。
|
||
* 3. 手动在 deny.json 里追加的条目(如 "steve_*")同样支持通配符。
|
||
*
|
||
* 说明:deny.json 中若包含中文说明文本,本管理器只识别纯用户名/通配模式字符串,
|
||
* 说明文本会被静默忽略(不参与匹配、不报错)。
|
||
*/
|
||
public class DenyListManager {
|
||
|
||
|
||
private final JavaPlugin plugin;
|
||
private final File denyJson;
|
||
private final File wildcardBanJson;
|
||
|
||
/** 手动维护的 用户协议/deny.json 里解析出的用户/通配模式(小写)。 */
|
||
private Set<String> cachedManualPatterns = new HashSet<>();
|
||
/** ban/通配封禁.json 里满足 永久/≥10年 的 user 通配模式(小写)。 */
|
||
private Set<String> cachedWildcardBanPatterns = new HashSet<>();
|
||
private String manualFp = "";
|
||
private String wildcardFp = "";
|
||
private boolean loadedOnce = false;
|
||
|
||
private static final String WILDCARD_BAN_FILE = "ban/通配封禁.json";
|
||
|
||
public DenyListManager(JavaPlugin plugin) {
|
||
this.plugin = plugin;
|
||
this.denyJson = new File(plugin.getDataFolder(), "用户协议/deny.json");
|
||
this.wildcardBanJson = new File(plugin.getDataFolder(), WILDCARD_BAN_FILE);
|
||
ensureDenyJsonExists();
|
||
ensureWildcardBanJsonExists();
|
||
}
|
||
|
||
/**
|
||
* 玩家进入时调用:
|
||
* 1. 懒重载通配封禁文件到内存模式;
|
||
* 2. 若当前玩家命中任意模式 → 返回 true(调用方应直接踢出/拒绝,不弹屏);
|
||
* 3. 未命中 → false。
|
||
*/
|
||
public boolean isDenied(Player p) {
|
||
if (p == null) return false;
|
||
reloadWildcardBans();
|
||
String name = p.getName().toLowerCase(Locale.ROOT);
|
||
for (String pattern : cachedManualPatterns) {
|
||
if (matches(name, pattern)) return true;
|
||
}
|
||
for (String pattern : cachedWildcardBanPatterns) {
|
||
if (matches(name, pattern)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** 供外部(如 /reg 回执锁)查询某玩家是否命中 deny 集合。 */
|
||
public boolean isDeniedName(String playerName) {
|
||
reloadWildcardBans();
|
||
String name = playerName == null ? "" : playerName.toLowerCase(Locale.ROOT);
|
||
for (String pattern : cachedManualPatterns) {
|
||
if (matches(name, pattern)) return true;
|
||
}
|
||
for (String pattern : cachedWildcardBanPatterns) {
|
||
if (matches(name, pattern)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 懒重载:读 用户协议/deny.json + ban/通配封禁.json,刷新内存 cachedPatterns。
|
||
* 玩家加入时由 isDenied 调用;指纹未变时跳过磁盘读。
|
||
*/
|
||
private void reloadWildcardBans() {
|
||
String mfp = fingerprint(denyJson);
|
||
String wfp = fingerprint(wildcardBanJson);
|
||
boolean changed = !mfp.equals(manualFp) || !wfp.equals(wildcardFp);
|
||
if (loadedOnce && !changed) return;
|
||
|
||
// 1) 手动维护的 用户协议/deny.json
|
||
cachedManualPatterns = filterPatterns(loadStringPatterns(denyJson));
|
||
|
||
// 2) ban/通配封禁.json 中满足 永久 或 ≥10年 的 user 通配模式
|
||
cachedWildcardBanPatterns = filterPatterns(loadLongBanPatterns(wildcardBanJson));
|
||
|
||
manualFp = mfp;
|
||
wildcardFp = wfp;
|
||
loadedOnce = true;
|
||
plugin.getLogger().info("[拒签名单] 懒重载完成:用户协议/deny.json + " + WILDCARD_BAN_FILE
|
||
+ ",生效手动模式 " + cachedManualPatterns.size() + " 条"
|
||
+ ",生效通配封禁模式 " + cachedWildcardBanPatterns.size() + " 条"
|
||
+ "(" + joinAll() + ")");
|
||
}
|
||
|
||
private String joinAll() {
|
||
java.util.Set<String> all = new java.util.HashSet<>();
|
||
all.addAll(cachedManualPatterns);
|
||
all.addAll(cachedWildcardBanPatterns);
|
||
return String.join(", ", all);
|
||
}
|
||
|
||
private Set<String> filterPatterns(java.util.Set<String> raw) {
|
||
java.util.Set<String> clean = new java.util.HashSet<>();
|
||
for (String p : raw) {
|
||
if (p == null) continue;
|
||
p = p.trim().toLowerCase(Locale.ROOT);
|
||
if (p.isEmpty()) continue;
|
||
// 说明性文本通常包含中文、空格或“年/月/封禁”等关键词;
|
||
// 纯用户名/通配模式(如 steve_*、2111_*)不含空格/中文/关键词,全部保留。
|
||
if (p.contains(" ") || p.contains("年") || p.contains("月") || p.contains("封禁")
|
||
|| containsChinese(p)) {
|
||
continue;
|
||
}
|
||
clean.add(p);
|
||
}
|
||
return clean;
|
||
}
|
||
|
||
/** 是否包含中文(CJK 统一表意文字范围)。 */
|
||
private static boolean containsChinese(String s) {
|
||
for (int i = 0; i < s.length(); i++) {
|
||
char c = s.charAt(i);
|
||
if (c >= 0x4E00 && c <= 0x9FFF) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** 读 用户协议/deny.json 的字符串数组(支持说明文本,自动过滤)。 */
|
||
private Set<String> loadStringPatterns(File f) {
|
||
Set<String> out = new HashSet<>();
|
||
try {
|
||
byte[] bytes = Files.readAllBytes(Paths.get(f.getAbsolutePath()));
|
||
String txt = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
|
||
JsonElement root = JsonParser.parseString(txt);
|
||
if (root.isJsonArray()) {
|
||
for (JsonElement el : root.getAsJsonArray()) {
|
||
if (el != null && el.isJsonPrimitive()) {
|
||
out.add(el.getAsString());
|
||
}
|
||
}
|
||
} else if (root.isJsonObject()) {
|
||
// 兼容对象数组 [{name:...}] / [{user:...}]
|
||
JsonElement arr = root.getAsJsonObject().get("items");
|
||
if (arr != null && arr.isJsonArray()) {
|
||
for (JsonElement el : arr.getAsJsonArray()) {
|
||
if (el == null || !el.isJsonObject()) continue;
|
||
JsonElement obj = el;
|
||
String u = obj.getAsJsonObject().has("user")
|
||
? obj.getAsJsonObject().get("user").getAsString()
|
||
: obj.getAsJsonObject().get("name").getAsString();
|
||
out.add(u);
|
||
}
|
||
}
|
||
}
|
||
} catch (Exception ex) {
|
||
plugin.getLogger().warning("[拒签名单] 读取 " + f.getName() + " 失败: " + ex.getMessage());
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 读 ban/通配封禁.json,筛选 永久(endtime=0)或 跨度≥10年 的 user 模式。 */
|
||
private Set<String> loadLongBanPatterns(File f) {
|
||
Set<String> out = new HashSet<>();
|
||
if (!f.exists()) return out;
|
||
try {
|
||
byte[] bytes = Files.readAllBytes(Paths.get(f.getAbsolutePath()));
|
||
String txt = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
|
||
JsonElement root = JsonParser.parseString(txt);
|
||
if (!root.isJsonArray()) return out;
|
||
|
||
long now = System.currentTimeMillis();
|
||
long tenYearsMs = 10L * 365L * 24 * 3600 * 1000;
|
||
|
||
for (JsonElement el : root.getAsJsonArray()) {
|
||
if (el == null || !el.isJsonObject()) continue;
|
||
JsonObject obj = el.getAsJsonObject();
|
||
String user = str(obj, "user");
|
||
if (user.isEmpty()) continue;
|
||
|
||
int endtime = 0;
|
||
if (obj.has("endtime") && !obj.get("endtime").isJsonNull()) {
|
||
try { endtime = obj.get("endtime").getAsInt(); } catch (Exception ignored) {}
|
||
}
|
||
String starttime = str(obj, "starttime");
|
||
|
||
boolean permanent = (endtime == 0);
|
||
boolean longBan = false;
|
||
if (!permanent) {
|
||
long startMs = parseTime(starttime, now);
|
||
long endMs = endtime; // 文件里 endtime 为秒或毫秒?见下方注释
|
||
// 兼容:endtime 若 10 位按秒处理,13 位按毫秒处理
|
||
if (endtime > 0 && endtime < 100_000_000_000L) {
|
||
endMs = endtime * 1000L;
|
||
}
|
||
if (startMs > 0 && endMs > 0) {
|
||
long span = endMs - startMs;
|
||
if (span >= tenYearsMs) longBan = true;
|
||
} else {
|
||
// 时间戳解析失败但 endtime>0 → 保守按“长封禁”处理(≥10 年或未知)
|
||
longBan = endMs >= now + tenYearsMs;
|
||
}
|
||
}
|
||
|
||
if (permanent || longBan) {
|
||
out.add(user);
|
||
}
|
||
}
|
||
} catch (Exception ex) {
|
||
plugin.getLogger().warning("[拒签名单] 读取 " + WILDCARD_BAN_FILE + " 失败: " + ex.getMessage());
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 通配符匹配:支持 *(任意串),其余字符精确;不含 * 则 equals。 */
|
||
private static boolean matches(String name, String pattern) {
|
||
if (name == null || pattern == null) return false;
|
||
name = name.toLowerCase(Locale.ROOT);
|
||
pattern = pattern.toLowerCase(Locale.ROOT);
|
||
if (!pattern.contains("*")) {
|
||
return name.equals(pattern);
|
||
}
|
||
String[] parts = pattern.split("\\*", -1);
|
||
StringBuilder regex = new StringBuilder();
|
||
for (int i = 0; i < parts.length; i++) {
|
||
if (i > 0) regex.append(".*");
|
||
regex.append(java.util.regex.Pattern.quote(parts[i]));
|
||
}
|
||
return java.util.regex.Pattern.compile(regex.toString()).matcher(name).matches();
|
||
}
|
||
|
||
/** 文件指纹:长度 + 内容 hash,用于懒重载判变。 */
|
||
private String fingerprint(File f) {
|
||
if (f == null || !f.exists()) return "missing";
|
||
try {
|
||
byte[] bytes = Files.readAllBytes(Paths.get(f.getAbsolutePath()));
|
||
return f.length() + "B/" + java.util.Arrays.hashCode(bytes);
|
||
} catch (Exception ex) {
|
||
return "err:" + ex.getMessage();
|
||
}
|
||
}
|
||
|
||
private static String str(JsonElement obj, String key) {
|
||
JsonElement el = obj.getAsJsonObject().get(key);
|
||
return (el == null || el.isJsonNull()) ? "" : el.getAsString();
|
||
}
|
||
|
||
/**
|
||
* 解析中文时间 "2026年11月21日 12点15分" → 毫秒;失败返回 fallback。
|
||
* 兼容 "yyyy年MM月dd日 HH点mm分"、ISO 格式、纯数字时间戳。
|
||
*/
|
||
private long parseTime(String s, long fallback) {
|
||
if (s == null || s.trim().isEmpty()) return 0;
|
||
s = s.trim();
|
||
// 纯数字时间戳
|
||
if (s.matches("\\d+")) {
|
||
long v = Long.parseLong(s);
|
||
return v < 100_000_000_000L ? v * 1000L : v;
|
||
}
|
||
// 中文格式
|
||
try {
|
||
String norm = s
|
||
.replace("年", "-")
|
||
.replace("月", "-")
|
||
.replace("日", " ")
|
||
.replace("点", ":")
|
||
.replace("分", "");
|
||
if (norm.endsWith(":")) norm = norm + "00";
|
||
String[] bits = norm.trim().split("\\s+");
|
||
String datePart = bits.length > 0 ? bits[0] : "";
|
||
String timePart = bits.length > 1 ? bits[1] : "00:00:00";
|
||
if (!timePart.matches("\\d{1,2}:\\d{2}(:\\d{2})?")) {
|
||
// 若拆成 3 段(时:分:秒 被空格分开),重新拼
|
||
if (bits.length >= 4) {
|
||
timePart = bits[1] + ":" + bits[2] + (bits.length >= 5 ? ":" + bits[3] : ":00");
|
||
}
|
||
}
|
||
if (timePart.equals("00:00:00") && bits.length == 1) {
|
||
// 只有日期,补 00:00:00
|
||
timePart = "00:00:00";
|
||
}
|
||
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||
LocalDateTime ldt = LocalDateTime.parse(datePart + " " + timePart, fmt);
|
||
return ldt.toInstant(java.time.ZoneOffset.of("+8")).toEpochMilli();
|
||
} catch (Exception ex) {
|
||
plugin.getLogger().fine("[拒签名单] 时间解析失败: " + s + " → " + ex.getMessage());
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
public void addDeny(String playerName, String reason) {
|
||
if (playerName == null || playerName.isEmpty()) return;
|
||
String entry = playerName.trim().toLowerCase(Locale.ROOT);
|
||
if (entry.isEmpty()) return;
|
||
|
||
// 1) 如果该玩家已被永久/10年封禁(在 cachedWildcardBanPatterns 里),则不重复写 deny.json
|
||
// 2) 否则写入 deny.json
|
||
reloadWildcardBans();
|
||
if (cachedWildcardBanPatterns.contains(entry)) {
|
||
plugin.getLogger().info("[拒签名单] " + entry + " 已存在于 ban/通配封禁.json(永久/10年封禁),跳过写入 用户协议/deny.json");
|
||
return;
|
||
}
|
||
|
||
// 读现有 deny.json,追加到数组里(保持简单字符串数组格式)
|
||
List<String> existing = loadStringPatternsRaw(denyJson);
|
||
if (existing.contains(entry)) {
|
||
plugin.getLogger().info("[拒签名单] " + entry + " 已存在于 用户协议/deny.json,跳过写入");
|
||
return;
|
||
}
|
||
existing.add(entry);
|
||
writeDenyJson(existing, reason);
|
||
plugin.getLogger().info("[拒签名单] 玩家 " + entry + " 已写入 用户协议/deny.json(" + reason + ")");
|
||
}
|
||
|
||
/** 读 deny.json 的原始字符串数组(不去重过滤,保留说明文本)。 */
|
||
private List<String> loadStringPatternsRaw(File f) {
|
||
List<String> out = new java.util.ArrayList<>();
|
||
if (!f.exists()) return out;
|
||
try {
|
||
byte[] bytes = Files.readAllBytes(Paths.get(f.getAbsolutePath()));
|
||
String txt = new String(bytes, java.nio.charset.StandardCharsets.UTF_8).trim();
|
||
if (txt.isEmpty()) return out;
|
||
JsonElement root = JsonParser.parseString(txt);
|
||
if (root.isJsonArray()) {
|
||
for (JsonElement el : root.getAsJsonArray()) {
|
||
if (el != null && el.isJsonPrimitive()) {
|
||
out.add(el.getAsString());
|
||
}
|
||
}
|
||
} else {
|
||
out.add(txt); // 非数组时原样保留(避免数据丢失)
|
||
}
|
||
} catch (Exception ex) {
|
||
plugin.getLogger().warning("[拒签名单] 读取 用户协议/deny.json 原始内容失败: " + ex.getMessage());
|
||
}
|
||
return out;
|
||
}
|
||
|
||
private void writeDenyJson(List<String> values, String reason) {
|
||
try {
|
||
File parent = denyJson.getParentFile();
|
||
if (!parent.exists()) parent.mkdirs();
|
||
StringBuilder sb = new StringBuilder();
|
||
sb.append("[\n");
|
||
com.google.gson.Gson gson = new com.google.gson.Gson();
|
||
for (int i = 0; i < values.size(); i++) {
|
||
sb.append(" ").append(gson.toJson(values.get(i)));
|
||
if (i < values.size() - 1) sb.append(",");
|
||
sb.append("\n");
|
||
}
|
||
sb.append("]");
|
||
Files.write(denyJson.toPath(), sb.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||
} catch (IOException ex) {
|
||
plugin.getLogger().severe("[拒签名单] 写入 用户协议/deny.json 失败: " + ex.getMessage());
|
||
}
|
||
}
|
||
|
||
private void ensureDenyJsonExists() {
|
||
File parent = denyJson.getParentFile();
|
||
if (!parent.exists()) parent.mkdirs();
|
||
if (!denyJson.exists()) {
|
||
try {
|
||
Files.write(denyJson.toPath(), new byte[0]);
|
||
plugin.getLogger().info("[拒签名单] 已创建空的 用户协议/deny.json");
|
||
} catch (IOException ex) {
|
||
plugin.getLogger().warning("[拒签名单] 创建 用户协议/deny.json 失败: " + ex.getMessage());
|
||
}
|
||
}
|
||
}
|
||
|
||
private void ensureWildcardBanJsonExists() {
|
||
File parent = wildcardBanJson.getParentFile();
|
||
if (!parent.exists()) parent.mkdirs();
|
||
if (!wildcardBanJson.exists()) {
|
||
try {
|
||
Files.write(wildcardBanJson.toPath(),
|
||
"[\n {\n \"time\": \"\",\n \"user\": \"\",\n \"msg\": \"\",\n \"starttime\": \"\",\n \"endtime\": 0\n }\n]".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||
plugin.getLogger().info("[拒签名单] 已创建空的 ban/通配封禁.json 模板");
|
||
} catch (IOException ex) {
|
||
plugin.getLogger().warning("[拒签名单] 创建 ban/通配封禁.json 失败: " + ex.getMessage());
|
||
}
|
||
}
|
||
}
|
||
} |