diff --git a/Auth/ApiKeyService.cs b/Auth/ApiKeyService.cs index 5741f09..6111463 100644 --- a/Auth/ApiKeyService.cs +++ b/Auth/ApiKeyService.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Security.Cryptography; using System.Text; +using SLDataAPI.Services; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -136,21 +137,32 @@ public static void Reload() } /// 校验明文 Key → 主体。失败 401;权限另检 403。 - public static bool TryAuthenticate(string ip, string? plaintextKey, out ApiKeyPrincipal? principal, out string error) + public static bool TryAuthenticate(string ip, string? plaintextKey, out ApiKeyPrincipal? principal, out string error) => + TryAuthenticate(ip, plaintextKey, out principal, out error, out _); + + /// 校验明文 Key → 主体,同时返回稳定错误码(不随 language 变化)。 + public static bool TryAuthenticate(string ip, string? plaintextKey, out ApiKeyPrincipal? principal, + out string error, out string errorCode) { principal = null; error = ""; + errorCode = ""; if (Control.ControlAuth.IsControlLocked(ip, out var remaining)) { - error = $"该来源已因多次鉴权失败被临时锁定,请 {Math.Ceiling(remaining.TotalSeconds)} 秒后重试"; + error = Localization.F("该来源已因多次鉴权失败被临时锁定,请 {0} 秒后重试", + "This source is temporarily locked after repeated authentication failures; retry in {0} seconds", + Math.Ceiling(remaining.TotalSeconds)); + errorCode = Localization.CodeAuthLocked; return false; } if (string.IsNullOrWhiteSpace(plaintextKey)) { Control.ControlAuth.RegisterControlFailure(ip); - error = "缺少 API Key(请使用 Authorization: Bearer 或 X-SLDataAPI-Key)"; + error = Localization.T("缺少 API Key(请使用 Authorization: Bearer 或 X-SLDataAPI-Key)", + "Missing API key (use Authorization: Bearer or X-SLDataAPI-Key)"); + errorCode = Localization.CodeUnauthorized; return false; } @@ -168,7 +180,8 @@ public static bool TryAuthenticate(string ip, string? plaintextKey, out ApiKeyPr if (hit == null) { Control.ControlAuth.RegisterControlFailure(ip); - error = "API Key 无效"; + error = Localization.T("API Key 无效", "Invalid API key"); + errorCode = Localization.CodeUnauthorized; return false; } diff --git a/Auth/RemoteCommandGuard.cs b/Auth/RemoteCommandGuard.cs index f483820..e431d8c 100644 --- a/Auth/RemoteCommandGuard.cs +++ b/Auth/RemoteCommandGuard.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using SLDataAPI.Services; namespace SLDataAPI.Auth; @@ -28,10 +29,13 @@ public static class RemoteCommandGuard /// 给上游平台的机器可读拒绝码。 public const string RemoteDenyCode = "sldataapi_cli_forbidden"; - /// 控制面拒绝文案(HTTP 403 / WS result 的 message)。 - public const string RemoteDenyMessage = - "拒绝执行:SLDataAPI 管理命令(sldataapi / slda)不允许通过远程控制通道执行。" + - "API Key 的创建与吊销只能在服务器本地控制台(LocalAdmin / RemoteAdmin / 游戏内控制台)操作。"; + /// 控制面拒绝文案(HTTP 403 / WS result 的 message),随 language 本地化。 + public static string RemoteDenyMessage => + Localization.T( + "拒绝执行:SLDataAPI 管理命令(sldataapi / slda)不允许通过远程控制通道执行。" + + "API Key 的创建与吊销只能在服务器本地控制台(LocalAdmin / RemoteAdmin / 游戏内控制台)操作。", + "Denied: SLDataAPI management commands (sldataapi / slda) cannot be executed through the remote control channel. " + + "API key creation and revocation are only available from the local server console (LocalAdmin / RemoteAdmin / in-game console)."); /// /// 命令是否会调起 SLDataAPI 管理 CLI。逐个空白分隔的 token 判定(不只看首 token, diff --git a/CHANGELOG.md b/CHANGELOG.md index da63781..085e021 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## 2.6.3 Saluton + +SLDataAPI **2.6.3 Saluton**(相对 2.6.2-patch Holiday26),发布日期 **2026-11-15**。以 GitHub **正式版(Latest)**发布,程序集版本 **2.6.3** / **2.6.3.0**,强名称签名(公钥令牌 `3ec73bb20070fa9c`)。本版本主题为接口输出多语言(中文 / 英文)与稳定机器码;默认 `zh-CN` 下既有输出逐字不变,旧版客户端无需改动。本版本按 **14.2.x / LabApi 1.1.7** 编译,不包含任何游戏 15.0 专有内容。 + +### 多语言(i18n) + +- 新增配置项 `language`:`zh-CN`(默认)或 `en`;大小写与首尾空白不敏感,非法值回退 `zh-CN` 并在启动日志告警;在插件启用时读取,修改后需重启服务器或重载插件 +- `zh-CN` 下所有 HTTP / WebSocket 输出与 2.6.2-patch 逐字一致:既有字段名、字段顺序、中文文本均不变,新增字段只追加在既有字段之后 +- `en` 下本插件生成的文本(回合阶段、核弹状态、阵营 / 角色名、控制面与语音提示、错误信息、控制台提示)输出英文 +- 玩家昵称、控制台回显、封禁 / 踢出 / 解封原因、日志内容、第三方插件返回内容等外部内容原样透传,不翻译 + +### 稳定 code 字段(不随语言变化) + +- `get_sl_data` 根对象:`phase_code`(`waiting` / `in_progress` / `ended`)、`warhead_code`(`inactive` / `armed` / `detonating` / `detonated`) +- `get_sl_data` 玩家项:`role_code`(`RoleTypeId` 枚举成员名,如 `Spectator` / `Tutorial` / `NtfCaptain`)、`team_code`(`Team` 枚举成员名,如 `ClassD` / `ChaosInsurgency` / `FoundationForces` / `SCPs` / `Dead` / `OtherAlive`) +- 语音 `/status` 的 speaker 项与 WS `speaker` 帧:`role_code` +- 错误响应顶层 `code`(snake_case):`timeout` / `symlink_forbidden` / `unauthorized` / `forbidden` / `not_found` / `invalid_argument` / `bad_request` / `method_not_allowed` / `payload_too_large` / `request_header_too_large` / `conflict` / `internal_error` / `not_implemented` / `service_unavailable` / `too_many_requests` / `operation_failed` / `auth_locked` / `token_not_configured` / `empty_response`;既有 `data.code` 机器码(如 `tls_required` / `transport_mismatch` / `holiday_inactive` / `feature_unavailable` / `dummy_limit` 等)原值提升为顶层 `code` +- 所有插件生成的 JSON 根对象新增 `lang`(`zh-CN` / `en`) +- `en` 下错误码推断先还原为中文文本再复用 `zh-CN` 规则,保证中英文 code 一致;错误响应补 `code` 时只在末尾追加,不重新序列化既有字段 +- 兼容说明:`zh-CN` 下回合结束仍显示「等待开始」(`phase_code` = `ended`),核弹拉杆已拉起但未倒计时仍显示「未激活」(`warhead_code` = `armed`) + +### 其他 + +- 控制台 `sldataapi` / `sldataapi apikey` 用法提示补充 `language` 与 code 字段说明;README 新增「多语言与稳定 code」章节(中英文) +- 新增本地化与错误码纯逻辑类及回归测试(`zh-CN` 逐字锁定、`en` 输出、全仓中英文文案对 code 一致性扫描、错误码追加不改既有字段),功能测试共 410 项全部通过 + +### 许可证 + +- 由 **GPL-3.0-only** 变更为 **Apache-2.0**(允许闭源使用;须保留版权 / SPDX 头、NOTICE,并注明来自 DNTOF/SLDataAPI;禁止删改署名后换皮发布)。语音转发 / 录音仍标注为本项目原创。详见 `LICENSE`、`NOTICE`、README「许可证」。 + +### English + +SLDataAPI **2.6.3 Saluton** (since 2.6.2-patch Holiday26), released **2026-11-15** as the GitHub **Latest** release. Assembly version **2.6.3** / **2.6.3.0**, strong-name signed (public key token `3ec73bb20070fa9c`). Built against **14.2.x / LabApi 1.1.7**; contains no game-15.0-specific content. + +- **Language setting**: new `language` config, `zh-CN` (default) or `en`. Invalid values fall back to `zh-CN` with a startup warning. Read when the plugin is enabled; restart the server or reload the plugin after changing it. +- **Backward compatible**: with `zh-CN`, every HTTP / WebSocket output is byte-for-byte identical to 2.6.2-patch (same field names, field order and Chinese text). New fields are only appended after existing ones. +- **English output**: with `en`, plugin-generated text (round phase, warhead status, team / role names, control and voice messages, errors, console hints) is in English. Player nicknames, console output, ban / kick / unban reasons, log contents and third-party plugin responses are passed through unchanged. +- **Stable codes** (independent of language): `phase_code`, `warhead_code` on the `get_sl_data` root; `role_code`, `team_code` on each player (enum member names); `role_code` on voice `/status` speakers and WS `speaker` frames; a top-level snake_case `code` on error responses (existing `data.code` values are promoted unchanged); and `lang` on every plugin-generated JSON root object. +- **Consistent error codes**: in `en`, error-code inference maps the message back to Chinese and reuses the `zh-CN` rules, so codes are identical in both languages. The `code` field is appended without re-serializing existing fields. +- **Compatibility notes**: in `zh-CN`, an ended round still shows 「等待开始」 (`phase_code` = `ended`), and an armed-but-not-counting-down warhead still shows 「未激活」 (`warhead_code` = `armed`). +- **Docs & tests**: console usage hints and README (Chinese and English) document `language` and the code fields. New pure-logic localization / error-code classes with regression tests; all 410 functional tests pass. +- **License**: changed from GPL-3.0-only to Apache-2.0 (attribution required; see `LICENSE`, `NOTICE`). ## 2.6.2-patch Holiday26 SLDataAPI **2.6.2-patch Holiday26**(相对 2.6.2 Holiday26)。版本号仍为 **2.6.2**,仅在 `InformationalVersion` / Release 标签增加 `-patch` 后缀。以 GitHub **正式版(Latest)**发布;原先的 `v2.6.2_Holiday26` 仍保留为上一正式版。本 patch 合入安全加固与 `/control/dummies` 实现,并对正式包恢复强名称签名。 @@ -19,12 +61,6 @@ SLDataAPI **2.6.2-patch Holiday26**(相对 2.6.2 Holiday26)。版本号仍 - `/control/dummies` 由 501 占位改为实现:`spawn` / `list`(只读,不写审计)/ `remove`。同时硬上限 5;超限返回 409 `dummy_limit`;`remove` 缺 target 返回 400,目标不存在返回 404 `dummy_not_found`;目标可为 PlayerId / 昵称 / `all`。`spawn` 支持可选 `nickname`(默认 Dummy,最长 32)与 `role`(RoleTypeId)。游戏版本缺少 `DummyUtils` 时返回 501 `feature_unavailable`,不抛 500 -## Unreleased - -### 许可证 - -- 由 **GPL-3.0-only** 变更为 **Apache-2.0**(允许闭源使用;须保留版权 / SPDX 头、NOTICE,并注明来自 DNTOF/SLDataAPI;禁止删改署名后换皮发布)。语音转发 / 录音仍标注为本项目原创。详见 `LICENSE`、`NOTICE`、README「许可证」。 - ## 2.6.2 Holiday26 SLDataAPI **2.6.2 Holiday26**(相对 2.6.1 Mores)。以 GitHub **正式版**发布。节日相关接口曾于 2026-10-17 以 **2.6.2-preview Holiday26** 预发布(见下方条目);本正式版包含其全部内容,并新增物品栏 / 糖果 / 设施状态端点、节日自动回退与事件流扩展。游戏公开分支已更新到 **14.2.8**(万圣节版本),本版本按 14.2.8 编译。2.6.1 Mores 与 2.6.2-preview 的更新检查都会提示本版本。 diff --git a/Commands/ApikeyParentCommand.cs b/Commands/ApikeyParentCommand.cs index 3ffb120..58de879 100644 --- a/Commands/ApikeyParentCommand.cs +++ b/Commands/ApikeyParentCommand.cs @@ -28,7 +28,8 @@ protected override bool ExecuteParent(ArraySegment arguments, ICommandSe { if (ApikeyCommandGuard.Reject(sender, out response)) return false; - response = "用法:\n sldataapi apikey create [note]\n sldataapi apikey revoke \n sldataapi apikey list"; + response = "用法:\n sldataapi apikey create [note]\n sldataapi apikey revoke \n sldataapi apikey list\n" + + SldataapiParentCommand.I18nHint; return false; } } diff --git a/Commands/SldataapiParentCommand.cs b/Commands/SldataapiParentCommand.cs index cdad2d1..b9fe223 100644 --- a/Commands/SldataapiParentCommand.cs +++ b/Commands/SldataapiParentCommand.cs @@ -20,6 +20,10 @@ public sealed class SldataapiParentCommand : ParentCommand public override string Description => "SLDataAPI 管理命令(API Key / TLS 证书)。远程 /control/console 已硬拒绝;若用权限插件收窄 RemoteAdmin,请同时拒绝 sldataapi / slda。"; + /// i18n / 机器码提示(控制台命令与 README 保持一致)。 + internal const string I18nHint = + "输出语言:config.yml 的 language(zh-CN 默认 / en)。接口响应新增稳定 code 字段(role_code / team_code / phase_code / warhead_code / error.code)与 lang 字段。"; + public override void LoadGeneratedCommands() { RegisterCommand(new ApikeyParentCommand()); @@ -28,7 +32,7 @@ public override void LoadGeneratedCommands() protected override bool ExecuteParent(ArraySegment arguments, ICommandSender sender, out string response) { - response = "用法: sldataapi apikey … | sldataapi cert (cert 仅限本地控制台)"; + response = "用法: sldataapi apikey … | sldataapi cert (cert 仅限本地控制台)\n" + I18nHint; return false; } } \ No newline at end of file diff --git a/Config.cs b/Config.cs index b2ffe71..1cc9b55 100644 --- a/Config.cs +++ b/Config.cs @@ -13,6 +13,14 @@ public class Config { public bool Debug { get; set; } = false; + /// + /// 接口输出语言:zh-CN(默认)或 en。 + /// 仅影响本插件生成的 HTTP / WebSocket 文本;游戏昵称、控制台回显、封禁 / 踢出原因等外部内容原样透传。 + /// 默认 zh-CN 时所有既有中文字段与文案保持不变;非法值回退 zh-CN 并在启动日志告警。 + /// 稳定 code 字段(role_code / team_code / phase_code / warhead_code / error.code)不随语言变化。 + /// + public string Language { get; set; } = "zh-CN"; + /// /// 只读数据口(/get_sl_data、/plugins/adapted 等)的共享口令。 /// 出厂默认 your_secret_token、空、或未通过强度校验(长度≥8 且同时含大写/小写/数字/特殊符号) diff --git a/Control/ControlAuth.cs b/Control/ControlAuth.cs index 9dacd12..64974c7 100644 --- a/Control/ControlAuth.cs +++ b/Control/ControlAuth.cs @@ -6,6 +6,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; +using SLDataAPI.Services; namespace SLDataAPI.Control; @@ -215,20 +216,22 @@ public static bool TryAuthenticate(string ip, string providedToken, string confi if (IsLocked(ip, table, out var remaining)) { - error = $"该来源已因多次鉴权失败被临时锁定,请 {Math.Ceiling(remaining.TotalSeconds)} 秒后重试"; + error = Localization.F("该来源已因多次鉴权失败被临时锁定,请 {0} 秒后重试", + "This source is temporarily locked after repeated authentication failures; retry in {0} seconds", + Math.Ceiling(remaining.TotalSeconds)); return false; } if (string.IsNullOrEmpty(configuredToken)) { - error = "服务端未配置访问令牌"; + error = Localization.T("服务端未配置访问令牌", "Access token is not configured on the server"); return false; } if (!SecureEquals(providedToken ?? string.Empty, configuredToken)) { RegisterFailure(ip, table); - error = "token 错误或缺失"; + error = Localization.T("token 错误或缺失", "Token is incorrect or missing"); return false; } diff --git a/Control/ControlController.Features.cs b/Control/ControlController.Features.cs index f8c385e..0639bab 100644 --- a/Control/ControlController.Features.cs +++ b/Control/ControlController.Features.cs @@ -36,26 +36,32 @@ private static (int, string) PlayerInventoryAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.target)) - return (400, Json(false, "缺少 target 字段")); + return (400, Json(false, Localization.T("缺少 target 字段", "Missing target field"), code: Localization.CodeInvalidArgument)); if (!FeatureInputRules.IsInventoryAction(req.action, out string action)) - return (400, Json(false, $"未知 action: {req.action}(支持 list/add/remove/clear)")); + return (400, Json(false, Localization.F("未知 action: {0}(支持 list/add/remove/clear)", + "Unknown action: {0} (supported: list/add/remove/clear)", req.action), code: Localization.CodeInvalidArgument)); ItemType itemType = ItemType.None; int amount = 1; if (action is "add" or "remove") { if (!TryParseItemType(req.item, out itemType)) - return (400, Json(false, $"无效物品名: {req.item}", new { code = "invalid_item" })); + return (400, Json(false, Localization.F("无效物品名: {0}", "Invalid item name: {0}", req.item), + new { code = "invalid_item" }, code: "invalid_item")); if (IsAmmoType(itemType)) - return (400, Json(false, "弹药不是物品栏物品,暂不支持通过本端点增减", new { code = "ammo_not_supported" })); + return (400, Json(false, Localization.T("弹药不是物品栏物品,暂不支持通过本端点增减", + "Ammunition is not an inventory item and cannot be added or removed through this endpoint"), + new { code = "ammo_not_supported" }, code: "ammo_not_supported")); int max = action == "add" ? FeatureInputRules.MaxItemAdd : FeatureInputRules.MaxItemRemove; if (!FeatureInputRules.TryValidateAmount(req.amount, max, out amount)) - return (400, Json(false, $"amount 超出上限 {max}", new { code = "amount_exceeds_limit", max })); + return (400, Json(false, Localization.F("amount 超出上限 {0}", "amount exceeds the limit of {0}", max), + new { code = "amount_exceeds_limit", max }, code: "amount_exceeds_limit")); } var (status, json) = MainThreadExecutor.RunOnMainThread(() => { - var p = FindPlayer(req.target) ?? throw new InvalidOperationException($"找不到玩家: {req.target}"); + var p = FindPlayer(req.target) ?? throw new InvalidOperationException( + Localization.F("找不到玩家: {0}", "Player not found: {0}", req.target)); switch (action) { case "list": @@ -78,13 +84,16 @@ private static (int, string) PlayerInventoryAction(string body) if (added.Count == 0) { bool full = p.IsInventoryFull; - return (409, Json(false, full ? "物品栏已满" : "物品发放失败(游戏拒绝添加)", new + return (409, Json(false, full + ? Localization.T("物品栏已满", "Inventory is full") + : Localization.T("物品发放失败(游戏拒绝添加)", "Item grant failed (the game rejected the add)"), new { code = full ? "inventory_full" : "add_failed", inventory = DescribeInventory(p), })); } - return (200, Json(true, $"已发放 {added.Count}/{amount} 个 {itemType}", new + return (200, Json(true, Localization.F("已发放 {0}/{1} 个 {2}", + "Granted {0}/{1} × {2}", added.Count, amount, itemType), new { requested = amount, added, @@ -97,7 +106,8 @@ private static (int, string) PlayerInventoryAction(string body) int before = p.Items.Count(x => x != null && x.Type == itemType); if (before > 0) p.RemoveItem(itemType, amount); int after = p.Items.Count(x => x != null && x.Type == itemType); - return (200, Json(true, $"已移除 {before - after} 个 {itemType}", new + return (200, Json(true, Localization.F("已移除 {0} 个 {1}", + "Removed {0} × {1}", before - after, itemType), new { requested = amount, removed = before - after, @@ -110,7 +120,7 @@ private static (int, string) PlayerInventoryAction(string body) int items = p.Items.Count(); int ammoKinds = p.Ammo.Count(kv => kv.Value > 0); p.ClearInventory(clearAmmo: req.clear_ammo, clearItems: true); - return (200, Json(true, "物品栏已清空", new + return (200, Json(true, Localization.T("物品栏已清空", "Inventory cleared"), new { cleared_items = items, cleared_ammo_types = req.clear_ammo ? ammoKinds : 0, @@ -119,7 +129,8 @@ private static (int, string) PlayerInventoryAction(string body) } default: - return (400, Json(false, $"未知 action: {action}")); + return (400, Json(false, Localization.F("未知 action: {0}", "Unknown action: {0}", action), + code: Localization.CodeInvalidArgument)); } }, out var err); return err != null ? (400, Json(false, err.Message)) : (status, json); @@ -170,10 +181,12 @@ private static (int, string) PlayerCandyAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.target)) - return (400, Json(false, "缺少 target 字段")); + return (400, Json(false, Localization.T("缺少 target 字段", "Missing target field"), code: Localization.CodeInvalidArgument)); if (!FeatureInputRules.TryValidateAmount(req.amount, FeatureInputRules.MaxCandyGive, out int amount)) - return (400, Json(false, $"amount 超出上限 {FeatureInputRules.MaxCandyGive}", - new { code = "amount_exceeds_limit", max = FeatureInputRules.MaxCandyGive })); + return (400, Json(false, Localization.F("amount 超出上限 {0}", + "amount exceeds the limit of {0}", FeatureInputRules.MaxCandyGive), + new { code = "amount_exceeds_limit", max = FeatureInputRules.MaxCandyGive }, + code: "amount_exceeds_limit")); string candyName = (req.candy ?? "").Trim(); bool random = candyName.Length == 0 || candyName.Equals("random", StringComparison.OrdinalIgnoreCase); @@ -181,7 +194,7 @@ private static (int, string) PlayerCandyAction(string body) if (!random && (!Enum.TryParse(candyName, true, out kind) || kind == CandyKindID.None || !Enum.IsDefined(typeof(CandyKindID), kind))) { - return (400, Json(false, $"无效糖果名: {req.candy}", new + return (400, Json(false, Localization.F("无效糖果名: {0}", "Invalid candy name: {0}", req.candy), new { code = "invalid_candy", valid = Enum.GetNames(typeof(CandyKindID)).Where(n => n != "None").ToArray(), @@ -190,7 +203,8 @@ private static (int, string) PlayerCandyAction(string body) var (status, json) = MainThreadExecutor.RunOnMainThread(() => { - var p = FindPlayer(req.target) ?? throw new InvalidOperationException($"找不到玩家: {req.target}"); + var p = FindPlayer(req.target) ?? throw new InvalidOperationException( + Localization.F("找不到玩家: {0}", "Player not found: {0}", req.target)); if (!random) { @@ -224,14 +238,16 @@ private static (int, string) PlayerCandyAction(string body) active_holiday = HolidayFeatures.ActiveHoliday(), }; if (given.Count == 0) - return (409, Json(false, "糖果发放失败(物品栏或糖果袋已满)", new + return (409, Json(false, Localization.T("糖果发放失败(物品栏或糖果袋已满)", + "Candy grant failed (inventory or candy bag is full)"), new { code = "candy_bag_full", result.bag, result.candy_pool, result.active_holiday, })); - return (200, Json(true, $"已发放 {given.Count}/{amount} 颗糖果", result)); + return (200, Json(true, Localization.F("已发放 {0}/{1} 颗糖果", + "Granted {0}/{1} candy item(s)", given.Count, amount), result)); }, out var err); return err != null ? (400, Json(false, err.Message)) : (status, json); } @@ -318,13 +334,16 @@ private static (int, string) DummiesAction(string body) { var req = Parse(body); if (req == null || !FeatureInputRules.IsDummyAction(req.action, out string action)) - return (400, Json(false, "缺少或未知 action(支持 spawn/list/remove)", - new { code = "invalid_action", valid = FeatureInputRules.DummyActions })); + return (400, Json(false, Localization.T("缺少或未知 action(支持 spawn/list/remove)", + "Missing or unknown action (supported: spawn/list/remove)"), + new { code = "invalid_action", valid = FeatureInputRules.DummyActions }, + code: "invalid_action")); // 旧游戏版本可能没有 DummyUtils:先按类型名探测,避免 JIT 到引用缺失类型的方法时抛 TypeLoadException if (ReflectionLookup.FindType("NetworkManagerUtils.Dummies.DummyUtils") == null) { - return (501, Json(false, "当前游戏版本不提供假人 API(DummyUtils 不存在)", new + return (501, Json(false, Localization.T("当前游戏版本不提供假人 API(DummyUtils 不存在)", + "This game version does not provide the dummy API (DummyUtils is missing)"), new { code = "feature_unavailable", feature = "dummies", @@ -337,13 +356,16 @@ private static (int, string) DummiesAction(string body) if (!Enum.TryParse(req.role.Trim(), true, out RoleTypeId roleId) || !Enum.IsDefined(typeof(RoleTypeId), roleId)) { - return (400, Json(false, $"无效角色名: {req.role}", new { code = "invalid_role" })); + return (400, Json(false, Localization.F("无效角色名: {0}", "Invalid role name: {0}", req.role), + new { code = "invalid_role" }, code: "invalid_role")); } spawnRole = roleId; } if (action == "remove" && string.IsNullOrWhiteSpace(req.target)) - return (400, Json(false, "remove 需要 target(假人 PlayerId / 昵称,或 all)", new { code = "missing_target" })); + return (400, Json(false, Localization.T("remove 需要 target(假人 PlayerId / 昵称,或 all)", + "remove requires target (dummy PlayerId / nickname, or all)"), + new { code = "missing_target" }, code: "missing_target")); string nickname = FeatureInputRules.NormalizeDummyNickname(req.nickname); string target = (req.target ?? "").Trim(); @@ -360,7 +382,8 @@ private static (int, string) DummiesAction(string body) int count = Player.DummyList.Count(); if (count >= FeatureInputRules.MaxDummies) { - return (409, Json(false, $"假人数量已达上限 {FeatureInputRules.MaxDummies}", new + return (409, Json(false, Localization.F("假人数量已达上限 {0}", + "Dummy limit reached ({0})", FeatureInputRules.MaxDummies), new { code = "dummy_limit", max = FeatureInputRules.MaxDummies, @@ -373,7 +396,8 @@ private static (int, string) DummiesAction(string body) try { hub = SpawnDummySafe(nickname); } catch (TypeLoadException ex) { - return (501, Json(false, $"当前游戏版本不提供假人 API: {ex.Message}", new + return (501, Json(false, Localization.F("当前游戏版本不提供假人 API: {0}", + "This game version does not provide the dummy API: {0}", ex.Message), new { code = "feature_unavailable", feature = "dummies", @@ -381,7 +405,8 @@ private static (int, string) DummiesAction(string body) } catch (MissingMethodException ex) { - return (501, Json(false, $"当前游戏版本不提供假人 API: {ex.Message}", new + return (501, Json(false, Localization.F("当前游戏版本不提供假人 API: {0}", + "This game version does not provide the dummy API: {0}", ex.Message), new { code = "feature_unavailable", feature = "dummies", @@ -389,16 +414,20 @@ private static (int, string) DummiesAction(string body) } if (hub == null) - return (500, Json(false, "假人生成失败(SpawnDummy 返回 null)", new { code = "spawn_failed" })); + return (500, Json(false, Localization.T("假人生成失败(SpawnDummy 返回 null)", + "Dummy spawn failed (SpawnDummy returned null)"), new { code = "spawn_failed" }, + code: "spawn_failed")); var player = Player.Get(hub); if (player == null) - return (500, Json(false, "假人已生成但无法包装为 Player", new { code = "spawn_failed" })); + return (500, Json(false, Localization.T("假人已生成但无法包装为 Player", + "Dummy was spawned but could not be wrapped as a Player"), + new { code = "spawn_failed" }, code: "spawn_failed")); if (spawnRole.HasValue) player.SetRole(spawnRole.Value); - return (200, Json(true, $"已生成假人 {player.Nickname}", new + return (200, Json(true, Localization.F("已生成假人 {0}", "Spawned dummy {0}", player.Nickname), new { dummy = DescribeDummy(player), count = Player.DummyList.Count(), @@ -414,7 +443,8 @@ private static (int, string) DummiesAction(string body) try { DestroyAllDummiesSafe(); } catch (TypeLoadException ex) { - return (501, Json(false, $"当前游戏版本不提供假人 API: {ex.Message}", new + return (501, Json(false, Localization.F("当前游戏版本不提供假人 API: {0}", + "This game version does not provide the dummy API: {0}", ex.Message), new { code = "feature_unavailable", feature = "dummies", @@ -422,13 +452,15 @@ private static (int, string) DummiesAction(string body) } catch (MissingMethodException ex) { - return (501, Json(false, $"当前游戏版本不提供假人 API: {ex.Message}", new + return (501, Json(false, Localization.F("当前游戏版本不提供假人 API: {0}", + "This game version does not provide the dummy API: {0}", ex.Message), new { code = "feature_unavailable", feature = "dummies", })); } - return (200, Json(true, $"已清除全部假人({before})", new + return (200, Json(true, Localization.F("已清除全部假人({0})", + "Removed all dummies ({0})", before), new { removed = before, count = Player.DummyList.Count(), @@ -438,7 +470,8 @@ private static (int, string) DummiesAction(string body) var dummy = FindDummy(target); if (dummy == null) - return (404, Json(false, $"找不到假人: {target}", new { code = "dummy_not_found" })); + return (404, Json(false, Localization.F("找不到假人: {0}", "Dummy not found: {0}", target), + new { code = "dummy_not_found" }, code: "dummy_not_found")); var snapshot = DescribeDummy(dummy); string goneName = dummy.Nickname; @@ -449,10 +482,11 @@ private static (int, string) DummiesAction(string body) } catch (Exception ex) { - return (500, Json(false, $"销毁假人失败: {ex.Message}", new { code = "destroy_failed" })); + return (500, Json(false, Localization.F("销毁假人失败: {0}", "Failed to destroy dummy: {0}", ex.Message), + new { code = "destroy_failed" }, code: "destroy_failed")); } - return (200, Json(true, $"已移除假人 {goneName}", new + return (200, Json(true, Localization.F("已移除假人 {0}", "Removed dummy {0}", goneName), new { removed = snapshot, count = Player.DummyList.Count(), @@ -461,7 +495,8 @@ private static (int, string) DummiesAction(string body) } default: - return (400, Json(false, $"未知 action: {action}")); + return (400, Json(false, Localization.F("未知 action: {0}", "Unknown action: {0}", action), + code: Localization.CodeInvalidArgument)); } }, out var err); return err != null ? (400, Json(false, err.Message)) : (status, json); diff --git a/Control/ControlController.cs b/Control/ControlController.cs index 91d485b..a6ec996 100644 --- a/Control/ControlController.cs +++ b/Control/ControlController.cs @@ -103,7 +103,7 @@ public static (int status, string json) Handle(string path, string body, string? "/control/files/write_chunk" => FilesBetaAction(body, "write_chunk", actor), // [内测] beta_adapted_plugin_actions:适配插件写 / 动作路由 _ when path.StartsWith(AdaptedActionPrefix, StringComparison.Ordinal) => AdaptedPluginAction(path, body, actor), - _ => (404, Json(false, "未知控制端点(2.6 已移除旧路径别名,请使用 RA 对齐新路径)")), + _ => (404, Json(false, Localization.T("未知控制端点(2.6 已移除旧路径别名,请使用 RA 对齐新路径)", "Unknown control endpoint (legacy path aliases were removed in 2.6; use the RA-aligned paths)"), code: Localization.CodeNotFound)), }; // ★ 最终兜底:任何端点漏检查主线程派发错误而泄漏 (0, null) 时, @@ -111,9 +111,12 @@ _ when path.StartsWith(AdaptedActionPrefix, StringComparison.Ordinal) => Adapted if (status <= 0 || string.IsNullOrEmpty(json)) { Log.Error($"[SLDataAPI][Control] 端点 {path} 返回了无效结果 (status={status})——内部错误未正确传播,已兜底为 500"); - return (500, Json(false, "内部错误")); + return (500, Json(false, Localization.InternalError, code: Localization.CodeInternalError)); } + // 统一补齐错误 code(未显式指定时按状态码 + 文案推断),保证所有错误响应都有稳定机器码。 + json = ErrorCodeEnvelope.EnsureErrorCode(status, json); + // 控制操作审计日志(v2.5.5-preview 推出,代号 Everest C1):只记录主动侵入性操作(排除只读/自动化流程), // 不计 IP,只记时间 + 端点 + 请求体 + 结果。HTTP 与 WS call 通道都汇聚到这里,自动全覆盖 if (!IsReadOnlyOperation(path, body)) @@ -130,7 +133,7 @@ _ when path.StartsWith(AdaptedActionPrefix, StringComparison.Ordinal) => Adapted { Log.Error($"[SLDataAPI][Control] 顶层异常: {ex}"); // 不向客户端回显异常细节(可能含服务器路径等敏感信息),细节只进服务器日志 - return (500, Json(false, "内部错误")); + return (500, Json(false, Localization.InternalError, code: Localization.CodeInternalError)); } } @@ -195,7 +198,7 @@ private static (int, string) WaveAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段")); + return (400, Json(false, Localization.T("缺少 action 字段", "Missing action field"), code: Localization.CodeInvalidArgument)); var (status, json) = MainThreadExecutor.RunOnMainThread(() => { @@ -203,10 +206,12 @@ private static (int, string) WaveAction(string body) { "mtf" => LabApi.Features.Wrappers.RespawnWaves.PrimaryMtfWave, "chaos" => LabApi.Features.Wrappers.RespawnWaves.PrimaryChaosWave, - _ => throw new InvalidOperationException($"未知阵营: {req.faction}(支持 mtf / chaos)"), + _ => throw new InvalidOperationException(Localization.F("未知阵营: {0}(支持 mtf / chaos)", + "Unknown faction: {0} (supported: mtf / chaos)", req.faction)), }; if (wave == null) - throw new InvalidOperationException("该阵营当前没有待生成的波次"); + throw new InvalidOperationException(Localization.T("该阵营当前没有待生成的波次", + "No pending respawn wave for this faction")); string action = req.action.Trim().ToLowerInvariant(); switch (action) @@ -220,7 +225,8 @@ private static (int, string) WaveAction(string body) case "status": break; default: - throw new InvalidOperationException($"未知 action: {req.action}(支持 instant / set / status)"); + throw new InvalidOperationException(Localization.F("未知 action: {0}(支持 instant / set / status)", + "Unknown action: {0} (supported: instant / set / status)", req.action)); } var payload = new Dictionary @@ -249,7 +255,8 @@ private static (int, string) ReportsAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段(支持 list / handle)")); + return (400, Json(false, Localization.T("缺少 action 字段(支持 list / handle)", + "Missing action field (supported: list / handle)"), code: Localization.CodeInvalidArgument)); switch (req.action.Trim().ToLowerInvariant()) { @@ -257,12 +264,15 @@ private static (int, string) ReportsAction(string body) return (200, Json(true, "ok", ReportService.ListPending())); case "handle": if (string.IsNullOrWhiteSpace(req.id)) - return (400, Json(false, "缺少 id 字段(举报记录 id)")); + return (400, Json(false, Localization.T("缺少 id 字段(举报记录 id)", + "Missing id field (report record id)"), code: Localization.CodeInvalidArgument)); return ReportService.MarkHandled(req.id.Trim()) - ? (200, Json(true, "已标记为已处理")) - : (404, Json(false, "未找到该记录或该记录已处理")); + ? (200, Json(true, Localization.T("已标记为已处理", "Marked as handled"))) + : (404, Json(false, Localization.T("未找到该记录或该记录已处理", + "Record not found or already handled"), code: Localization.CodeNotFound)); default: - return (400, Json(false, $"未知 action: {req.action}(支持 list / handle)")); + return (400, Json(false, Localization.F("未知 action: {0}(支持 list / handle)", + "Unknown action: {0} (supported: list / handle)", req.action), code: Localization.CodeInvalidArgument)); } } @@ -276,7 +286,7 @@ private static (int, string) RunCommand(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.command)) - return (400, Json(false, "缺少 command 字段")); + return (400, Json(false, Localization.T("缺少 command 字段", "Missing command field"), code: Localization.CodeInvalidArgument)); // SLDataAPI 自身的管理 CLI 一律不经远程控制通道执行(所有子命令,不只 apikey)。 // 远程通道只能证明"持有某把 Key",无法证明操作者身份;放行等于任何拿到 console 授权的 Key @@ -305,7 +315,7 @@ private static (int, string) RunCommand(string body) if (err != null) { Log.Error($"[SLDataAPI][Control] 命令执行失败({sw.ElapsedMilliseconds}ms): {err.GetType().Name}: {err.Message}"); - return (500, Json(false, $"命令执行失败: {err.Message}")); + return (500, Json(false, Localization.F("命令执行失败: {0}", "Command execution failed: {0}", err.Message), code: Localization.CodeOperationFailed)); } } finally @@ -317,7 +327,7 @@ private static (int, string) RunCommand(string body) // 全链路诊断(不受 debug 开关限制——控制台回显是核心功能,问题要能一眼定位) Log.Info($"[SLDataAPI][Control] 命令完成({sw.ElapsedMilliseconds}ms):output 长度 {output?.Length ?? 0},console 长度 {consoleOutput?.Length ?? 0}"); - return (200, Json(true, "已执行", new { output, console = consoleOutput })); + return (200, Json(true, Localization.T("已执行", "Executed"), new { output, console = consoleOutput })); } private static readonly char[] SpaceSeparator = { ' ' }; @@ -355,14 +365,15 @@ private static string ExecuteConsoleCommandCore(string command) string[] array = trimmed.Substring(1).Trim().Split(SpaceSeparator, StringSplitOptions.RemoveEmptyEntries); if (array.Length == 0) - return "命令为空"; + return Localization.T("命令为空", "Command is empty"); bool found = QueryProcessor.DotCommandHandler.TryGetCommand(array[0], out var dotCommand); var arguments = new ArraySegment(array, 1, array.Length - 1); // 原生玩家路径以玩家身份执行(大量插件命令会取 sender.Player),专用服用主机玩家等效代替 if (!ReferenceHub.TryGetLocalHub(out var hub) || hub == null) - return "主机玩家不存在,无法以玩家身份执行点命令"; + return Localization.T("主机玩家不存在,无法以玩家身份执行点命令", + "The host player does not exist; cannot execute dot commands as a player"); var sender = new PlayerCommandSender(hub); // 与原生路径一致:触发 LabAPI 命令事件(监听/审计命令的插件可见) @@ -429,31 +440,35 @@ private static (int, string) PlayerAction(string body, string kind) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.target)) - return (400, Json(false, "缺少 target 字段")); + return (400, Json(false, Localization.T("缺少 target 字段", "Missing target field"), code: Localization.CodeInvalidArgument)); MainThreadExecutor.RunOnMainThread(() => { var player = FindPlayer(req.target); if (player == null) - throw new InvalidOperationException($"找不到玩家: {req.target}"); + throw new InvalidOperationException(Localization.F("找不到玩家: {0}", "Player not found: {0}", req.target)); switch (kind) { case "kick": - player.Kick(string.IsNullOrWhiteSpace(req.reason) ? "由管理端踢出" : req.reason); + player.Kick(string.IsNullOrWhiteSpace(req.reason) + ? Localization.T("由管理端踢出", "Kicked by the administration") + : req.reason); break; case "ban": // 请求单位是分钟;LabAPI 的 Ban 按秒计,0 = 永久。 // X-08:负数 duration 语义未定义,钳制为 0(永久) player.Ban( - string.IsNullOrWhiteSpace(req.reason) ? "由管理端封禁" : req.reason, + string.IsNullOrWhiteSpace(req.reason) + ? Localization.T("由管理端封禁", "Banned by the administration") + : req.reason, (long)Math.Max(0, req.duration) * 60); break; case "role": if (!Enum.TryParse(req.role, true, out var roleId)) - throw new InvalidOperationException($"无效角色名: {req.role}"); + throw new InvalidOperationException(Localization.F("无效角色名: {0}", "Invalid role name: {0}", req.role)); player.SetRole(roleId); break; @@ -464,7 +479,8 @@ private static (int, string) PlayerAction(string body, string kind) case "mute": { if (req.mute == null) - throw new InvalidOperationException("缺少 mute 字段(true=语音禁言 / false=解除)"); + throw new InvalidOperationException(Localization.T("缺少 mute 字段(true=语音禁言 / false=解除)", + "Missing mute field (true = mute voice / false = unmute)")); // 四档化(v2.5.4-preview 推出,代号 ENIGMA;v2.5.4 正式版,代号 GIS,GNSS,RS!): // voice(全局语音)/ intercom(对讲机)× persistent(持久写入本地静音存储) @@ -486,7 +502,7 @@ private static (int, string) PlayerAction(string body, string kind) case "msg": if (string.IsNullOrWhiteSpace(req.message)) - throw new InvalidOperationException("缺少 message 字段"); + throw new InvalidOperationException(Localization.T("缺少 message 字段", "Missing message field")); float dur = ControlMessageValidation.ClampDurationSeconds(req.duration_seconds); if (req.msg_type == "broadcast") player.SendBroadcast(req.message, (ushort)Math.Ceiling(dur)); @@ -496,9 +512,10 @@ private static (int, string) PlayerAction(string body, string kind) case "effect": if (req.effect_intensity < 0 || req.effect_intensity > 255) - throw new InvalidOperationException($"effect_intensity 超出范围: {req.effect_intensity}(0-255,0=关闭)"); + throw new InvalidOperationException(Localization.F("effect_intensity 超出范围: {0}(0-255,0=关闭)", + "effect_intensity is out of range: {0} (0-255; 0 disables the effect)", req.effect_intensity)); if (!TryEnableEffect(player, req.effect, Math.Max(0.1f, req.effect_duration), (byte)req.effect_intensity)) - throw new InvalidOperationException($"无效效果名: {req.effect}"); + throw new InvalidOperationException(Localization.F("无效效果名: {0}", "Invalid effect name: {0}", req.effect)); break; case "state": @@ -520,7 +537,7 @@ private static (int, string) PlayerAction(string body, string kind) return (400, Json(false, err.Message)); Log.Info($"[SLDataAPI][Control] player/{kind} target={req.target}"); - return (200, Json(true, "操作完成")); + return (200, Json(true, Localization.T("操作完成", "Operation completed"))); } // 效果名别名:旧 EXILED EffectType 枚举名 → base-game 效果类名(大小写不敏感匹配) @@ -606,11 +623,13 @@ private static void SetVoiceChannel(Player player, bool intercom) { var module = player.VoiceModule; if (module == null) - throw new InvalidOperationException("玩家语音模块未初始化"); + throw new InvalidOperationException(Localization.T("玩家语音模块未初始化", + "Player voice module is not initialized")); var prop = typeof(PlayerRoles.Voice.VoiceModuleBase) .GetProperty("CurrentChannel", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (prop == null || !prop.CanWrite) - throw new InvalidOperationException("CurrentChannel 属性不可写"); + throw new InvalidOperationException(Localization.T("CurrentChannel 属性不可写", + "The CurrentChannel property is not writable")); prop.SetValue(module, channel); } catch (InvalidOperationException) @@ -619,7 +638,8 @@ private static void SetVoiceChannel(Player player, bool intercom) } catch (Exception ex) { - throw new InvalidOperationException($"切换语音通道失败: {ex.Message}"); + throw new InvalidOperationException(Localization.F("切换语音通道失败: {0}", + "Failed to switch voice channel: {0}", ex.Message)); } } @@ -647,7 +667,8 @@ private static (int, string) BroadcastAction(string body) return (400, Json(false, err.Message)); Log.Info($"[SLDataAPI][Control] broadcast duration={seconds} clear={clear}"); - return (200, Json(true, "全服广播已发送", new { duration_seconds = seconds, clear_previous = clear })); + return (200, Json(true, Localization.T("全服广播已发送", "Server-wide broadcast sent"), + new { duration_seconds = seconds, clear_previous = clear })); } // ------------------------------------------------------------------ @@ -665,7 +686,8 @@ private static (int, string) StaffChatAction(string body) MainThreadExecutor.RunOnMainThread(() => { if (Server.Host == null) - throw new InvalidOperationException("服务器主机未就绪,无法发送管理聊天"); + throw new InvalidOperationException(Localization.T("服务器主机未就绪,无法发送管理聊天", + "Server host is not ready; admin chat cannot be sent")); // LabAPI 1.1.7:SendAdminChatMessage 过滤 ReadyList 中具备 AdminChat 权限的玩家, // 走 EncryptedChannel.AdminChat(RA Staff Chat)。isSilent=true 时不附带屏幕广播提示。 @@ -676,7 +698,7 @@ private static (int, string) StaffChatAction(string body) return (400, Json(false, err.Message)); Log.Info($"[SLDataAPI][Control] staffchat silent={silent}"); - return (200, Json(true, "管理聊天已发送", new { is_silent = silent })); + return (200, Json(true, Localization.T("管理聊天已发送", "Admin chat sent"), new { is_silent = silent })); } // ------------------------------------------------------------------ @@ -686,7 +708,7 @@ private static (int, string) RoundAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段")); + return (400, Json(false, Localization.T("缺少 action 字段", "Missing action field"), code: Localization.CodeInvalidArgument)); MainThreadExecutor.RunOnMainThread(() => { @@ -702,7 +724,8 @@ private static (int, string) RoundAction(string body) Round.Start(); break; default: - throw new InvalidOperationException($"未知 action: {req.action}(支持 restart / end / start)"); + throw new InvalidOperationException(Localization.F("未知 action: {0}(支持 restart / end / start)", + "Unknown action: {0} (supported: restart / end / start)", req.action)); } }, out var err); @@ -710,7 +733,7 @@ private static (int, string) RoundAction(string body) return (400, Json(false, err.Message)); Log.Info($"[SLDataAPI][Control] round action={req.action}"); - return (200, Json(true, "回合操作完成")); + return (200, Json(true, Localization.T("回合操作完成", "Round operation completed"))); } // ------------------------------------------------------------------ @@ -720,9 +743,10 @@ private static (int, string) CassieAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.message)) - return (400, Json(false, "缺少 message 字段")); + return (400, Json(false, Localization.T("缺少 message 字段", "Missing message field"), code: Localization.CodeInvalidArgument)); if (req.message.Length > 500) - return (400, Json(false, $"message 过长({req.message.Length} 字符,上限 500)")); + return (400, Json(false, Localization.F("message 过长({0} 字符,上限 500)", + "message is too long ({0} characters; limit 500)", req.message.Length), code: Localization.CodeInvalidArgument)); MainThreadExecutor.RunOnMainThread(() => { @@ -743,7 +767,7 @@ private static (int, string) CassieAction(string body) if (err != null) return (400, Json(false, err.Message)); - return (200, Json(true, "CASSIE 播报已触发")); + return (200, Json(true, Localization.T("CASSIE 播报已触发", "CASSIE announcement triggered"))); } // ------------------------------------------------------------------ @@ -753,7 +777,7 @@ private static (int, string) WarheadAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段")); + return (400, Json(false, Localization.T("缺少 action 字段", "Missing action field"), code: Localization.CodeInvalidArgument)); MainThreadExecutor.RunOnMainThread(() => { @@ -769,7 +793,8 @@ private static (int, string) WarheadAction(string body) Warhead.Detonate(); break; default: - throw new InvalidOperationException($"未知 action: {req.action}(支持 start / stop / detonate)"); + throw new InvalidOperationException(Localization.F("未知 action: {0}(支持 start / stop / detonate)", + "Unknown action: {0} (supported: start / stop / detonate)", req.action)); } }, out var err); @@ -777,7 +802,7 @@ private static (int, string) WarheadAction(string body) return (400, Json(false, err.Message)); Log.Info($"[SLDataAPI][Control] warhead action={req.action}"); - return (200, Json(true, "核弹操作完成")); + return (200, Json(true, Localization.T("核弹操作完成", "Warhead operation completed"))); } // ------------------------------------------------------------------ @@ -787,7 +812,8 @@ private static (int, string) SlPlayerAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段")); + return (400, Json(false, Localization.T("缺少 action 字段", "Missing action field"), + code: Localization.CodeInvalidArgument)); string action = req.action.ToLowerInvariant(); @@ -796,20 +822,22 @@ private static (int, string) SlPlayerAction(string body) if (action == "fetch") { if (string.IsNullOrWhiteSpace(req.url)) - return (400, Json(false, "缺少 url 字段")); + return (400, Json(false, Localization.T("缺少 url 字段", "Missing url field"), code: Localization.CodeInvalidArgument)); // 防命令注入:URL 会拼进控制台命令,必须是合法 http(s) 绝对地址, // 且不含任何空白/控制字符(空格、换行等可被控制台解析成多条命令或参数) string url = req.url.Trim(); if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) - return (400, Json(false, "url 必须是合法的 http:// 或 https:// 绝对地址")); + return (400, Json(false, Localization.T("url 必须是合法的 http:// 或 https:// 绝对地址", + "url must be a valid absolute http:// or https:// address"), code: Localization.CodeInvalidArgument)); foreach (char c in url) { if (char.IsWhiteSpace(c) || char.IsControl(c)) - return (400, Json(false, "url 不能包含空白或控制字符")); + return (400, Json(false, Localization.T("url 不能包含空白或控制字符", + "url cannot contain whitespace or control characters"), code: Localization.CodeInvalidArgument)); } - return RunConsoleCommand($".m fetch {url}", "正在拉取云端歌单..."); + return RunConsoleCommand($".m fetch {url}", Localization.T("正在拉取云端歌单...", "Fetching remote playlist...")); } var (slStatus, slJson) = MainThreadExecutor.RunOnMainThread(() => @@ -826,7 +854,7 @@ private static (int, string) SlPlayerAction(string body) case "play": if (req.index < 0) - return (400, Json(false, "缺少 index 字段")); + return (400, Json(false, Localization.T("缺少 index 字段", "Missing index field"), code: Localization.CodeInvalidArgument)); return (200, Json(true, SlPlayerController.Play(controller, req.index))); case "next": @@ -837,7 +865,8 @@ private static (int, string) SlPlayerAction(string body) case "volume": if (req.volume < 0 || req.volume > 100) - return (400, Json(false, "volume 需在 0-100 之间")); + return (400, Json(false, Localization.T("volume 需在 0-100 之间", "volume must be between 0 and 100"), + code: Localization.CodeInvalidArgument)); return (200, Json(true, SlPlayerController.SetVolume(controller, req.volume))); case "shuffle": @@ -847,7 +876,9 @@ private static (int, string) SlPlayerAction(string body) return (200, Json(true, SlPlayerController.Reload(controller))); default: - return (404, Json(false, $"未知 action: {req.action}(支持 status/list/play/next/stop/volume/shuffle/reload/fetch)")); + return (404, Json(false, Localization.F("未知 action: {0}(支持 status/list/play/next/stop/volume/shuffle/reload/fetch)", + "Unknown action: {0} (supported: status/list/play/next/stop/volume/shuffle/reload/fetch)", req.action), + code: Localization.CodeNotFound)); } }, out var err); @@ -870,7 +901,8 @@ private static (int, string) RunConsoleCommand(string command, string okText) out var err); if (err != null) - return (500, Json(false, $"命令执行失败: {err.Message}")); + return (500, Json(false, Localization.F("命令执行失败: {0}", "Command execution failed: {0}", err.Message), + code: Localization.CodeOperationFailed)); return (200, Json(true, okText, new { output })); } @@ -925,29 +957,34 @@ private static (int, string) PluginsAction(string body) try { p.LoadConfigs(); count++; } catch { /* 单个插件失败不影响其余 */ } } - return Json(true, $"已热重载 {count} 个插件的配置(插件本体与启停状态需重启服务器生效)"); + return Json(true, Localization.F("已热重载 {0} 个插件的配置(插件本体与启停状态需重启服务器生效)", + "Reloaded configs for {0} plugin(s) (plugin assemblies and enabled state require a server restart)", count)); } if (req?.action == "stage") { if (string.IsNullOrWhiteSpace(req.name)) - throw new InvalidOperationException("缺少 name 字段"); + throw new InvalidOperationException(Localization.T("缺少 name 字段", "Missing name field")); bool found = FindLabPlugin(req.name) != null || ExiledInterop.FindPlugin(req.name) != null; if (!found) - throw new InvalidOperationException($"未找到插件: {req.name}"); + throw new InvalidOperationException(Localization.F("未找到插件: {0}", "Plugin not found: {0}", req.name)); var labSelf = FindLabPlugin(req.name); if (labSelf != null && IsSelfPlugin(labSelf)) - throw new InvalidOperationException("禁止禁用 SLDataAPI 自身"); + throw new InvalidOperationException(Localization.T("禁止禁用 SLDataAPI 自身", "SLDataAPI itself cannot be disabled")); PluginStaged[req.name.Trim()] = req.enabled; + string stagedAction = req.enabled + ? Localization.T("启用", "enable") + : Localization.T("禁用", "disable"); return Json(true, - $"已暂存{(req.enabled ? "启用" : "禁用")}插件 {req.name.Trim()}(点\"保存并重载\"统一生效)", + Localization.F("已暂存{0}插件 {1}(点\"保存并重载\"统一生效)", + "Staged {0} for plugin {1} (apply with \"Save and reload\")", stagedAction, req.name.Trim()), new { staged = StagedSnapshot() }); } if (req?.action == "clear") { PluginStaged.Clear(); - return Json(true, "已清空暂存", new { staged = StagedSnapshot() }); + return Json(true, Localization.T("已清空暂存", "Staged changes cleared"), new { staged = StagedSnapshot() }); } if (req?.action == "apply") @@ -962,13 +999,14 @@ private static (int, string) PluginsAction(string body) { if (IsSelfPlugin(labPlugin)) { - failed.Add(new { name = kv.Key, reason = "禁止禁用 SLDataAPI 自身" }); + failed.Add(new { name = kv.Key, reason = Localization.T("禁止禁用 SLDataAPI 自身", "SLDataAPI itself cannot be disabled") }); continue; } try { WriteLabPluginEnabled(labPlugin, kv.Value); - applied.Add(new { name = kv.Key, enabled = kv.Value, note = "重启服务器后生效" }); + applied.Add(new { name = kv.Key, enabled = kv.Value, + note = Localization.T("重启服务器后生效", "Takes effect after a server restart") }); } catch (Exception ex) { @@ -983,7 +1021,8 @@ private static (int, string) PluginsAction(string body) string? errReason = ExiledInterop.SetPluginEnabled(exiledPlugin, kv.Value); if (errReason == null) { - applied.Add(new { name = kv.Key, enabled = kv.Value, note = "EXILED 插件已重载生效" }); + applied.Add(new { name = kv.Key, enabled = kv.Value, + note = Localization.T("EXILED 插件已重载生效", "EXILED plugin reloaded and applied") }); exiledTouched = true; } else @@ -993,7 +1032,7 @@ private static (int, string) PluginsAction(string body) continue; } - failed.Add(new { name = kv.Key, reason = "插件不存在" }); + failed.Add(new { name = kv.Key, reason = Localization.T("插件不存在", "Plugin does not exist") }); } PluginStaged.Clear(); @@ -1001,13 +1040,17 @@ private static (int, string) PluginsAction(string body) ExiledInterop.ReloadPlugins(); return Json(true, - $"已保存 {applied.Count} 个插件的启停设置" + (failed.Count > 0 ? $"({failed.Count} 个失败)" : "") + - "。LabAPI 插件需重启服务器生效。", + Localization.F("已保存 {0} 个插件的启停设置", "Saved enabled state for {0} plugin(s)", applied.Count) + + (failed.Count > 0 + ? Localization.F("({0} 个失败)", " ({0} failed)", failed.Count) + : "") + + Localization.T("。LabAPI 插件需重启服务器生效。", + ". LabAPI plugins require a server restart."), new { applied, failed }); } if (req != null && !string.IsNullOrEmpty(req.action) && req.action != "list") - throw new InvalidOperationException($"未知 action: {req.action}"); + throw new InvalidOperationException(Localization.F("未知 action: {0}", "Unknown action: {0}", req.action)); // 列表:enabled 读【配置文件】(LabAPI properties.yml / EXILED is_enabled), // 而非运行时状态 —— 运行时可能被全局禁用/重载中,不代表配置文件里的启停设置 @@ -1052,7 +1095,8 @@ private static (int, string) PluginsAction(string body) }, out var err); if (err != null) - return (500, Json(false, $"插件操作失败: {err.Message}")); + return (500, Json(false, Localization.F("插件操作失败: {0}", "Plugin operation failed: {0}", err.Message), + code: Localization.CodeOperationFailed)); return (200, json); } @@ -1090,7 +1134,8 @@ private static (int, string) BanListAction() }, out var err); if (err != null) - return (500, Json(false, $"封禁列表读取失败: {err.Message}")); + return (500, Json(false, Localization.F("封禁列表读取失败: {0}", "Failed to read ban list: {0}", err.Message), + code: Localization.CodeOperationFailed)); return (200, json); } @@ -1117,7 +1162,8 @@ private static (int, string) BanRevokeAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.user_id)) - return (400, Json(false, "缺少 user_id 字段")); + return (400, Json(false, Localization.T("缺少 user_id 字段", "Missing user_id field"), + code: Localization.CodeInvalidArgument)); bool ok = MainThreadExecutor.RunOnMainThread(() => { @@ -1131,13 +1177,15 @@ private static (int, string) BanRevokeAction(string body) }, out var err); if (err != null) - return (500, Json(false, $"解除封禁失败: {err.Message}")); + return (500, Json(false, Localization.F("解除封禁失败: {0}", "Failed to revoke ban: {0}", err.Message), + code: Localization.CodeOperationFailed)); if (!ok) - return (404, Json(false, $"未找到该封禁记录: {req.user_id}")); + return (404, Json(false, Localization.F("未找到该封禁记录: {0}", "Ban record not found: {0}", req.user_id), + code: Localization.CodeNotFound)); Log.Info($"[SLDataAPI][Control] 解除封禁 user_id={req.user_id}"); - return (200, Json(true, "已解除封禁")); + return (200, Json(true, Localization.T("已解除封禁", "Ban revoked"))); } // ------------------------------------------------------------------ @@ -1147,7 +1195,8 @@ private static (int, string) BanAddAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.user_id)) - return (400, Json(false, "缺少 user_id 字段")); + return (400, Json(false, Localization.T("缺少 user_id 字段", "Missing user_id field"), + code: Localization.CodeInvalidArgument)); string userId = req.user_id.Trim(); GameBanType bt = req.ban_type == "ip" ? GameBanType.IP : GameBanType.UserId; @@ -1170,13 +1219,15 @@ private static (int, string) BanAddAction(string body) }, out var err); if (err != null) - return (500, Json(false, $"封禁失败: {err.Message}")); + return (500, Json(false, Localization.F("封禁失败: {0}", "Ban failed: {0}", err.Message), + code: Localization.CodeOperationFailed)); if (!ok) - return (400, Json(false, "封禁写入失败(IssueBan 返回 false)")); + return (400, Json(false, Localization.T("封禁写入失败(IssueBan 返回 false)", + "Failed to write ban (IssueBan returned false)"), code: Localization.CodeOperationFailed)); Log.Info($"[SLDataAPI][Control] 新增封禁 user_id={userId} type={req.ban_type} duration={req.duration}min"); - return (200, Json(true, "已封禁")); + return (200, Json(true, Localization.T("已封禁", "Banned"))); } // ------------------------------------------------------------------ @@ -1213,7 +1264,7 @@ private static (int, string) FilesAction(string body, string kind) var req = Parse(body); string root = Plugin.Instance?.Config.FileRoot ?? ""; if (!FileService.IsEnabled(root)) - return (404, Json(false, "文件端点未启用(服务器未配置 FileRoot)")); + return (404, Json(false, Localization.FileRootNotConfigured, code: Localization.CodeServiceUnavailable)); try { @@ -1222,7 +1273,7 @@ private static (int, string) FilesAction(string body, string kind) "list" => FileService.List(root, req?.path ?? ""), "read" => FileService.Read(root, req?.path ?? ""), "write" => FileService.Write(root, req?.path ?? "", req?.content ?? ""), - _ => throw new InvalidOperationException("未知文件操作") + _ => throw new InvalidOperationException(Localization.T("未知文件操作", "Unknown file operation")) }; return (200, Json(true, "ok", data)); } @@ -1245,15 +1296,17 @@ private static (int, string) FilesAction(string body, string kind) private static (int, string) FilesBetaAction(string body, string kind, string? actor) { if (Plugin.Instance?.Config.BetaFileRootWs != true) - return (404, Json(false, "内测端点未开启(config: beta_file_root_ws: false)")); + return (404, Json(false, Localization.T("内测端点未开启(config: beta_file_root_ws: false)", + "Beta endpoint is disabled (config: beta_file_root_ws: false)"), code: Localization.CodeNotFound)); string root = Plugin.Instance?.Config.FileRoot ?? ""; if (!FileService.IsEnabled(root)) - return (404, Json(false, "文件端点未启用(服务器未配置 FileRoot)")); + return (404, Json(false, Localization.FileRootNotConfigured, code: Localization.CodeServiceUnavailable)); JObject req; try { req = string.IsNullOrWhiteSpace(body) ? new JObject() : JObject.Parse(body); } - catch { return (400, Json(false, "请求体不是合法 JSON 对象")); } + catch { return (400, Json(false, Localization.T("请求体不是合法 JSON 对象", "Request body is not a valid JSON object"), + code: Localization.CodeInvalidArgument)); } string relPath = req["path"]?.ToString() ?? ""; string who = actor ?? ""; @@ -1279,22 +1332,29 @@ private static (int, string) FilesBetaAction(string body, string kind, string? a if (action == "abort") { bool removed = FileUploads.Abort(uploadId, who); - return (200, Json(true, removed ? "已取消上传" : "会话不存在或已过期", new { upload_id = uploadId, aborted = removed })); + return (200, Json(true, removed + ? Localization.T("已取消上传", "Upload cancelled") + : Localization.T("会话不存在或已过期", "Session does not exist or has expired"), + new { upload_id = uploadId, aborted = removed })); } if (action != "append") - return (400, Json(false, $"未知 action: {action}(支持 append / abort)")); + return (400, Json(false, Localization.F("未知 action: {0}(支持 append / abort)", + "Unknown action: {0} (supported: append / abort)", action), code: Localization.CodeInvalidArgument)); long offset = req["offset"]?.Value() ?? 0; bool final = req["final"]?.Value() ?? false; string? sha = req["sha256"]?.ToString(); byte[] chunk; try { chunk = Convert.FromBase64String(req["data"]?.ToString() ?? ""); } - catch { return (400, Json(false, "data 不是合法 base64")); } + catch { return (400, Json(false, Localization.T("data 不是合法 base64", "data is not valid base64"), + code: Localization.CodeInvalidArgument)); } if (string.IsNullOrEmpty(uploadId)) { if (offset != 0) - return (400, Json(false, "新上传必须从 offset 0 开始(或携带 upload_id 续传)")); + return (400, Json(false, Localization.T("新上传必须从 offset 0 开始(或携带 upload_id 续传)", + "A new upload must start at offset 0 (or include upload_id to resume)"), + code: Localization.CodeInvalidArgument)); FileService.PreflightWrite(root, relPath); // 开会话前就跑完全部写入防线,越界/受保护路径立即拒绝 uploadId = FileUploads.Begin(who, relPath); } @@ -1305,11 +1365,12 @@ private static (int, string) FilesBetaAction(string body, string kind, string? a byte[] all = FileUploads.Complete(uploadId, who, relPath, sha); object written = FileService.WriteBytes(root, relPath, all); - return (200, Json(true, "已写入", new { upload_id = uploadId, received, committed = true, file = written })); + return (200, Json(true, Localization.T("已写入", "Written"), + new { upload_id = uploadId, received, committed = true, file = written })); } default: - return (400, Json(false, "未知文件操作")); + return (400, Json(false, Localization.T("未知文件操作", "Unknown file operation"), code: Localization.CodeInvalidArgument)); } } catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || ex is IOException || @@ -1351,22 +1412,25 @@ private static string AuditBody(string path, string body) private static (int, string) AdaptedPluginAction(string path, string body, string? actor) { if (Plugin.Instance?.Config.BetaAdaptedPluginActions != true) - return (404, Json(false, "内测端点未开启(config: beta_adapted_plugin_actions: false)")); + return (404, Json(false, Localization.T("内测端点未开启(config: beta_adapted_plugin_actions: false)", + "Beta endpoint is disabled (config: beta_adapted_plugin_actions: false)"), code: Localization.CodeNotFound)); string rest = path.Substring(AdaptedActionPrefix.Length); string[] segs = rest.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segs.Length != 2) - return (404, Json(false, "路径不存在(需要 /control/adapted//)")); + return (404, Json(false, Localization.T("路径不存在(需要 /control/adapted//)", + "Path not found (expected /control/adapted//)"), code: Localization.CodeNotFound)); string pluginId = segs[0]; string actionPath = segs[1]; if (pluginId.Contains("..") || actionPath.Contains("..")) - return (400, Json(false, "invalid path")); + return (400, Json(false, Localization.T("invalid path", "invalid path"), code: Localization.CodeInvalidArgument)); if (!string.IsNullOrWhiteSpace(body)) { try { JToken.Parse(body); } - catch { return (400, Json(false, "请求体不是合法 JSON")); } + catch { return (400, Json(false, Localization.T("请求体不是合法 JSON", "Request body is not valid JSON"), + code: Localization.CodeInvalidArgument)); } } string transport = Plugin.Instance?.Config.ControlTransport ?? "http"; @@ -1378,7 +1442,8 @@ private static (int, string) AdaptedPluginAction(string path, string body, strin if (err != null) { Log.Warn($"[SLDataAPI][Control] adapted action dispatch failed {pluginId}/{actionPath}: {err.Message}"); - return (504, Json(false, "动作超时或派发失败")); + return (504, Json(false, Localization.T("动作超时或派发失败", "Action timed out or dispatch failed"), + code: Localization.CodeTimeout)); } if (st >= 200 && st < 300) @@ -1392,29 +1457,30 @@ private static (int, string) AdaptedPluginAction(string path, string body, strin } // 插件 / 注册表返回的错误体形如 {"success":false,"message":...},统一转成 ControlResponse - string msg = "动作失败"; + string msg = Localization.T("动作失败", "Action failed"); try { msg = JObject.Parse(data ?? "{}")["message"]?.ToString() ?? msg; } catch { /* 留默认 */ } - return (st <= 0 ? 500 : st, Json(false, msg)); + return (st <= 0 ? 500 : st, Json(false, msg, code: Localization.ErrorCodeFor(st <= 0 ? 500 : st, msg))); } // ------------------------------------------------------------------ // 2.6 辅助:占位 / 玩家档案只读 / 审计列表 / 地图路径拆分 // ------------------------------------------------------------------ private static (int, string) Stub501(string name) => - (501, Json(false, $"端点尚未实现: {name}")); + (501, Json(false, Localization.F("端点尚未实现: {0}", "Endpoint not implemented: {0}", name), + code: Localization.CodeNotImplemented)); private static (int, string) PlayerDataAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.target)) - return (400, Json(false, "缺少 target 字段")); + return (400, Json(false, Localization.T("缺少 target 字段", "Missing target field"), code: Localization.CodeInvalidArgument)); var (status, json) = MainThreadExecutor.RunOnMainThread(() => { // 不按 IP 匹配:UserId 精确 → PlayerId → UserId(忽略大小写)→ 昵称精确 → 昵称模糊 var p = Player.Get(req.target) ?? FindPlayerWithoutIp(req.target); if (p == null) - throw new InvalidOperationException($"未找到玩家: {req.target}"); + throw new InvalidOperationException(Localization.F("未找到玩家: {0}", "Player not found: {0}", req.target)); // 14.2.8:PlayerEffectsController.EnabledEffects(旧版自动回落),效果可提供开门权限(TemporaryBypass) var enabled = HolidayFeatures.EnabledEffects(p.ReferenceHub); var effectDoor = Interactables.Interobjects.DoorUtils.DoorPermissionFlags.None; @@ -1504,11 +1570,14 @@ private static (int, string) MapFacilityAction(string body) { var req = Parse(body); if (req == null || string.IsNullOrWhiteSpace(req.action)) - return (400, Json(false, "缺少 action 字段(doors / elevators / lights)")); + return (400, Json(false, Localization.T("缺少 action 字段(doors / elevators / lights)", + "Missing action field (doors / elevators / lights)"), code: Localization.CodeInvalidArgument)); string action = req.action.ToLowerInvariant(); if (action is "layout" or "seed") - return (400, Json(false, "layout/seed 请分别调用 /control/map/layout 与 /control/map/seed")); + return (400, Json(false, Localization.T("layout/seed 请分别调用 /control/map/layout 与 /control/map/seed", + "Call /control/map/layout and /control/map/seed separately for layout/seed"), + code: Localization.CodeInvalidArgument)); // lights 新参数预校验(color / flicker_seconds),非法值直接 400,不进主线程 float lr = 0f, lg = 0f, lb = 0f, la = 0f, flicker = 0f; @@ -1517,9 +1586,12 @@ private static (int, string) MapFacilityAction(string body) { if (req.color != null && !FeatureInputRules.TryParseColor(req.color, out lr, out lg, out lb, out la, out colorReset)) - return (400, Json(false, $"无效颜色: {req.color}(#RGB / #RRGGBB / #RRGGBBAA / reset)", new { code = "invalid_color" })); + return (400, Json(false, Localization.F("无效颜色: {0}(#RGB / #RRGGBB / #RRGGBBAA / reset)", + "Invalid color: {0} (#RGB / #RRGGBB / #RRGGBBAA / reset)", req.color), + new { code = "invalid_color" }, code: "invalid_color")); if (req.flicker_seconds.HasValue && !FeatureInputRules.TryClampFlicker(req.flicker_seconds.Value, out flicker)) - return (400, Json(false, "无效 flicker_seconds", new { code = "invalid_flicker" })); + return (400, Json(false, Localization.T("无效 flicker_seconds", "Invalid flicker_seconds"), + new { code = "invalid_flicker" }, code: "invalid_flicker")); } var (mapStatus, mapJson) = MainThreadExecutor.RunOnMainThread(() => @@ -1547,13 +1619,15 @@ private static (int, string) MapFacilityAction(string body) { Door? door = FindDoor(req.door_type); if (door == null) - throw new InvalidOperationException($"未找到门: {req.door_type}"); + throw new InvalidOperationException(Localization.F("未找到门: {0}", "Door not found: {0}", req.door_type)); targets = new List { door }; } if (targets.Count == 0) throw new InvalidOperationException( - scope == "type" ? $"未找到门: {req.door_type}" : "未找到任何符合条件的门"); + scope == "type" + ? Localization.F("未找到门: {0}", "Door not found: {0}", req.door_type) + : Localization.T("未找到任何符合条件的门", "No matching doors found")); // 逐门操作并防御:单门失败(已销毁/网络同步异常)不中断整批 int locked = 0, unlocked = 0, opened = 0, closed = 0, failed = 0; @@ -1577,7 +1651,9 @@ private static (int, string) MapFacilityAction(string body) } return (200, Json(true, - $"已处理 {targets.Count} 扇门(锁定 {locked}/解锁 {unlocked}/开 {opened}/关 {closed}/失败 {failed})", + Localization.F("已处理 {0} 扇门(锁定 {1}/解锁 {2}/开 {3}/关 {4}/失败 {5})", + "Processed {0} door(s) (locked {1}/unlocked {2}/opened {3}/closed {4}/failed {5})", + targets.Count, locked, unlocked, opened, closed, failed), new { scope, @@ -1606,7 +1682,7 @@ private static (int, string) MapFacilityAction(string body) else { if (string.IsNullOrWhiteSpace(req.elevator_type)) - throw new InvalidOperationException("缺少 elevator_type 字段"); + throw new InvalidOperationException(Localization.T("缺少 elevator_type 字段", "Missing elevator_type field")); string typeKey = req.elevator_type.Trim(); // 1) 当前 ElevatorGroup 枚举名直接匹配(如 Nuke01/LczA01/GateA01——单轿厢粒度) @@ -1615,19 +1691,21 @@ private static (int, string) MapFacilityAction(string body) bool asAlias = ElevatorAliases.TryGetValue(typeKey, out var aliasGroups); if (!asGroup && !asAlias) - throw new InvalidOperationException( - $"未知电梯类型: {req.elevator_type}(支持当前 ElevatorGroup 名如 Nuke01/LczA01/GateA01,或旧名 Nuke/GateA/GateB/Scp049/LczA/LczB/ServerRoom)"); + throw new InvalidOperationException(Localization.F( + "未知电梯类型: {0}(支持当前 ElevatorGroup 名如 Nuke01/LczA01/GateA01,或旧名 Nuke/GateA/GateB/Scp049/LczA/LczB/ServerRoom)", + "Unknown elevator type: {0} (use a current ElevatorGroup name such as Nuke01/LczA01/GateA01, or a legacy name such as Nuke/GateA/GateB/Scp049/LczA/LczB/ServerRoom)", + req.elevator_type)); targets = Elevator.List .Where(e => (asGroup && e.Group == group) || (asAlias && aliasGroups!.Contains(e.Group))) .ToList(); if (targets.Count == 0) - throw new InvalidOperationException($"未找到电梯: {req.elevator_type}"); + throw new InvalidOperationException(Localization.F("未找到电梯: {0}", "Elevator not found: {0}", req.elevator_type)); } if (targets.Count == 0) - throw new InvalidOperationException("未找到任何电梯"); + throw new InvalidOperationException(Localization.T("未找到任何电梯", "No elevators found")); string cmd = (req.command ?? "").Trim().ToLowerInvariant(); bool sendMode = cmd == "send"; @@ -1636,10 +1714,12 @@ private static (int, string) MapFacilityAction(string body) "up" => 1, "down" => -1, "send" => 0, - _ => throw new InvalidOperationException($"未知 command: {req.command}(支持 up / down / send)"), + _ => throw new InvalidOperationException(Localization.F("未知 command: {0}(支持 up / down / send)", + "Unknown command: {0} (supported: up / down / send)", req.command)), }; if (sendMode && req.level < 0) - throw new InvalidOperationException("command=send 需要 level 字段(非负整数目标楼层)"); + throw new InvalidOperationException(Localization.T("command=send 需要 level 字段(非负整数目标楼层)", + "command=send requires the level field (a non-negative target floor)")); int moved = 0, invalid = 0; foreach (var el in targets) @@ -1678,7 +1758,12 @@ private static (int, string) MapFacilityAction(string body) } return (200, Json(true, - $"已向 {moved}/{targets.Count} 部电梯发送 {(sendMode ? $"直达 {req.level} 层" : cmd)} 指令", + Localization.F("已向 {0}/{1} 部电梯发送 {2} 指令", + "Sent {2} command to {0}/{1} elevator(s)", + moved, targets.Count, + sendMode + ? Localization.F("直达 {0} 层", "direct to floor {0}", req.level) + : cmd), new { scope = escope, @@ -1703,12 +1788,12 @@ private static (int, string) MapFacilityAction(string body) else { if (!Enum.TryParse(req.room_type, true, out var roomName)) - throw new InvalidOperationException($"无效房间类型: {req.room_type}"); + throw new InvalidOperationException(Localization.F("无效房间类型: {0}", "Invalid room type: {0}", req.room_type)); // ★ N-05:同名房间可能有多处(Room.Get 返回集合),统一全部处理(此前只处理第一间) rooms = Room.Get(roomName).ToList(); } if (rooms.Count == 0) - throw new InvalidOperationException($"未找到房间: {req.room_type}"); + throw new InvalidOperationException(Localization.F("未找到房间: {0}", "Room not found: {0}", req.room_type)); bool hasColor = req.color != null; bool hasFlicker = req.flicker_seconds.HasValue; @@ -1742,7 +1827,9 @@ private static (int, string) MapFacilityAction(string body) } default: - return (404, Json(false, $"未知 action: {req.action}(支持 layout/doors/elevators/lights)")); + return (404, Json(false, Localization.F("未知 action: {0}(支持 layout/doors/elevators/lights)", + "Unknown action: {0} (supported: layout/doors/elevators/lights)", req.action), + code: Localization.CodeNotFound)); } }, out var err); @@ -1811,12 +1898,14 @@ private static (int, string) MapExportAction() } catch (Exception ex) { - return Json(false, $"导出失败: {ex.Message}"); + return Json(false, Localization.F("导出失败: {0}", "Export failed: {0}", ex.Message), + code: Localization.CodeOperationFailed); } }, out var err); if (err != null) - return (500, Json(false, $"导出失败: {err.Message}")); + return (500, Json(false, Localization.F("导出失败: {0}", "Export failed: {0}", err.Message), + code: Localization.CodeOperationFailed)); return (200, json); } @@ -1834,8 +1923,14 @@ private static (int, string) MapExportAction() } } - private static string Json(bool success, string message, object data = null!) => - JsonConvert.SerializeObject(new ControlResponse { success = success, message = message, data = data }); + private static string Json(bool success, string message, object data = null!, string? code = null) => + JsonConvert.SerializeObject(new ControlResponse + { + success = success, + message = message, + data = data, + code = success ? null : code, + }); /// 清空插件启停暂存(插件重载时调用,X-05)。 public static void ClearPluginStaged() => PluginStaged.Clear(); diff --git a/Control/ControlMessageValidation.cs b/Control/ControlMessageValidation.cs index 30f61f4..755a462 100644 --- a/Control/ControlMessageValidation.cs +++ b/Control/ControlMessageValidation.cs @@ -3,6 +3,7 @@ // Original project: https://github.com/DNTOF/SLDataAPI using System; +using SLDataAPI.Services; namespace SLDataAPI.Control; @@ -24,13 +25,15 @@ public static bool TryValidateMessage(string? message, out string error) { if (string.IsNullOrWhiteSpace(message)) { - error = "缺少 message 字段"; + error = Localization.T("缺少 message 字段", "Missing message field"); return false; } if (message!.Length > MaxMessageLength) { - error = $"message 过长({message.Length} 字符,上限 {MaxMessageLength})"; + error = Localization.F("message 过长({0} 字符,上限 {1})", + "message is too long ({0} characters; limit {1})", + message.Length, MaxMessageLength); return false; } diff --git a/Control/WsControlService.cs b/Control/WsControlService.cs index 3be4c84..65521bf 100644 --- a/Control/WsControlService.cs +++ b/Control/WsControlService.cs @@ -84,14 +84,17 @@ public static bool TryHandle( if (method != "GET" || !IsWebSocketUpgrade(headers)) { - WriteHttpJson(stream, 400, "该路径的 WebSocket 需要 GET 升级请求(Upgrade: websocket);一次性调用请直接 POST /control/*"); + WriteHttpJson(stream, 400, Localization.T("该路径的 WebSocket 需要 GET 升级请求(Upgrade: websocket);一次性调用请直接 POST /control/*", + "This WebSocket path requires a GET upgrade request (Upgrade: websocket); for one-shot calls, POST /control/* directly"), + errorCode: Localization.CodeBadRequest); return true; } if (!config.ControlEnabled) { // 与 HTTP /control/* 的门控行为一致:未启用时一律 404 - WriteHttpJson(stream, 404, "控制接口未启用"); + WriteHttpJson(stream, 404, Localization.T("控制接口未启用", "Control API is disabled"), + errorCode: Localization.CodeNotFound); return true; } @@ -100,17 +103,18 @@ public static bool TryHandle( // data.code 是给上游平台的机器可读协商信号。 if (!string.Equals(config.ControlTransport, "ws", StringComparison.OrdinalIgnoreCase)) { - WriteHttpJson(stream, 404, "控制接口为 HTTP 模式(control_transport: http),WebSocket 未启用", - new { code = "transport_mismatch", use = "http" }); + WriteHttpJson(stream, 404, Localization.T("控制接口为 HTTP 模式(control_transport: http),WebSocket 未启用", + "Control API is in HTTP mode (control_transport: http); WebSocket is disabled"), + new { code = "transport_mismatch", use = "http" }, errorCode: "transport_mismatch"); return true; } // v2.6.0 推出,代号 PEAK:握手必须带 Authorization: Bearer 或 X-SLDataAPI-Key(不再接受 ?key= / ?token= / X-Control-Token) string? key = ApiKeyService.ExtractKeyFromHeaders(headers); - if (!ApiKeyService.TryAuthenticate(remoteIp, key, out var principal, out string authErr) || principal == null) + if (!ApiKeyService.TryAuthenticate(remoteIp, key, out var principal, out string authErr, out string authCode) || principal == null) { Log.Warn($"[SLDataAPI][WsControl] 鉴权失败 from {remoteIp}: {authErr}"); - WriteHttpJson(stream, 401, authErr); + WriteHttpJson(stream, 401, authErr, errorCode: authCode); return true; } @@ -119,13 +123,15 @@ public static bool TryHandle( { if (Sessions.Count >= MaxClients) { - WriteHttpJson(stream, 503, $"控制 WebSocket 连接数已满(上限 {MaxClients})"); + WriteHttpJson(stream, 503, Localization.F("控制 WebSocket 连接数已满(上限 {0})", + "Control WebSocket connection limit reached (max {0})", MaxClients), errorCode: Localization.CodeServiceUnavailable); return true; } } if (!headers.TryGetValue("Sec-WebSocket-Key", out string? wsKey) || string.IsNullOrEmpty(wsKey)) { - WriteHttpJson(stream, 400, "缺少 Sec-WebSocket-Key"); + WriteHttpJson(stream, 400, Localization.T("缺少 Sec-WebSocket-Key", "Missing Sec-WebSocket-Key"), + errorCode: Localization.CodeBadRequest); return true; } @@ -238,11 +244,17 @@ private static bool IsWebSocketUpgrade(Dictionary headers) return upgrade && connection; } - private static void WriteHttpJson(Stream stream, int code, string message, object? data = null) + private static void WriteHttpJson(Stream stream, int code, string message, object? data = null, string? errorCode = null) { try { - string json = JsonConvert.SerializeObject(new ControlResponse { success = false, message = message, data = data }); + string json = JsonConvert.SerializeObject(new ControlResponse + { + success = false, + message = message, + data = data, + code = errorCode ?? Localization.ErrorCodeFor(code, message), + }); byte[] body = Encoding.UTF8.GetBytes(json); string reason = code switch { @@ -302,6 +314,7 @@ public void PushEvent(string eventType, JObject data) ["event"] = eventType, ["utc"] = DateTime.UtcNow.ToString("o"), ["data"] = data, + ["lang"] = Localization.Language, }; SendJson(o); } @@ -321,6 +334,7 @@ public void Run() ["cert_fingerprint"] = TlsCertificateService.Mode == TlsMode.Off || TlsCertificateService.Fingerprint == null ? JValue.CreateNull() : new JValue(TlsCertificateService.Fingerprint), + ["lang"] = Localization.Language, }); var fragments = new List(1024); @@ -356,8 +370,8 @@ public void Run() for (int i = 0; i < 8; i++) len = (len << 8) | ext[i]; } - if (rsv) { CloseWith(1002, "不支持扩展位"); break; } - if (len > MaxMessageBytes) { CloseWith(1009, "消息过大"); break; } + if (rsv) { CloseWith(1002, Localization.T("不支持扩展位", "Unsupported reserved bits")); break; } + if (len > MaxMessageBytes) { CloseWith(1009, Localization.T("消息过大", "Message too large")); break; } var mask = new byte[4]; if (masked && ReadExact(mask, 4) < 4) break; @@ -372,7 +386,7 @@ public void Run() if (opcode == 0xA) { LastActivity = DateTime.UtcNow; continue; } // 数据帧:仅支持文本 - if (opcode == 0x2) { CloseWith(1003, "仅支持文本帧"); break; } + if (opcode == 0x2) { CloseWith(1003, Localization.T("仅支持文本帧", "Text frames only")); break; } if (opcode == 0x1) { fragments.Clear(); @@ -381,16 +395,16 @@ public void Run() } else if (opcode == 0x0) { - if (messageOpcode < 0) { CloseWith(1002, "意外的续帧"); break; } + if (messageOpcode < 0) { CloseWith(1002, Localization.T("意外的续帧", "Unexpected continuation frame")); break; } } - else { CloseWith(1002, "未知 opcode"); break; } + else { CloseWith(1002, Localization.T("未知 opcode", "Unknown opcode")); break; } fragments.AddRange(payload); - if (fragments.Count > MaxMessageBytes) { CloseWith(1009, "消息过大"); break; } + if (fragments.Count > MaxMessageBytes) { CloseWith(1009, Localization.T("消息过大", "Message too large")); break; } // 分片滴流防护:组装中的消息超时(攻击者可夹 ping 帧保活绕过空闲超时) if (messageOpcode >= 0 && (DateTime.UtcNow - messageStarted).TotalSeconds > MaxMessageAssemblySeconds) { - CloseWith(1008, "消息组装超时"); + CloseWith(1008, Localization.T("消息组装超时", "Message assembly timed out")); break; } if (!fin) continue; @@ -426,7 +440,7 @@ private void HandleTextMessage(string text) try { msg = JObject.Parse(text); } catch { - SendJson(new JObject { ["type"] = "error", ["message"] = "消息不是合法 JSON" }); + SendError(Localization.T("消息不是合法 JSON", "Message is not valid JSON"), Localization.CodeBadRequest); return; } @@ -434,22 +448,22 @@ private void HandleTextMessage(string text) switch (type) { case "ping": - SendJson(new JObject { ["type"] = "pong" }); + SendJson(new JObject { ["type"] = "pong", ["lang"] = Localization.Language }); return; case "subscribe_events": if (!_principal.Allows("ws:subscribe_events", wantWrite: false)) { - SendJson(new JObject { ["type"] = "error", ["message"] = "API Key 未授权 ws:subscribe_events" }); + SendError(Localization.T("API Key 未授权 ws:subscribe_events", "API key is not authorized for ws:subscribe_events"), Localization.CodeForbidden); return; } EventsSubscribed = true; - SendJson(new JObject { ["type"] = "events_subscribed" }); + SendJson(new JObject { ["type"] = "events_subscribed", ["lang"] = Localization.Language }); return; case "unsubscribe_events": EventsSubscribed = false; - SendJson(new JObject { ["type"] = "events_unsubscribed" }); + SendJson(new JObject { ["type"] = "events_unsubscribed", ["lang"] = Localization.Language }); return; case "call": @@ -457,7 +471,9 @@ private void HandleTextMessage(string text) return; default: - SendJson(new JObject { ["type"] = "error", ["message"] = $"未知消息类型: {type}(支持 ping / subscribe_events / call)" }); + SendError(Localization.F("未知消息类型: {0}(支持 ping / subscribe_events / call)", + "Unknown message type: {0} (supported: ping / subscribe_events / call)", type), + Localization.CodeInvalidArgument); return; } } @@ -469,13 +485,18 @@ private void HandleCall(JObject msg) if (string.IsNullOrWhiteSpace(path) || !path.StartsWith("/control/", StringComparison.Ordinal)) { - SendResult(reqId, ok: false, status: 400, message: "path 必须是 /control/* 端点"); + SendResult(reqId, ok: false, status: 400, + message: Localization.T("path 必须是 /control/* 端点", "path must be a /control/* endpoint"), + code: Localization.CodeInvalidArgument); return; } if (!WsCallGate.TryEnter(ref _pendingCalls, MaxConcurrentCallsPerConnection)) { - SendResult(reqId, ok: false, status: 429, message: $"并发调用过多(单连接上限 {MaxConcurrentCallsPerConnection})"); + SendResult(reqId, ok: false, status: 429, + message: Localization.F("并发调用过多(单连接上限 {0})", + "Too many concurrent calls (per-connection limit {0})", MaxConcurrentCallsPerConnection), + code: Localization.CodeTooManyRequests); return; } @@ -485,7 +506,8 @@ private void HandleCall(JObject msg) if (!_principal.Allows(path, wantWrite)) { WsCallGate.Exit(ref _pendingCalls); - SendResult(reqId, ok: false, status: 403, message: "API Key 有效但未授权该端点"); + SendResult(reqId, ok: false, status: 403, message: Localization.Forbidden, + code: Localization.CodeForbidden); return; } @@ -502,12 +524,14 @@ private void HandleCall(JObject msg) // 只有 JObject 才能安全索引 message(JValue/标量索引会抛 "Cannot access child value") string? failMessage = status == 200 ? null : (data is JObject jobj ? jobj["message"]?.ToString() : null); - SendResult(reqId, status == 200, status, failMessage, data); + string? failCode = status == 200 ? null : (data as JObject)?["code"]?.ToString(); + SendResult(reqId, status == 200, status, failMessage, data, failCode); } catch (Exception ex) { Log.Error($"[SLDataAPI][WsControl] call 异常 path={path}: {ex}"); - SendResult(reqId, ok: false, status: 500, message: "内部错误"); + SendResult(reqId, ok: false, status: 500, message: Localization.InternalError, + code: Localization.CodeInternalError); } finally { @@ -516,7 +540,8 @@ private void HandleCall(JObject msg) }); } - private void SendResult(string reqId, bool ok, int status, string? message = null, JToken? data = null) + private void SendResult(string reqId, bool ok, int status, string? message = null, JToken? data = null, + string? code = null) { var o = new JObject { @@ -527,9 +552,20 @@ private void SendResult(string reqId, bool ok, int status, string? message = nul }; if (message != null) o["message"] = message; if (data != null) o["data"] = data; + if (!string.IsNullOrEmpty(code)) o["code"] = code; + o["lang"] = Localization.Language; SendJson(o); } + private void SendError(string message, string code) => + SendJson(new JObject + { + ["type"] = "error", + ["message"] = message, + ["code"] = code, + ["lang"] = Localization.Language, + }); + private void SendJson(JObject o) => TrySendFrame(0x1, Encoding.UTF8.GetBytes(o.ToString(Formatting.None))); diff --git a/Data/ControlModels.cs b/Data/ControlModels.cs index 823220a..a70415f 100644 --- a/Data/ControlModels.cs +++ b/Data/ControlModels.cs @@ -11,6 +11,13 @@ public class ControlResponse public bool success { get; set; } public string message { get; set; } = ""; public object? data { get; set; } + + /// 稳定错误码(snake_case,不随 language 变化);成功响应不带该字段。 + [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? code { get; set; } + + /// 当前输出语言:zh-CN / en。 + public string lang { get; set; } = SLDataAPI.Services.Localization.Language; } /// POST /control/command diff --git a/Data/Models.cs b/Data/Models.cs index 0ec6537..97c7cf9 100644 --- a/Data/Models.cs +++ b/Data/Models.cs @@ -18,6 +18,12 @@ public class PlayerInfo public float x { get; set; } public float y { get; set; } public float z { get; set; } + + /// 角色稳定代码:RoleTypeId 枚举成员名(不随 language 变化)。 + public string role_code { get; set; } = ""; + + /// 阵营稳定代码:Team 枚举成员名(不随 language 变化)。 + public string team_code { get; set; } = ""; } public class ServerData @@ -57,6 +63,15 @@ public class ServerData /// (including DNT_OF wrappers and third-party plugins). No allowlist. /// public List adapted_plugins { get; set; } = new(); + + /// 回合阶段稳定代码:waiting / in_progress / ended(不随 language 变化)。 + public string phase_code { get; set; } = ""; + + /// 核弹状态稳定代码:inactive / armed / detonating / detonated(不随 language 变化)。 + public string warhead_code { get; set; } = ""; + + /// 当前输出语言:zh-CN / en。 + public string lang { get; set; } = "zh-CN"; } /// Discovery entry for one adapted plugin (get_sl_data + /plugins/adapted). diff --git a/Integrations/DntofDetector.cs b/Integrations/DntofDetector.cs index 6f4833e..fcfe29e 100644 --- a/Integrations/DntofDetector.cs +++ b/Integrations/DntofDetector.cs @@ -8,6 +8,7 @@ using System.Linq; using LabApi.Loader; using SLDataAPI.Data; +using SLDataAPI.Services; namespace SLDataAPI.Integrations; @@ -159,7 +160,7 @@ private static void SyncRegistryWrappers(DntofInfo info) result.coin_holders.Add(new CoinHolderInfo { - nickname = nickname ?? "未知", + nickname = nickname ?? Localization.T("未知", "Unknown"), count = valCount is int c ? c : 0, position = FormatPosition(positionObj) ?? "" }); diff --git a/Integrations/ExiledInterop.cs b/Integrations/ExiledInterop.cs index 5a91c51..095dd64 100644 --- a/Integrations/ExiledInterop.cs +++ b/Integrations/ExiledInterop.cs @@ -8,6 +8,7 @@ using System.IO; using System.Linq; using System.Reflection; +using SLDataAPI.Services; namespace SLDataAPI.Integrations; @@ -154,21 +155,21 @@ public static (string Name, string Author, string Version, string Prefix, string { var config = GetProp(plugin, "Config"); if (config == null) - return "插件没有配置对象"; + return Localization.T("插件没有配置对象", "The plugin does not expose a configuration object"); var isEnabled = config.GetType().GetProperty("IsEnabled", BindingFlags.Public | BindingFlags.Instance); if (isEnabled == null || !isEnabled.CanWrite) - return "配置对象缺少可写的 IsEnabled"; + return Localization.T("配置对象缺少可写的 IsEnabled", "The configuration object has no writable IsEnabled"); isEnabled.SetValue(config, enabled); string? configPath = GetString(plugin, "ConfigPath"); if (string.IsNullOrWhiteSpace(configPath)) - return "插件未暴露 ConfigPath"; + return Localization.T("插件未暴露 ConfigPath", "The plugin does not expose ConfigPath"); Resolve(); object? serializer = _serializerProp?.GetValue(null); if (serializer == null) - return "EXILED 序列化器不可用"; + return Localization.T("EXILED 序列化器不可用", "The EXILED serializer is not available"); // 兼容 Serialize(object) 与 Serialize(T) 两种签名 var methods = serializer.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance) @@ -187,7 +188,7 @@ public static (string Name, string Author, string Version, string Prefix, string serialized = generic.MakeGenericMethod(config.GetType()).Invoke(serializer, new[] { config }); } if (serialized is not string yaml) - return "序列化结果不是文本"; + return Localization.T("序列化结果不是文本", "The serializer did not return text"); File.WriteAllText(configPath, yaml, System.Text.Encoding.UTF8); return null; diff --git a/Integrations/PluginEndpointRegistry.cs b/Integrations/PluginEndpointRegistry.cs index e104d4d..b26d4b4 100644 --- a/Integrations/PluginEndpointRegistry.cs +++ b/Integrations/PluginEndpointRegistry.cs @@ -10,6 +10,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SLDataAPI.Data; +using SLDataAPI.Services; namespace SLDataAPI.Integrations; @@ -484,7 +485,13 @@ private static List NormalizeActions(IEnumerable? } private static string Err(string message) => - JsonConvert.SerializeObject(new { success = false, message }); + JsonConvert.SerializeObject(new + { + success = false, + message, + code = Localization.ErrorCodeFor(400, message), + lang = Localization.Language, + }); private sealed class Registration { diff --git a/Integrations/SlPlayerController.cs b/Integrations/SlPlayerController.cs index bb41e87..e28603f 100644 --- a/Integrations/SlPlayerController.cs +++ b/Integrations/SlPlayerController.cs @@ -9,6 +9,7 @@ using System.Reflection; using LabApi.Loader; using Newtonsoft.Json; +using SLDataAPI.Services; namespace SLDataAPI.Integrations; @@ -37,10 +38,11 @@ public static object GetController() { object? plugin = FindPlugin(); if (plugin == null) - throw new InvalidOperationException("SLPlayer 插件未加载"); + throw new InvalidOperationException(Localization.T("SLPlayer 插件未加载", "SLPlayer plugin is not loaded")); object? controller = plugin.GetType().GetProperty("Controller")?.GetValue(plugin); if (controller == null) - throw new InvalidOperationException("SLPlayer 控制器未就绪(插件可能仍在初始化)"); + throw new InvalidOperationException(Localization.T("SLPlayer 控制器未就绪(插件可能仍在初始化)", + "SLPlayer controller is not ready (the plugin may still be initializing)")); return controller; } @@ -49,7 +51,8 @@ public static object GetController() { MethodInfo? mi = target.GetType().GetMethod(method, BindingFlags.Public | BindingFlags.Instance, null, argTypes, null); if (mi == null) - throw new InvalidOperationException($"SLPlayer 缺少方法 {method}(版本不兼容?)"); + throw new InvalidOperationException(Localization.F("SLPlayer 缺少方法 {0}(版本不兼容?)", + "SLPlayer is missing method {0} (incompatible version?)", method)); return mi.Invoke(target, args); } @@ -58,7 +61,8 @@ public static object GetController() { PropertyInfo? pi = target.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance); if (pi == null) - throw new InvalidOperationException($"SLPlayer 缺少属性 {name}(版本不兼容?)"); + throw new InvalidOperationException(Localization.F("SLPlayer 缺少属性 {0}(版本不兼容?)", + "SLPlayer is missing property {0} (incompatible version?)", name)); return pi.GetValue(target); } @@ -134,32 +138,33 @@ private static System.Collections.Generic.List BuildPlaylist(IList? play public static string Play(object controller, int index) { object? result = Call(controller, "PlayIndex", new[] { typeof(int) }, new object[] { index }); - return result as string ?? "已触发播放"; + return result as string ?? Localization.T("已触发播放", "Playback started"); } public static string PlayNext(object controller) { object? result = Call(controller, "PlayNext", Type.EmptyTypes, Array.Empty()); - return result as string ?? "已切换下一首"; + return result as string ?? Localization.T("已切换下一首", "Skipped to next track"); } public static string Stop(object controller) { Call(controller, "Stop", Type.EmptyTypes, Array.Empty()); - return "音乐已停止播放"; + return Localization.T("音乐已停止播放", "Music stopped"); } public static string SetVolume(object controller, int volumePercent) { object? result = Call(controller, "SetVolume", new[] { typeof(float) }, new object[] { volumePercent / 100f }); - return result as string ?? $"音量已设置为 {volumePercent}%"; + return result as string ?? Localization.F("音量已设置为 {0}%", "Volume set to {0}%", volumePercent); } public static string SetShuffle(object controller, string mode) { PropertyInfo? pi = controller.GetType().GetProperty("IsShuffle", BindingFlags.Public | BindingFlags.Instance); if (pi == null) - throw new InvalidOperationException("SLPlayer 缺少 IsShuffle 属性(版本不兼容?)"); + throw new InvalidOperationException(Localization.T("SLPlayer 缺少 IsShuffle 属性(版本不兼容?)", + "SLPlayer is missing the IsShuffle property (incompatible version?)")); bool cur = pi.GetValue(controller) is true; bool next = mode switch @@ -169,13 +174,16 @@ public static string SetShuffle(object controller, string mode) _ => !cur }; pi.SetValue(controller, next); - return next ? "已切换为随机模式" : "已切换为顺序模式"; + return next + ? Localization.T("已切换为随机模式", "Shuffle enabled") + : Localization.T("已切换为顺序模式", "Shuffle disabled"); } public static string Reload(object controller) { object? result = Call(controller, "ScanFiles", Type.EmptyTypes, Array.Empty()); int count = result is int n ? n : 0; - return $"扫描完成,共加载 {count} 首本地歌曲"; + return Localization.F("扫描完成,共加载 {0} 首本地歌曲", + "Scan complete; {0} local songs loaded", count); } } diff --git a/Plugin.cs b/Plugin.cs index e2fa5f3..da96b1c 100644 --- a/Plugin.cs +++ b/Plugin.cs @@ -27,15 +27,22 @@ public class Plugin : LabApi.Loader.Features.Plugins.Plugin private HttpServer? server; public override string Name => "SLDataAPI"; - public override string Description => "通过 HTTP API 向外部(WebUI / 机器人)提供服务器数据采集与远程控制能力(LabAPI 原生插件,v2.6.2-patch,代号 Holiday26)"; + public override string Description => "通过 HTTP API 向外部(WebUI / 机器人)提供服务器数据采集与远程控制能力(LabAPI 原生插件,v2.6.3,代号 Saluton)"; public override string Author => "DNT_OF"; - public override Version Version => new Version(2, 6, 2); + public override Version Version => new Version(2, 6, 3); public override Version RequiredApiVersion => new Version(1, 1, 7); public override void Enable() { Instance = this; + // 接口输出语言:必须在任何 HTTP / WS 服务启动前生效。 + // zh-CN(默认)保持所有既有中文字段逐字不变;非法值回退 zh-CN 并告警。 + if (!Localization.SetLanguage(Config.Language)) + { + Log.Warn($"[SLDataAPI] 配置 language 值非法: \"{Config.Language}\"(仅支持 zh-CN / en),本次按 zh-CN 处理。"); + } + LabApi.Events.Handlers.ServerEvents.WaitingForPlayers += OnWaitingForPlayers; LabApi.Events.Handlers.ServerEvents.RoundStarted += OnRoundStarted; LabApi.Events.Handlers.ServerEvents.RoundEnded += OnRoundEnded; @@ -104,7 +111,7 @@ public override void Enable() $"control={(Config.ControlEnabled ? $"{Config.ControlTransport} 模式,API Key 鉴权" : "关闭")}," + $"voice={(Config.VoiceEnabled ? $"启用(端口 {Config.VoicePort})" : "关闭")}," + $"录音={(Config.VoiceRecordEnabled ? $"开(保留 {Config.VoiceRecordMaxRounds} 局)" : "关")}," + - $"webdav={(Config.WebdavUploadEnabled ? "开" : "关")}。"); + $"webdav={(Config.WebdavUploadEnabled ? "开" : "关")},language={Localization.Language}。"); // 插件配置目录(configs//SLDataAPI/):TLS 证书、举报、API Key、审计日志共用 string reportConfigDir = ""; @@ -165,7 +172,7 @@ public override void Enable() string httpStatus = server != null ? $"HTTP on port {Config.HttpPort}" + (dataPlaneOk ? "" : "(仅控制面,数据口已关闭)") : "HTTP 未绑定"; - Log.Info($"SLDataAPI v{Version} (2.6.2-patch Holiday26 / LabAPI) enabled. {httpStatus}. Control API: {(Config.ControlEnabled ? $"{Config.ControlTransport.ToUpperInvariant()} 模式,API Key" : "关闭")}. Voice: {(Config.VoiceEnabled ? $"启用(端口 {Config.VoicePort})" : "关闭")}. {tlsBanner}."); + Log.Info($"SLDataAPI v{Version} (2.6.3 Saluton / LabAPI) enabled. {httpStatus}. Control API: {(Config.ControlEnabled ? $"{Config.ControlTransport.ToUpperInvariant()} 模式,API Key" : "关闭")}. Voice: {(Config.VoiceEnabled ? $"启用(端口 {Config.VoicePort})" : "关闭")}. {tlsBanner}."); } public override void Disable() diff --git a/README.md b/README.md index 314565f..9b3cc35 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ curl -H "Authorization: Bearer " http://:8081/get_sl_data ```yaml debug: false +language: "zh-CN" # zh-CN(默认)| en:接口文本语言;zh-CN 下既有输出逐字不变 verify_token: "your_secret_token" # 必须改成强随机值;默认/弱口令会 fail-closed 关闭数据口 http_port: 8081 push_interval_seconds: 8 @@ -173,6 +174,18 @@ control_log_enabled: true 完整字段、YAML 常见坑、token 写法见 Wiki [Configuration](https://github.com/DNTOF/SLDataAPI/wiki/Configuration)。 +### 多语言与稳定 code / Language & stable codes + +- `language`:`"zh-CN"`(默认)或 `"en"`。非法值回退 `zh-CN` 并在启动日志告警。仅影响插件生成的 HTTP / WebSocket 文本;玩家昵称、控制台回显、封禁 / 踢出 / 解封原因等外部内容原样透传。 +- 稳定 code 与语言无关(`language` 切换时值不变)。错误文本经 `Localization.T/F` 生成时,en 结果会在有界缓存中记录“英文结果 → 中文结果”映射;`error.code` 推断先还原成中文文本,再复用 zh-CN 的同一套规则,zh-CN 路径与既有结果完全一致: + - `role_code`:`RoleTypeId` 枚举成员名(如 `Spectator` / `Tutorial` / `NtfCaptain`) + - `team_code`:`Team` 枚举成员名(如 `ClassD` / `ChaosInsurgency` / `FoundationForces` / `SCPs` / `Dead` / `OtherAlive`) + - `phase_code`:`waiting` / `in_progress` / `ended` + - `warhead_code`:`inactive` / `armed` / `detonating` / `detonated` + - `error.code`(控制面错误对象的 `code` 字段):snake_case,至少包含 `timeout` / `symlink_forbidden` / `unauthorized` / `forbidden` / `not_found` / `invalid_argument` +- 所有插件生成的 JSON 根对象新增 `lang`(`"zh-CN"` / `"en"`)。新字段只追加在既有字段之后。 +- English: set `language: "en"` to switch plugin-generated HTTP/WebSocket text to English. Stable codes and `lang` do not change with language; player nicknames, console output, and ban/kick/revoke reasons are passed through unchanged. + ## 🔐 鉴权与安全 | 通道 | 凭据 | 存放位置 | diff --git a/SLDataAPI.csproj b/SLDataAPI.csproj index 1c329c0..f7ee3d0 100644 --- a/SLDataAPI.csproj +++ b/SLDataAPI.csproj @@ -5,10 +5,10 @@ latest enable Library - 2.6.2 - 2.6.2.0 - 2.6.2.0 - 2.6.2-patch Holiday26 + 2.6.3 + 2.6.3.0 + 2.6.3.0 + 2.6.3 Saluton DNT_OF Copyright (C) 2026 DNT_OF Apache-2.0 diff --git a/Services/DataCollector.cs b/Services/DataCollector.cs index 484c69b..cd1b61e 100644 --- a/Services/DataCollector.cs +++ b/Services/DataCollector.cs @@ -75,15 +75,17 @@ public static string BuildJson() // 避免高频轮询时每次请求都做一次主线程派发 if (resp.round_started) { - var (nukeStatus, nukeCountdown) = MainThreadExecutor.RunOnMainThread( - () => (GetNukeStatus(), GetNukeCountdown()), out var err); + var (nukeStatus, nukeCode, nukeCountdown) = MainThreadExecutor.RunOnMainThread( + () => (GetNukeStatus(), GetWarheadCode(), GetNukeCountdown()), out var err); if (err == null) { resp.nuke_status = nukeStatus; + resp.warhead_code = nukeCode; resp.nuke_countdown = nukeCountdown; } } + resp.lang = Localization.Language; return Newtonsoft.Json.JsonConvert.SerializeObject(resp); } @@ -111,6 +113,9 @@ public static string BuildJson() players = src.players, dntof_plugins = src.dntof_plugins, adapted_plugins = src.adapted_plugins, + phase_code = src.phase_code, + warhead_code = src.warhead_code, + lang = src.lang, }; private static void UpdateData() @@ -135,12 +140,17 @@ private static void UpdateData() fresh.max_players = Server.MaxPlayers; fresh.round_started = Round.IsRoundStarted; fresh.round_duration = Round.IsRoundStarted ? (int)Round.Duration.TotalSeconds : 0; - fresh.current_phase = Round.IsRoundStarted ? "进行中" : "等待开始"; + bool roundEnded = !Round.IsRoundStarted && Round.IsRoundEnded; + fresh.current_phase = Localization.PhaseText(Round.IsRoundStarted, roundEnded); + fresh.phase_code = Localization.PhaseCode(Round.IsRoundStarted, roundEnded); // ★ 修复:Warhead 在地图加载前是 null,用 try-catch 单独保护 fresh.nuke_status = GetNukeStatus(); + fresh.warhead_code = GetWarheadCode(); fresh.nuke_countdown = GetNukeCountdown(); + fresh.lang = Localization.Language; + // ★ 修复:排除 Dummy/NPC/主机 玩家(手动添加的 dummy 会混入 Player.List 导致数据污染) var realPlayers = players.Where(p => p != null && !p.IsNpc && !p.IsHost).ToList(); @@ -172,11 +182,13 @@ private static void UpdateData() { nickname = Sanitize(p.Nickname), steam_id = p.UserId ?? "", - role = GetRoleCN(p.Role), - team = GetTeamCN(p.Team), + role = GetRoleText(p.Role), + team = GetTeamText(p.Team), x = p.Position.x, y = p.Position.y, - z = p.Position.z + z = p.Position.z, + role_code = p.Role.ToString(), + team_code = p.Team.ToString() }) .ToList(); @@ -212,64 +224,51 @@ private static int GetPing(Player p) } } - // ★ 修复:地图加载前 Warhead 对象未初始化,整个方法加保护 - private static string GetNukeStatus() + /// 核弹状态(地图加载前 Warhead 对象未初始化,读取失败按未激活处理)。 + private static (bool Detonated, bool Detonating, bool Armed, int Countdown) GetWarheadState() { try { - if (Warhead.IsDetonated) return "已爆炸"; - if (Warhead.IsDetonationInProgress) return $"倒计时:{(int)Warhead.DetonationTime}秒"; + if (Warhead.IsDetonated) return (true, false, false, 0); + if (Warhead.IsDetonationInProgress) + return (false, true, true, (int)Warhead.DetonationTime); + // LeverStatus 为 bool 时表示拉杆已拉起(armed);读取失败按未激活处理。 + bool armed = Warhead.LeverStatus is bool b && b; + return (false, false, armed, 0); + } + catch + { + // 地图加载前 / Warhead 未初始化:按未激活处理 } - catch { } - return "未激活"; + return (false, false, false, 0); + } + + private static string GetNukeStatus() + { + var s = GetWarheadState(); + return Localization.WarheadText(s.Detonated, s.Detonating, s.Countdown, s.Armed); + } + + private static string GetWarheadCode() + { + var s = GetWarheadState(); + return Localization.WarheadCode(s.Detonated, s.Detonating, s.Armed); } private static int GetNukeCountdown() { - try { return Warhead.IsDetonationInProgress ? (int)Warhead.DetonationTime : 0; } - catch { return 0; } + var s = GetWarheadState(); + return s.Detonating ? s.Countdown : 0; } private static string Sanitize(string name) => (name ?? "").Replace("\n", "").Replace("\r", "").Trim(); - private static string GetRoleCN(RoleTypeId role) => role switch - { - RoleTypeId.ClassD => "D级人员", - RoleTypeId.Scientist => "科学家", - RoleTypeId.FacilityGuard => "保安", - RoleTypeId.NtfPrivate => "九尾狐-士兵", - RoleTypeId.NtfSergeant => "九尾狐-中士", - RoleTypeId.NtfCaptain => "九尾狐-指挥官", - RoleTypeId.ChaosConscript => "混沌-征召兵", - RoleTypeId.ChaosRifleman => "混沌-步枪手", - RoleTypeId.ChaosMarauder => "混沌-掠夺者", - RoleTypeId.ChaosRepressor => "混沌-镇压者", - RoleTypeId.Scp173 => "SCP-173", - RoleTypeId.Scp049 => "SCP-049", - RoleTypeId.Scp096 => "SCP-096", - RoleTypeId.Scp106 => "SCP-106", - RoleTypeId.Scp939 => "SCP-939", - RoleTypeId.Scp079 => "SCP-079", - RoleTypeId.Scp3114 => "SCP-3114", - RoleTypeId.Scp0492 => "SCP-049-2", - RoleTypeId.Spectator => "观察者", - RoleTypeId.Tutorial => "教程", - RoleTypeId.None => "未分配", - - // ★ 诊断用:如果仍然出现未知职业,HTTP 返回值会显示 "未知(数字)" - // 把这个数字告诉开发者,就能知道是哪个 RoleTypeId 枚举值缺失了 - _ => $"未知({(int)role})" - }; + // ★ 映射按枚举成员名查表(Localization),不依赖枚举数值; + // 未知职业仍保留改造前的 "未知(数字)" 兜底,便于定位缺失的 RoleTypeId。 + private static string GetRoleText(RoleTypeId role) => + Localization.DataRoleText(role.ToString(), (int)role); - private static string GetTeamCN(Team team) => team switch - { - Team.SCPs => "SCP", - Team.FoundationForces => "基金会", - Team.ClassD => "D级", - Team.ChaosInsurgency => "混沌", - Team.Dead => "观察者", - Team.OtherAlive => "其他", // ★ 修复1:Tutorial 等非标准职业会落入此枚举值 - _ => "未知" - }; + private static string GetTeamText(Team team) => + Localization.TeamText(team.ToString()); } diff --git a/Services/ErrorCodeEnvelope.cs b/Services/ErrorCodeEnvelope.cs new file mode 100644 index 0000000..d15e29e --- /dev/null +++ b/Services/ErrorCodeEnvelope.cs @@ -0,0 +1,49 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace SLDataAPI.Services; + +/// +/// 错误响应 code 补齐(纯逻辑,仅依赖 Newtonsoft,可供单元测试直接链接)。 +/// +/// 只解析 JSON 用于判断 success / 既有 code / data.code / message,然后 +/// 在根对象末尾**字符串追加** "code":"...",不重新序列化。 +/// 这样 zh-CN 下既有字段的值、转义与顺序保持逐字不变(浮点数、\uXXXX、 +/// 控制字符、Unicode 等不会被 JObject 重新格式化)。 +/// +public static class ErrorCodeEnvelope +{ + public static string EnsureErrorCode(int status, string json) + { + if (status < 400 || string.IsNullOrEmpty(json)) return json; + + try + { + var o = JObject.Parse(json); + if (o["success"]?.Type == JTokenType.Boolean && (bool)o["success"]!) return json; + + // 已有顶层 code 时不重复追加(避免产生同名键或改动既有字段)。 + if (o["code"] != null) return json; + + string? code = o["data"] is JObject d ? d["code"]?.ToString() : null; + if (string.IsNullOrEmpty(code)) + code = Localization.ErrorCodeFor(status, o["message"]?.ToString()); + if (string.IsNullOrEmpty(code)) return json; + + int end = json.LastIndexOf('}'); + if (end < 0) return json; + + return json.Substring(0, end) + ",\"code\":" + JsonConvert.ToString(code) + json.Substring(end); + } + catch + { + // 非法 JSON / 非对象体:保持原样,绝不因补 code 破坏响应。 + return json; + } + } +} diff --git a/Services/FileSandbox.cs b/Services/FileSandbox.cs index 9dedbc3..dcc70f0 100644 --- a/Services/FileSandbox.cs +++ b/Services/FileSandbox.cs @@ -24,28 +24,31 @@ public static class FileSandbox public static string Resolve(string root, string? relPath, bool rejectReparsePoints = true) { if (string.IsNullOrWhiteSpace(root)) - throw new InvalidOperationException("文件端点未启用(服务器未配置 FileRoot)"); + throw new InvalidOperationException(Localization.FileRootNotConfigured); string fullRoot; try { fullRoot = Path.GetFullPath(root.Trim()); } - catch (Exception ex) { throw new InvalidOperationException($"FileRoot 非法: {ex.Message}"); } + catch (Exception ex) { throw new InvalidOperationException(Localization.F("FileRoot 非法: {0}", "Invalid FileRoot: {0}", ex.Message)); } if (!Directory.Exists(fullRoot)) - throw new InvalidOperationException($"FileRoot 目录不存在({Path.GetFileName(fullRoot.TrimEnd(Path.DirectorySeparatorChar))})"); + throw new InvalidOperationException(Localization.F("FileRoot 目录不存在({0})", + "FileRoot directory does not exist ({0})", + Path.GetFileName(fullRoot.TrimEnd(Path.DirectorySeparatorChar)))); // X-09:拒绝含冒号的相对路径(Windows 盘符外的 ":" 即 NTFS 备用数据流) if ((relPath ?? "").IndexOf(':') >= 0) - throw new ArgumentException("路径含非法字符 ':'"); + throw new ArgumentException(Localization.T("路径含非法字符 ':'", "Path contains an invalid character ':'")); // 统一分隔符后去掉首尾斜杠,避免 ".." 或绝对路径被 Combine 拼接出界 string rel = (relPath ?? "").Replace('\\', '/').Trim('/'); string full; try { full = Path.GetFullPath(Path.Combine(fullRoot, rel)); } - catch (Exception ex) { throw new ArgumentException($"路径非法: {ex.Message}"); } + catch (Exception ex) { throw new ArgumentException(Localization.F("路径非法: {0}", "Invalid path: {0}", ex.Message)); } string rootTrim = fullRoot.TrimEnd(Path.DirectorySeparatorChar); if (!IsInside(rootTrim, full)) - throw new ArgumentException("路径越界:不允许访问 FileRoot 之外的目录"); + throw new ArgumentException(Localization.T("路径越界:不允许访问 FileRoot 之外的目录", + "Path escapes the sandbox: access outside FileRoot is not allowed")); if (rejectReparsePoints) EnsureNoReparsePoints(rootTrim, full); @@ -91,11 +94,11 @@ public static void EnsureNoReparsePoints(string rootNoTrailingSep, string full) } catch (Exception ex) { - throw new InvalidOperationException($"路径不可访问: {ex.Message}"); + throw new InvalidOperationException(Localization.F("路径不可访问: {0}", "Path is not accessible: {0}", ex.Message)); } if ((attrs & FileAttributes.ReparsePoint) != 0) - throw new InvalidOperationException("路径经过符号链接或目录联接(junction),已拒绝(防止越出 FileRoot)"); + throw new InvalidOperationException(Localization.SymlinkForbidden); } } } diff --git a/Services/FileService.cs b/Services/FileService.cs index 259e14a..546dd28 100644 --- a/Services/FileService.cs +++ b/Services/FileService.cs @@ -127,7 +127,8 @@ private static bool IsProtected(string fullPath) private static void EnsureNotProtected(string fullPath, string action) { if (IsProtected(fullPath)) - throw new InvalidOperationException($"受保护目录(SLDataAPI 配置),禁止{action}"); + throw new InvalidOperationException(Localization.F("受保护目录(SLDataAPI 配置),禁止{0}", + "Protected directory (SLDataAPI configuration); {0} is not allowed", action)); } /// @@ -140,17 +141,19 @@ public static object List(string root, string relPath) { string full = Resolve(root, relPath); if (File.Exists(full)) - throw new ArgumentException($"不是目录: {relPath}"); + throw new ArgumentException(Localization.F("不是目录: {0}", "Not a directory: {0}", relPath)); if (!Directory.Exists(full)) - throw new ArgumentException($"目录不存在: {relPath}"); + throw new ArgumentException(Localization.F("目录不存在: {0}", "Directory does not exist: {0}", relPath)); // 顶级防线:受保护配置目录本身不可打开(无论 FileRoot 是否覆盖) - EnsureNotProtected(full, "访问"); + EnsureNotProtected(full, Localization.T("访问", "access")); // 同级防线:Windows 系统目录禁止浏览 if (IsWindowsDir(full)) - throw new InvalidOperationException("系统目录(Windows)受保护,禁止访问"); + throw new InvalidOperationException(Localization.T("系统目录(Windows)受保护,禁止访问", + "The Windows system directory is protected; access is not allowed")); // 同级防线:游戏数据目录(%AppData%/SCP Secret Laboratory)禁止浏览(防篡改游戏配置) if (IsGameDataDir(full)) - throw new InvalidOperationException("游戏数据目录(SCP Secret Laboratory)受保护,禁止访问"); + throw new InvalidOperationException(Localization.T("游戏数据目录(SCP Secret Laboratory)受保护,禁止访问", + "The game data directory (SCP Secret Laboratory) is protected; access is not allowed")); var entries = new List(); @@ -197,7 +200,8 @@ public static object Read(string root, string relPath) { var (full, info) = PreflightRead(root, relPath); if (info.Length > MaxReadBytes) - throw new InvalidOperationException($"文件过大({info.Length} 字节 > 上限 {MaxReadBytes}),拒绝读取"); + throw new InvalidOperationException(Localization.F("文件过大({0} 字节 > 上限 {1}),拒绝读取", + "File is too large ({0} bytes > limit {1}); read refused", info.Length, MaxReadBytes)); string content = File.ReadAllText(full); return new @@ -215,18 +219,22 @@ private static (string full, FileInfo info) PreflightRead(string root, string re string full = Resolve(root, relPath); // 同级防线:Windows 系统目录内禁止读取(目录级检查,先于文件存在性) if (IsWindowsDir(full)) - throw new InvalidOperationException("系统目录(Windows)受保护,禁止读取"); + throw new InvalidOperationException(Localization.T("系统目录(Windows)受保护,禁止读取", + "The Windows system directory is protected; reading is not allowed")); // 同级防线:游戏数据目录内禁止读取 if (IsGameDataDir(full)) - throw new InvalidOperationException("游戏数据目录(SCP Secret Laboratory)受保护,禁止读取"); + throw new InvalidOperationException(Localization.T("游戏数据目录(SCP Secret Laboratory)受保护,禁止读取", + "The game data directory (SCP Secret Laboratory) is protected; reading is not allowed")); if (!File.Exists(full)) - throw new ArgumentException($"文件不存在: {relPath}"); + throw new ArgumentException(Localization.F("文件不存在: {0}", "File does not exist: {0}", relPath)); // 顶级防线:受保护配置目录内禁止读取 - EnsureNotProtected(full, "打开"); + EnsureNotProtected(full, Localization.T("打开", "opening")); // 非配置文件禁止读取(exe/dll 等二进制或可执行文件) if (!IsConfigExtension(full)) - throw new InvalidOperationException( - $"非配置文件({Path.GetExtension(full)})不允许读取(仅允许配置文件:yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)"); + throw new InvalidOperationException(Localization.F( + "非配置文件({0})不允许读取(仅允许配置文件:yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)", + "Non-config file ({0}) cannot be read (allowed: yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)", + Path.GetExtension(full))); return (full, new FileInfo(full)); } @@ -235,7 +243,8 @@ public static object Write(string root, string relPath, string content) string full = PreflightWrite(root, relPath); if (content != null && content.Length > MaxWriteBytes) - throw new InvalidOperationException($"内容过大({content.Length} 字符 > 上限 {MaxWriteBytes}),拒绝写入"); + throw new InvalidOperationException(Localization.F("内容过大({0} 字符 > 上限 {1}),拒绝写入", + "Content is too large ({0} characters > limit {1}); write refused", content.Length, MaxWriteBytes)); string dir = Path.GetDirectoryName(full); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) @@ -258,20 +267,24 @@ public static string PreflightWrite(string root, string relPath) { string full = Resolve(root, relPath); if (Directory.Exists(full)) - throw new ArgumentException($"目标是目录: {relPath}"); + throw new ArgumentException(Localization.F("目标是目录: {0}", "Target is a directory: {0}", relPath)); // 顶级防线:受保护配置目录内禁止任何写入(包括新建子路径) - EnsureNotProtected(full, "修改"); + EnsureNotProtected(full, Localization.T("修改", "modification")); // 系统目录保护:Windows 目录及其子目录禁止任何写入 if (IsWindowsDir(full)) - throw new InvalidOperationException("系统目录(Windows)受保护,禁止修改"); + throw new InvalidOperationException(Localization.T("系统目录(Windows)受保护,禁止修改", + "The Windows system directory is protected; modification is not allowed")); // 游戏数据目录保护:禁止写入(防篡改游戏配置/管理员名单) if (IsGameDataDir(full)) - throw new InvalidOperationException("游戏数据目录(SCP Secret Laboratory)受保护,禁止修改"); + throw new InvalidOperationException(Localization.T("游戏数据目录(SCP Secret Laboratory)受保护,禁止修改", + "The game data directory (SCP Secret Laboratory) is protected; modification is not allowed")); // 写入白名单:只允许配置文件扩展名(yml/yaml/txt/json/cfg/ini/conf/config/xml/properties) string ext = Path.GetExtension(full); if (!WritableExtensions.Contains(ext)) - throw new InvalidOperationException( - $"文件类型 {ext} 不允许写入(仅允许配置文件:yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)"); + throw new InvalidOperationException(Localization.F( + "文件类型 {0} 不允许写入(仅允许配置文件:yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)", + "File type {0} cannot be written (allowed: yml/yaml/txt/json/cfg/ini/conf/config/xml/properties)", + ext)); return full; } @@ -325,9 +338,10 @@ public static object ReadChunk(string root, string relPath, long offset, int len { var (full, info) = PreflightRead(root, relPath); if (info.Length > MaxReadBytes) - throw new InvalidOperationException($"文件过大({info.Length} 字节 > 上限 {MaxReadBytes}),拒绝读取"); + throw new InvalidOperationException(Localization.F("文件过大({0} 字节 > 上限 {1}),拒绝读取", + "File is too large ({0} bytes > limit {1}); read refused", info.Length, MaxReadBytes)); if (offset < 0 || offset > info.Length) - throw new ArgumentException($"offset 越界(0..{info.Length})"); + throw new ArgumentException(Localization.F("offset 越界(0..{0})", "offset is out of range (0..{0})", info.Length)); if (length <= 0) length = DefaultChunkBytes; if (length > MaxChunkBytes) length = MaxChunkBytes; @@ -369,9 +383,11 @@ public static object WriteBytes(string root, string relPath, byte[] bytes) { string full = PreflightWrite(root, relPath); if (bytes.Length > MaxWriteBytes) - throw new InvalidOperationException($"内容过大({bytes.Length} 字节 > 上限 {MaxWriteBytes}),拒绝写入"); + throw new InvalidOperationException(Localization.F("内容过大({0} 字节 > 上限 {1}),拒绝写入", + "Content is too large ({0} bytes > limit {1}); write refused", bytes.Length, MaxWriteBytes)); try { new System.Text.UTF8Encoding(false, true).GetString(bytes); } - catch { throw new InvalidOperationException("内容不是合法 UTF-8 文本(文件端点只允许写入文本配置)"); } + catch { throw new InvalidOperationException(Localization.T("内容不是合法 UTF-8 文本(文件端点只允许写入文本配置)", + "Content is not valid UTF-8 text (file endpoints only accept text configuration files)")); } string dir = Path.GetDirectoryName(full); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) diff --git a/Services/FileUploadSessions.cs b/Services/FileUploadSessions.cs index 3e3f433..5c845c1 100644 --- a/Services/FileUploadSessions.cs +++ b/Services/FileUploadSessions.cs @@ -62,9 +62,12 @@ public string Begin(string actor, string path) foreach (var s in _sessions.Values) if (string.Equals(s.Actor, actor, StringComparison.Ordinal)) mine++; if (mine >= MaxSessionsPerActor) - throw new InvalidOperationException($"该 Key 未完成的上传会话过多(上限 {MaxSessionsPerActor}),请先完成或等待 {Ttl.TotalSeconds:F0}s 过期"); + throw new InvalidOperationException(Localization.F("该 Key 未完成的上传会话过多(上限 {0}),请先完成或等待 {1}s 过期", + "Too many unfinished upload sessions for this key (limit {0}); finish one or wait {1}s for expiry", + MaxSessionsPerActor, Ttl.TotalSeconds.ToString("F0"))); if (_sessions.Count >= MaxSessions) - throw new InvalidOperationException($"服务器未完成的上传会话过多(上限 {MaxSessions})"); + throw new InvalidOperationException(Localization.F("服务器未完成的上传会话过多(上限 {0})", + "Too many unfinished upload sessions on the server (limit {0})", MaxSessions)); string id = NewId(); _sessions[id] = new Session { Id = id, Actor = actor ?? "", Path = NormalizePath(path), LastTouched = _clock() }; @@ -80,11 +83,13 @@ public long Append(string uploadId, string actor, string path, long offset, byte SweepUnlocked(); var s = GetOwnedUnlocked(uploadId, actor, path); if (offset != s.Data.Length) - throw new ArgumentException($"offset 不连续:期望 {s.Data.Length},收到 {offset}"); + throw new ArgumentException(Localization.F("offset 不连续:期望 {0},收到 {1}", + "offset is not contiguous: expected {0}, got {1}", s.Data.Length, offset)); if (s.Data.Length + chunk.Length > _maxBytes) { Remove(uploadId); - throw new InvalidOperationException($"上传内容过大(> 上限 {_maxBytes} 字节),会话已作废"); + throw new InvalidOperationException(Localization.F("上传内容过大(> 上限 {0} 字节),会话已作废", + "Upload content is too large (> limit {0} bytes); the session was invalidated", _maxBytes)); } s.Data.Write(chunk, 0, chunk.Length); s.LastTouched = _clock(); @@ -103,7 +108,8 @@ public byte[] Complete(string uploadId, string actor, string path, string? expec _sessions.Remove(uploadId); if (!string.IsNullOrWhiteSpace(expectedSha256) && !string.Equals(Sha256Hex(bytes), expectedSha256!.Trim(), StringComparison.OrdinalIgnoreCase)) - throw new InvalidOperationException("sha256 校验失败:上传内容与声明不一致,未写入"); + throw new InvalidOperationException(Localization.T("sha256 校验失败:上传内容与声明不一致,未写入", + "sha256 verification failed: uploaded content does not match the declared hash; nothing was written")); return bytes; } } @@ -141,11 +147,11 @@ public static string Sha256Hex(byte[] data) private Session GetOwnedUnlocked(string uploadId, string actor, string path) { if (string.IsNullOrEmpty(uploadId) || !_sessions.TryGetValue(uploadId, out var s)) - throw new ArgumentException("upload_id 不存在或已过期"); + throw new ArgumentException(Localization.T("upload_id 不存在或已过期", "upload_id does not exist or has expired")); if (!string.Equals(s.Actor, actor ?? "", StringComparison.Ordinal)) - throw new ArgumentException("upload_id 不属于当前 Key"); + throw new ArgumentException(Localization.T("upload_id 不属于当前 Key", "upload_id does not belong to the current key")); if (!string.Equals(s.Path, NormalizePath(path), StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("upload_id 与 path 不匹配"); + throw new ArgumentException(Localization.T("upload_id 与 path 不匹配", "upload_id does not match path")); return s; } diff --git a/Services/HolidayGate.cs b/Services/HolidayGate.cs index 2c3bb6b..257bf15 100644 --- a/Services/HolidayGate.cs +++ b/Services/HolidayGate.cs @@ -111,7 +111,9 @@ public static HolidayGateResult Evaluate( if (!featurePresent) return new HolidayGateResult(false, StatusFeatureUnavailable, CodeFeatureUnavailable, feature, active, required, - $"当前游戏版本不提供该功能({feature}:所需类型或成员不存在)", simulated); + Localization.F("当前游戏版本不提供该功能({0}:所需类型或成员不存在)", + "This game version does not provide the feature ({0}: required type or member is missing)", + feature), simulated); bool matches = required.Count == 0 || required.Any(r => string.Equals(r, active, StringComparison.OrdinalIgnoreCase)); @@ -122,9 +124,14 @@ public static HolidayGateResult Evaluate( if (available) return new HolidayGateResult(true, 200, "", feature, active, required, "ok", simulated); - string need = required.Count == 0 ? "特定节日" : string.Join(" / ", required); + string need = required.Count == 0 + ? Localization.T("特定节日", "a specific holiday") + : string.Join(" / ", required); return new HolidayGateResult(false, StatusHolidayInactive, CodeHolidayInactive, feature, active, required, - $"节日功能未开启:{feature} 需要 {need},当前节日 {active}" + (simulated ? "(测试覆盖)" : ""), simulated); + Localization.F("节日功能未开启:{0} 需要 {1},当前节日 {2}", + "Holiday feature is not active: {0} requires {1}; current holiday is {2}", + feature, need, active) + + (simulated ? Localization.T("(测试覆盖)", " (test override)") : ""), simulated); } /// 空 / null / 空白 → "None";其余原样去空白。 diff --git a/Services/HttpServer.cs b/Services/HttpServer.cs index 75eacd7..f1aa345 100644 --- a/Services/HttpServer.cs +++ b/Services/HttpServer.cs @@ -169,13 +169,13 @@ private void HandleClient(TcpClient client) if (headEnd >= 0) break; if (unchecked(Environment.TickCount - startTick) > RequestDeadlineMs) { - SendJson(stream, 408, Err("请求超时:头部长时间未收完(Slowloris 防护)")); + SendJson(stream, 408, Err(Localization.TimeoutRequestHeaders, Localization.CodeTimeout)); return; } } if (headEnd < 0) { - SendJson(stream, 431, Err("请求头过大或格式非法")); + SendJson(stream, 431, Err(Localization.T("请求头过大或格式非法", "Request headers too large or malformed"), Localization.CodeRequestHeaderTooLarge)); return; } @@ -183,7 +183,7 @@ private void HandleClient(TcpClient client) string[] headLines = headText.Split('\n'); if (headLines.Length == 0) { - SendJson(stream, 400, Err("bad request")); + SendJson(stream, 400, Err(Localization.T("bad request", "bad request"), Localization.CodeBadRequest)); return; } @@ -191,7 +191,7 @@ private void HandleClient(TcpClient client) var parts = requestLine.Split(' '); if (parts.Length < 2) { - SendJson(stream, 400, Err("bad request")); + SendJson(stream, 400, Err(Localization.T("bad request", "bad request"), Localization.CodeBadRequest)); return; } @@ -232,7 +232,7 @@ private void HandleClient(TcpClient client) if (contentLength > 65536) { - SendJson(stream, 413, Err("payload too large")); + SendJson(stream, 413, Err(Localization.T("payload too large", "payload too large"), Localization.CodePayloadTooLarge)); return; } @@ -256,7 +256,7 @@ private void HandleClient(TcpClient client) total += n; if (unchecked(Environment.TickCount - startTick) > RequestDeadlineMs) { - SendJson(stream, 408, Err("请求超时:请求体长时间未收完(Slowloris 防护)")); + SendJson(stream, 408, Err(Localization.TimeoutRequestBody, Localization.CodeTimeout)); return; } } @@ -305,7 +305,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s { if (method != "GET") { - SendJson(stream, 405, Err("Method Not Allowed")); + SendJson(stream, 405, Err(Localization.T("Method Not Allowed", "Method Not Allowed"), Localization.CodeMethodNotAllowed)); return; } @@ -324,7 +324,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s { if (method != "GET") { - SendJson(stream, 405, Err("Method Not Allowed")); + SendJson(stream, 405, Err(Localization.T("Method Not Allowed", "Method Not Allowed"), Localization.CodeMethodNotAllowed)); return; } @@ -337,6 +337,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s { success = true, adapted_plugins = snapAp, + lang = Localization.Language, })); return; } @@ -346,7 +347,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s { if (method != "GET") { - SendJson(stream, 405, Err("Method Not Allowed")); + SendJson(stream, 405, Err(Localization.T("Method Not Allowed", "Method Not Allowed"), Localization.CodeMethodNotAllowed)); return; } @@ -358,7 +359,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s string[] segs = rest.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segs.Length != 2) { - SendJson(stream, 404, Err("路径不存在(需要 /plugins//)")); + SendJson(stream, 404, Err(Localization.T("路径不存在(需要 /plugins//)", "Path not found (expected /plugins//)"), Localization.CodeNotFound)); return; } @@ -368,7 +369,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s // Path traversal / charset guards also inside HandleRouteOnMainThread if (pluginId.Contains("..") || routePath.Contains("..")) { - SendJson(stream, 400, Err("invalid path")); + SendJson(stream, 400, Err(Localization.T("invalid path", "invalid path"), Localization.CodeInvalidArgument)); return; } @@ -380,17 +381,19 @@ private void Route(Stream stream, string remoteIp, string method, string path, s if (routeEx != null) { Log.Warn($"[SLDataAPI] adapted route dispatch failed: {routeEx.Message}"); - SendJson(stream, 504, Err("route timeout or dispatch failed")); + SendJson(stream, 504, Err(Localization.T("route timeout or dispatch failed", "route timeout or dispatch failed"), Localization.CodeTimeout)); return; } if (st == 204) { - SendJson(stream, 200, "{}"); + SendJson(stream, 200, "{\"lang\":\"" + Localization.Language + "\"}"); return; } - SendJson(stream, st, string.IsNullOrEmpty(routeBody) ? Err("empty") : routeBody); + SendJson(stream, st, string.IsNullOrEmpty(routeBody) + ? Err(Localization.T("empty", "empty"), "empty_response") + : EnsureRootLang(routeBody)); return; } @@ -399,7 +402,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s { if (!_config.ControlEnabled) { - SendJson(stream, 404, Err("控制接口未启用")); + SendJson(stream, 404, Err(Localization.T("控制接口未启用", "Control API is disabled"), Localization.CodeNotFound)); return; } @@ -412,24 +415,25 @@ private void Route(Stream stream, string remoteIp, string method, string path, s SendJson(stream, 404, Newtonsoft.Json.JsonConvert.SerializeObject(new ControlResponse { success = false, - message = "控制接口已切换为 WebSocket 模式(control_transport: ws),HTTP /control/* 已禁用", + message = Localization.T("控制接口已切换为 WebSocket 模式(control_transport: ws),HTTP /control/* 已禁用", "Control API switched to WebSocket mode (control_transport: ws); HTTP /control/* is disabled"), data = new { code = "transport_mismatch", use = "ws" }, + code = "transport_mismatch", })); return; } // v2.6.0 推出,代号 PEAK:控制面 API Key(Bearer / X-SLDataAPI-Key);不再接受 X-Control-Token / ?token= string? apiKey = SLDataAPI.Auth.ApiKeyService.ExtractKeyFromHeaders(headers); - if (!SLDataAPI.Auth.ApiKeyService.TryAuthenticate(remoteIp, apiKey, out var principal, out string authErr)) + if (!SLDataAPI.Auth.ApiKeyService.TryAuthenticate(remoteIp, apiKey, out var principal, out string authErr, out string authCode)) { Log.Warn($"[SLDataAPI][Control] 鉴权失败 from {remoteIp}: {authErr}"); - SendJson(stream, 401, Err(authErr)); + SendJson(stream, 401, Err(authErr, authCode)); return; } if (method != "POST") { - SendJson(stream, 405, Err("控制接口仅支持 POST")); + SendJson(stream, 405, Err(Localization.T("控制接口仅支持 POST", "Control API only supports POST"), Localization.CodeMethodNotAllowed)); return; } @@ -437,7 +441,7 @@ private void Route(Stream stream, string remoteIp, string method, string path, s if (principal == null || !principal.Allows(path, wantWrite)) { Log.Warn($"[SLDataAPI][Control] 端点未授权 key={principal?.Id} path={path} write={wantWrite}"); - SendJson(stream, 403, Err("API Key 有效但未授权该端点")); + SendJson(stream, 403, Err(Localization.Forbidden, Localization.CodeForbidden)); return; } @@ -446,12 +450,12 @@ private void Route(Stream stream, string remoteIp, string method, string path, s return; } - SendJson(stream, 404, Err("路径不存在")); + SendJson(stream, 404, Err(Localization.NotFound, Localization.CodeNotFound)); } catch (Exception ex) { Log.Error($"[SLDataAPI] 路由处理异常: {ex}"); - try { SendJson(stream, 500, Err("内部错误")); } catch { } + try { SendJson(stream, 500, Err(Localization.InternalError, Localization.CodeInternalError)); } catch { } } } @@ -465,7 +469,7 @@ private bool TryAuthorizeDataPlane(Stream stream, string remoteIp, string query, if (!ControlAuth.IsAcceptableVerifyToken(_config.VerifyToken)) { SendJson(stream, 503, Err( - "数据接口已关闭:verify_token 未设置为强随机值(禁止出厂默认/空/弱口令)。请修改 config.yml 后重启。")); + Localization.T("数据接口已关闭:verify_token 未设置为强随机值(禁止出厂默认/空/弱口令)。请修改 config.yml 后重启。", "Data API is disabled: verify_token is not a strong random value (factory default, empty, and weak values are rejected). Update config.yml and restart."), Localization.CodeTokenNotConfigured)); return false; } @@ -480,7 +484,7 @@ private bool TryAuthorizeDataPlane(Stream stream, string remoteIp, string query, if (!ControlAuth.TryAuthenticate(remoteIp, reqToken, _config.VerifyToken ?? "", out string err, highPrivilege: false)) { Log.Warn($"[SLDataAPI] {logTag} 鉴权失败 from {remoteIp}: {err} {ControlAuth.DescribeMismatch(reqToken, _config.VerifyToken)}"); - SendJson(stream, 403, Err(err)); + SendJson(stream, 403, Err(err, Localization.ErrorCodeFor(403, err))); return false; } @@ -528,8 +532,31 @@ private static string ReasonPhrase(int code) } } - private static string Err(string message) => - Newtonsoft.Json.JsonConvert.SerializeObject(new ControlResponse { success = false, message = message }); + private static string Err(string message, string? code = null) => + Newtonsoft.Json.JsonConvert.SerializeObject(new ControlResponse + { + success = false, + message = message, + code = code ?? Localization.ErrorCodeFor(400, message), + }); + + /// + /// 适配插件路由可能直接返回 JSON 对象;在其根对象追加 lang(已有 lang / 非对象体原样返回)。 + /// + private static string EnsureRootLang(string json) + { + try + { + var token = Newtonsoft.Json.Linq.JToken.Parse(json); + if (token is Newtonsoft.Json.Linq.JObject obj && obj["lang"] == null) + { + obj["lang"] = Localization.Language; + return obj.ToString(Newtonsoft.Json.Formatting.None); + } + } + catch { /* 非 JSON 文本:原样透传 */ } + return json; + } /// 从 URL 查询串提取首个指定键的值(WsControlService 复用)。 internal static string ExtractQueryValue(string query, string key) diff --git a/Services/Localization.cs b/Services/Localization.cs new file mode 100644 index 0000000..45dc9c8 --- /dev/null +++ b/Services/Localization.cs @@ -0,0 +1,383 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace SLDataAPI.Services; + +/// +/// 接口输出本地化(纯逻辑,无 Unity / LabAPI / Newtonsoft 依赖,可供单元测试直接链接)。 +/// +/// 约定: +/// - zh-CN 是默认语言,所有既有中文字符串必须与引入 i18n 前逐字一致; +/// - en 只影响本插件生成的 HTTP / WebSocket 文本,不翻译游戏内昵称、 +/// 控制台回显、封禁 / 踢出原因等外部内容; +/// - 映射一律按枚举成员名(ToString())查表,不依赖数值; +/// - 稳定 code(role_code / team_code / phase_code / warhead_code / error.code) +/// 与语言无关,调用方直接使用枚举成员名或本类的 Code 方法。 +/// +public static class Localization +{ + public const string ChineseSimplified = "zh-CN"; + public const string English = "en"; + public const string DefaultLanguage = ChineseSimplified; + + private static string _language = DefaultLanguage; + + /// 当前输出语言:zh-CN 或 en。 + public static string Language => _language; + + /// 写入 JSON 根对象 lang 字段的当前语言值。 + public static string Lang => _language; + + public static bool IsEnglish => string.Equals(_language, English, StringComparison.Ordinal); + + /// + /// 设置输出语言。仅接受 zh-CN / en(大小写不敏感、忽略首尾空白)。 + /// 空值按默认 zh-CN 处理;非法值回退 zh-CN 并返回 false(由调用方打警告)。 + /// + public static bool SetLanguage(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + _language = DefaultLanguage; + return true; + } + + string v = value!.Trim(); + if (string.Equals(v, ChineseSimplified, StringComparison.OrdinalIgnoreCase)) + { + _language = ChineseSimplified; + return true; + } + if (string.Equals(v, English, StringComparison.OrdinalIgnoreCase)) + { + _language = English; + return true; + } + + _language = DefaultLanguage; + return false; + } + + /// 把配置值规整为受支持的语言;非法值回退 zh-CN。 + public static string NormalizeLanguage(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return DefaultLanguage; + string v = value!.Trim(); + if (string.Equals(v, ChineseSimplified, StringComparison.OrdinalIgnoreCase)) return ChineseSimplified; + if (string.Equals(v, English, StringComparison.OrdinalIgnoreCase)) return English; + return DefaultLanguage; + } + + // 英文结果 -> 中文结果(仅 en 下写入)。ErrorCodeFor 用它把 en 文本还原成 zh 文本, + // 保证 code 推断与语言无关。错误响应会立即推断,缓存只需覆盖最近产生的一批消息; + // 超过上限直接清空,避免长期运行无界增长。 + private const int TranslationCacheLimit = 2048; + private static readonly ConcurrentDictionary EnglishToChinese = + new(StringComparer.Ordinal); + + /// 按当前语言返回 zh / en 文本;en 下记录映射供错误码推断还原中文。 + public static string T(string zh, string en) + { + if (!IsEnglish) return zh; + if (!string.Equals(zh, en, StringComparison.Ordinal)) + RememberTranslation(en, zh); + return en; + } + + /// 按当前语言返回格式化文本;en 下记录“英文结果 -> 中文结果”映射。 + public static string F(string zh, string en, params object?[] args) + { + if (!IsEnglish) return string.Format(zh, args); + + string enText = string.Format(en, args); + if (!string.Equals(zh, en, StringComparison.Ordinal)) + RememberTranslation(enText, string.Format(zh, args)); + return enText; + } + + private static void RememberTranslation(string english, string chinese) + { + if (EnglishToChinese.Count >= TranslationCacheLimit) + EnglishToChinese.Clear(); + EnglishToChinese[english] = chinese; + } + + /// en 下把已知英文消息还原为对应的中文消息;未知消息原样返回。 + private static string ResolveChineseMessage(string message) + { + if (IsEnglish && EnglishToChinese.TryGetValue(message, out string? zh)) + return zh; + return message; + } + + // ────────────── 回合阶段 ────────────── + + /// 阶段稳定代码:waiting / in_progress / ended。 + public static string PhaseCode(bool roundStarted, bool roundEnded) => + roundStarted ? "in_progress" : roundEnded ? "ended" : "waiting"; + + /// + /// 阶段显示文本。zh-CN 保持既有两态文案(未开始统一显示「等待开始」,即使回合已结束); + /// en 按实际状态给出 Waiting to start / In progress / Ended。 + /// + public static string PhaseText(bool roundStarted, bool roundEnded) => + roundStarted + ? T("进行中", "In progress") + : T("等待开始", roundEnded ? "Ended" : "Waiting to start"); + + // ────────────── 核弹 ────────────── + + /// 核弹稳定代码:inactive / armed / detonating / detonated。 + public static string WarheadCode(bool detonated, bool detonating, bool armed = false) => + detonated ? "detonated" : detonating ? "detonating" : armed ? "armed" : "inactive"; + + /// + /// 核弹显示文本。倒计时秒数沿用既有的整数截断。 + /// zh-CN 保持既有文案:仅拉起拉杆(armed)但尚未开始倒计时时仍显示「未激活」; + /// en 下给出更准确的 "Armed"。 + /// + public static string WarheadText(bool detonated, bool detonating, int countdownSeconds, bool armed = false) + { + if (detonated) return T("已爆炸", "Detonated"); + if (detonating) return F("倒计时:{0}秒", "Detonating: {0}s", countdownSeconds); + if (armed) return T("未激活", "Armed"); + return T("未激活", "Inactive"); + } + + // ────────────── 阵营(数据接口 /get_sl_data) ────────────── + + /// 阵营稳定代码:Team 枚举成员名(如 ClassD / ChaosInsurgency / FoundationForces / SCPs / Dead / OtherAlive)。 + public static string TeamCode(string teamName) => teamName ?? ""; + + private static readonly Dictionary TeamNames = + new(StringComparer.Ordinal) + { + ["SCPs"] = ("SCP", "SCP"), + ["FoundationForces"] = ("基金会", "Foundation"), + ["ClassD"] = ("D级", "Class-D"), + ["ChaosInsurgency"] = ("混沌", "Chaos Insurgency"), + ["Dead"] = ("观察者", "Spectators"), + ["OtherAlive"] = ("其他", "Other"), + }; + + /// 阵营显示文本;未知成员名沿用既有「未知」兜底。 + public static string TeamText(string teamName) + { + if (teamName != null && TeamNames.TryGetValue(teamName, out var v)) + return T(v.Zh, v.En); + return T("未知", "Unknown"); + } + + // ────────────── 角色(数据接口 /get_sl_data) ────────────── + + /// 角色稳定代码:RoleTypeId 枚举成员名(如 Spectator / Tutorial / NtfCaptain)。 + public static string RoleCode(string roleName) => roleName ?? ""; + + // zh 值必须与改造前 DataCollector.GetRoleCN 逐字一致。 + // en 额外覆盖若干原表未列出的成员(原表这些成员的中文兜底为「未知(数字)」,保持不变)。 + private static readonly Dictionary DataRoleNames = + new(StringComparer.Ordinal) + { + ["ClassD"] = ("D级人员", "Class-D Personnel"), + ["Scientist"] = ("科学家", "Scientist"), + ["FacilityGuard"] = ("保安", "Facility Guard"), + ["NtfPrivate"] = ("九尾狐-士兵", "NTF Private"), + ["NtfSergeant"] = ("九尾狐-中士", "NTF Sergeant"), + ["NtfCaptain"] = ("九尾狐-指挥官", "NTF Captain"), + ["ChaosConscript"] = ("混沌-征召兵", "Chaos Insurgency Conscript"), + ["ChaosRifleman"] = ("混沌-步枪手", "Chaos Insurgency Rifleman"), + ["ChaosMarauder"] = ("混沌-掠夺者", "Chaos Insurgency Marauder"), + ["ChaosRepressor"] = ("混沌-镇压者", "Chaos Insurgency Repressor"), + ["Scp173"] = ("SCP-173", "SCP-173"), + ["Scp049"] = ("SCP-049", "SCP-049"), + ["Scp096"] = ("SCP-096", "SCP-096"), + ["Scp106"] = ("SCP-106", "SCP-106"), + ["Scp939"] = ("SCP-939", "SCP-939"), + ["Scp079"] = ("SCP-079", "SCP-079"), + ["Scp3114"] = ("SCP-3114", "SCP-3114"), + ["Scp0492"] = ("SCP-049-2", "SCP-049-2"), + ["Spectator"] = ("观察者", "Spectator"), + ["Tutorial"] = ("教程", "Tutorial"), + ["None"] = ("未分配", "Unassigned"), + }; + + // 原中文表未覆盖、但 en 下可以给出明确英文名的成员;zh 仍走「未知(数字)」兜底。 + private static readonly Dictionary DataRoleEnglishOnly = + new(StringComparer.Ordinal) + { + ["NtfSpecialist"] = "NTF Specialist", + ["Overwatch"] = "Overwatch", + ["Filmmaker"] = "Filmmaker", + }; + + /// + /// 数据接口角色显示文本。未知成员沿用改造前的 未知(数值) 中文兜底; + /// en 下优先查英文补充表,仍未知则返回 Unknown。 + /// + public static string DataRoleText(string roleName, int numericValue) + { + if (roleName != null && DataRoleNames.TryGetValue(roleName, out var v)) + return T(v.Zh, v.En); + if (IsEnglish && roleName != null && DataRoleEnglishOnly.TryGetValue(roleName, out var en)) + return en; + return IsEnglish ? "Unknown" : $"未知({numericValue})"; + } + + // ────────────── 角色(语音 /status 与 speaker 帧) ────────────── + + // zh 值必须与改造前 VoiceService.GetRoleCN 逐字一致。 + private static readonly Dictionary VoiceRoleNames = + new(StringComparer.Ordinal) + { + ["ClassD"] = ("D级人员", "Class-D Personnel"), + ["Scientist"] = ("科学家", "Scientist"), + ["FacilityGuard"] = ("设施警卫", "Facility Guard"), + ["NtfSpecialist"] = ("九尾狐-中士", "NTF Specialist"), + ["NtfSergeant"] = ("九尾狐-军士", "NTF Sergeant"), + ["NtfCaptain"] = ("九尾狐-队长", "NTF Captain"), + ["NtfPrivate"] = ("九尾狐-列兵", "NTF Private"), + ["ChaosConscript"] = ("混沌分裂者-征召兵", "Chaos Insurgency Conscript"), + ["ChaosRifleman"] = ("混沌分裂者-步枪手", "Chaos Insurgency Rifleman"), + ["ChaosMarauder"] = ("混沌分裂者-掠夺者", "Chaos Insurgency Marauder"), + ["ChaosRepressor"] = ("混沌分裂者-镇压者", "Chaos Insurgency Repressor"), + ["Scp049"] = ("SCP-049", "SCP-049"), + ["Scp0492"] = ("SCP-049-2", "SCP-049-2"), + ["Scp079"] = ("SCP-079", "SCP-079"), + ["Scp096"] = ("SCP-096", "SCP-096"), + ["Scp106"] = ("SCP-106", "SCP-106"), + ["Scp173"] = ("SCP-173", "SCP-173"), + ["Scp939"] = ("SCP-939", "SCP-939"), + ["Scp3114"] = ("SCP-3114", "SCP-3114"), + ["Tutorial"] = ("教程角色", "Tutorial"), + ["Spectator"] = ("旁观者", "Spectator"), + ["Overwatch"] = ("观察者", "Overwatch"), + ["Filmmaker"] = ("摄影者", "Filmmaker"), + }; + + /// 语音角色显示文本;未知成员沿用改造前「枚举成员名」兜底。 + public static string VoiceRoleText(string roleName) + { + if (roleName != null && VoiceRoleNames.TryGetValue(roleName, out var v)) + return T(v.Zh, v.En); + return roleName ?? ""; + } + + // ────────────── 稳定错误码 ────────────── + + public const string CodeTimeout = "timeout"; + public const string CodeSymlinkForbidden = "symlink_forbidden"; + public const string CodeUnauthorized = "unauthorized"; + public const string CodeForbidden = "forbidden"; + public const string CodeNotFound = "not_found"; + public const string CodeInvalidArgument = "invalid_argument"; + public const string CodeBadRequest = "bad_request"; + public const string CodeMethodNotAllowed = "method_not_allowed"; + public const string CodePayloadTooLarge = "payload_too_large"; + public const string CodeRequestHeaderTooLarge = "request_header_too_large"; + public const string CodeConflict = "conflict"; + public const string CodeInternalError = "internal_error"; + public const string CodeNotImplemented = "not_implemented"; + public const string CodeServiceUnavailable = "service_unavailable"; + public const string CodeTooManyRequests = "too_many_requests"; + public const string CodeOperationFailed = "operation_failed"; + public const string CodeAuthLocked = "auth_locked"; + public const string CodeTokenNotConfigured = "token_not_configured"; + + /// + /// 当调用点没有显式 code 时,按状态码 + 文本推断一个稳定的 snake_case 错误码。 + /// en 下先通过 T/F 记录的“英文结果 -> 中文结果”映射还原成中文,再复用同一套判断, + /// 因此 code 与当前语言无关;zh-CN 下直接使用原文本,推断结果与改造前完全一致。 + /// + public static string ErrorCodeFor(int status, string? message) + { + string m = ResolveChineseMessage(message ?? ""); + + if (Contains(m, "锁定", "locked")) return CodeAuthLocked; + if (Contains(m, "超时", "timed out", "timeout")) return CodeTimeout; + if (Contains(m, "符号链接", "symbolic link", "junction")) return CodeSymlinkForbidden; + // 必须早于 forbidden 的 "not allowed":Method Not Allowed 不能被误判为权限错误。 + if (Contains(m, "method not allowed", "仅支持 POST")) return CodeMethodNotAllowed; + if (Contains(m, "未授权", "not authorized", "unauthorized", "not allowed")) return CodeForbidden; + if (Contains(m, "找不到", "未找到", "不存在", "not found", "not registered")) return CodeNotFound; + if (Contains(m, "未配置访问令牌", "token 错误或缺失", "缺少 API Key", "API Key 无效", + "missing api key", "invalid api key", "token is missing", "token is invalid")) + return CodeUnauthorized; + if (Contains(m, "请求头过大", "request header")) return CodeRequestHeaderTooLarge; + if (Contains(m, "payload too large", "内容过大", "文件过大", "too large")) + return CodePayloadTooLarge; + if (Contains(m, "method not allowed")) return CodeMethodNotAllowed; + if (Contains(m, "bad request")) return CodeBadRequest; + if (Contains(m, "内部错误", "internal error", "handler error")) return CodeInternalError; + if (Contains(m, "尚未实现", "not implemented")) return CodeNotImplemented; + if (Contains(m, "服务不可用", "service unavailable", "未启用", "disabled")) return CodeServiceUnavailable; + if (Contains(m, "缺少", "missing", "无效", "invalid", "非法", "不支持", "not supported", + "超出", "exceeds", "必须", "must be", "需要", "required")) + return CodeInvalidArgument; + if (Contains(m, "失败", "failed")) return CodeOperationFailed; + + switch (status) + { + case 400: return CodeInvalidArgument; + case 401: return CodeUnauthorized; + case 403: return CodeForbidden; + case 404: return CodeNotFound; + case 405: return CodeMethodNotAllowed; + case 408: return CodeTimeout; + case 409: return CodeConflict; + case 413: return CodePayloadTooLarge; + case 429: return CodeTooManyRequests; + case 431: return CodeRequestHeaderTooLarge; + case 500: return CodeInternalError; + case 501: return CodeNotImplemented; + case 503: return CodeServiceUnavailable; + case 504: return CodeTimeout; + default: return CodeOperationFailed; + } + } + + private static bool Contains(string text, params string[] needles) + { + foreach (string n in needles) + { + if (text.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) + return true; + } + return false; + } + + // ────────────── 关键固定文案(同时供测试锁定) ────────────── + + public static string TimeoutRequestHeaders => + T("请求超时:头部长时间未收完(Slowloris 防护)", + "Request timed out: headers were not received in time (Slowloris protection)"); + + public static string TimeoutRequestBody => + T("请求超时:请求体长时间未收完(Slowloris 防护)", + "Request timed out: body was not received in time (Slowloris protection)"); + + public static string TimeoutMainThread => + T("主线程执行超时(服务器可能卡顿、正在切图或已停止响应)" + + "——若主线程在超时后恢复且操作已经开始,仍可能执行一次,请勿盲目重试非幂等操作", + "Main-thread execution timed out (the server may be lagging, loading a map, or unresponsive)" + + " — if the main thread recovers after the timeout and the operation has already started, it may still run once; do not blindly retry non-idempotent operations"); + + public static string SymlinkForbidden => + T("路径经过符号链接或目录联接(junction),已拒绝(防止越出 FileRoot)", + "Path traverses a symbolic link or directory junction; rejected to prevent escaping FileRoot"); + + public static string FileRootNotConfigured => + T("文件端点未启用(服务器未配置 FileRoot)", + "File endpoints are disabled (FileRoot is not configured on the server)"); + + public static string InternalError => T("内部错误", "Internal error"); + + public static string NotFound => T("路径不存在", "Path not found"); + + public static string Forbidden => T("API Key 有效但未授权该端点", + "API key is valid but not authorized for this endpoint"); +} diff --git a/Services/MainThreadExecutor.cs b/Services/MainThreadExecutor.cs index 35a1399..a24802c 100644 --- a/Services/MainThreadExecutor.cs +++ b/Services/MainThreadExecutor.cs @@ -58,9 +58,7 @@ public static bool RunOnMainThread(Action action, out Exception error, int timeo if (!completed) { cancelled = true; // N-02:标记迟到 action 跳过,避免"报超时但实际执行"导致的重试双重执行 - error = new TimeoutException( - "主线程执行超时(服务器可能卡顿、正在切图或已停止响应)" + - "——若主线程在超时后恢复且操作已经开始,仍可能执行一次,请勿盲目重试非幂等操作"); + error = new TimeoutException(Localization.TimeoutMainThread); return false; } @@ -106,9 +104,7 @@ public static T RunOnMainThread(Func func, out Exception error, int timeou if (!completed) { cancelled = true; // N-02 - error = new TimeoutException( - "主线程执行超时(服务器可能卡顿、正在切图或已停止响应)" + - "——若主线程在超时后恢复且操作已经开始,仍可能执行一次,请勿盲目重试非幂等操作"); + error = new TimeoutException(Localization.TimeoutMainThread); return default!; } diff --git a/Services/ServerLogService.cs b/Services/ServerLogService.cs index 729985e..2b0c08e 100644 --- a/Services/ServerLogService.cs +++ b/Services/ServerLogService.cs @@ -110,8 +110,9 @@ public static object Tail(int lines, string filter, string? path = null) if (string.IsNullOrWhiteSpace(path)) { file = FindLatestLogFile() - ?? throw new InvalidOperationException( - "找不到服务器日志文件(已探测 %AppData%/SCP Secret Laboratory/ServerLogs 与 SCPSL_Data/Logs)"); + ?? throw new InvalidOperationException(Localization.T( + "找不到服务器日志文件(已探测 %AppData%/SCP Secret Laboratory/ServerLogs 与 SCPSL_Data/Logs)", + "No server log file found (checked %AppData%/SCP Secret Laboratory/ServerLogs and SCPSL_Data/Logs)")); } else { @@ -120,19 +121,21 @@ public static object Tail(int lines, string filter, string? path = null) { string? resolved = ResolveRelativeLogPath(path); if (resolved == null) - throw new ArgumentException("日志路径不在服务器日志目录内,拒绝读取"); + throw new ArgumentException(Localization.T("日志路径不在服务器日志目录内,拒绝读取", + "Log path is outside the server log directory; read refused")); path = resolved; } // 安全校验:规范化后必须位于候选日志目录内 + 扩展名白名单(.log/.txt) string full; try { full = Path.GetFullPath(path); } - catch { throw new ArgumentException("日志路径非法"); } + catch { throw new ArgumentException(Localization.T("日志路径非法", "Invalid log path")); } string ext = Path.GetExtension(full); if (!string.Equals(ext, ".log", StringComparison.OrdinalIgnoreCase) && !string.Equals(ext, ".txt", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException($"日志接口只允许读取 .log/.txt 文件(收到 {ext})"); + throw new ArgumentException(Localization.F("日志接口只允许读取 .log/.txt 文件(收到 {0})", + "The log endpoint only reads .log/.txt files (got {0})", ext)); bool inside = GetLogDirs().Any(dir => { @@ -142,10 +145,11 @@ public static object Tail(int lines, string filter, string? path = null) return full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); }); if (!inside) - throw new ArgumentException("日志路径不在服务器日志目录内,拒绝读取"); + throw new ArgumentException(Localization.T("日志路径不在服务器日志目录内,拒绝读取", + "Log path is outside the server log directory; read refused")); if (!File.Exists(full)) - throw new ArgumentException($"日志文件不存在: {path}"); + throw new ArgumentException(Localization.F("日志文件不存在: {0}", "Log file does not exist: {0}", path)); file = full; } diff --git a/Services/TlsPolicy.cs b/Services/TlsPolicy.cs index 0efeee9..93c2ea4 100644 --- a/Services/TlsPolicy.cs +++ b/Services/TlsPolicy.cs @@ -35,8 +35,9 @@ public static class TlsPolicy /// 给上游客户端的机器可读码(426 响应 data.code)。 public const string TlsRequiredCode = "tls_required"; - public const string TlsRequiredMessage = - "该端口要求 TLS(tls_mode: required):请改用 https:// / wss:// 并校验证书指纹"; + public static string TlsRequiredMessage => + Localization.T("该端口要求 TLS(tls_mode: required):请改用 https:// / wss:// 并校验证书指纹", + "This port requires TLS (tls_mode: required): use https:// / wss:// and verify the certificate fingerprint"); /// /// 解析 tls_mode:off / optional / required(大小写、首尾空白不敏感)。 @@ -105,7 +106,8 @@ public static string FormatFingerprint(byte[] hash) public static string BuildTlsRequiredJson(string? message = null) { return "{\"success\":false,\"message\":\"" + JsonEscape(message ?? TlsRequiredMessage) + - "\",\"data\":{\"code\":\"" + TlsRequiredCode + "\"}}"; + "\",\"data\":{\"code\":\"" + TlsRequiredCode + "\"}" + + ",\"code\":\"" + TlsRequiredCode + "\",\"lang\":\"" + JsonEscape(Localization.Language) + "\"}"; } private static string JsonEscape(string s) diff --git a/Voice/VoiceService.cs b/Voice/VoiceService.cs index 8b5bb72..38b23a8 100644 --- a/Voice/VoiceService.cs +++ b/Voice/VoiceService.cs @@ -13,7 +13,6 @@ using System.Text; using System.Threading; using MEC; -using PlayerRoles; using SLDataAPI.Control; using SLDataAPI.Services; using VoiceChat; @@ -182,9 +181,14 @@ public static void HandleIncoming(Player? player, VoiceMessage msg) float now = UnityEngine.Time.time; - // 说话状态(/status 用):角色实时读 - string roleCn = "未知"; - try { roleCn = GetRoleCN(player.Role); } + // 说话状态(/status 用):角色实时读。role_code 固定为 RoleTypeId 成员名,不随 language 变化。 + string roleCn = Localization.T("未知", "Unknown"); + string roleCode = ""; + try + { + roleCode = player.Role.ToString(); + roleCn = Localization.VoiceRoleText(roleCode); + } catch { /* 忽略 */ } // 录音取证(可选):复用解码结果,主线程入队、后台线程写盘 @@ -197,6 +201,7 @@ public static void HandleIncoming(Player? player, VoiceMessage msg) Nickname = player.Nickname ?? "?", UserId = player.UserId ?? "?", Role = roleCn, + RoleCode = roleCode, Channel = (byte)msg.Channel, LastSeen = now }; @@ -233,6 +238,7 @@ public static void HandleIncoming(Player? player, VoiceMessage msg) Nickname = player.Nickname ?? "?", UserId = player.UserId ?? "?", Role = roleCn, + RoleCode = roleCode, NewBurst = newBurst, Samples = new float[samples] }; @@ -379,9 +385,10 @@ public static string BuildStatusJson() .Append("\",\"userid\":\"").Append(JsonEscape(kv.Value.UserId)) .Append("\",\"role\":\"").Append(JsonEscape(kv.Value.Role)) .Append("\",\"channel\":").Append(kv.Value.Channel) + .Append(",\"role_code\":\"").Append(JsonEscape(kv.Value.RoleCode)) .Append('}'); } - sb.Append("]}"); + sb.Append("],\"lang\":\"").Append(JsonEscape(Localization.Language)).Append("\"}"); return sb.ToString(); } @@ -414,6 +421,7 @@ internal class PcmPacket public string Nickname = ""; public string UserId = ""; public string Role = ""; + public string RoleCode = ""; public bool NewBurst; public float[] Samples = Array.Empty(); } @@ -424,6 +432,7 @@ private class VoiceActivity public string Nickname = ""; public string UserId = ""; public string Role = ""; + public string RoleCode = ""; public byte Channel; public float LastSeen; } @@ -710,10 +719,10 @@ private void HandleHttp(string header) string clientIp = ""; try { clientIp = ((IPEndPoint)_socket.RemoteEndPoint).Address.ToString(); } catch { /* 忽略 */ } - if (!ApiKeyService.TryAuthenticate(clientIp, key, out var principal, out string authErr) || principal == null) + if (!ApiKeyService.TryAuthenticate(clientIp, key, out var principal, out string authErr, out string authCode) || principal == null) { Log.Warn($"[SLDataAPI][Voice] 鉴权失败 from {clientIp}: {authErr}"); - SendHttp("401 Unauthorized", "application/json", "{\"ok\":false,\"error\":\"" + JsonEscape(authErr) + "\"}"); + SendHttp("401 Unauthorized", "application/json", VoiceErrorJson(authErr, authCode)); _state = -1; return; } @@ -727,14 +736,17 @@ private void HandleHttp(string header) { if (!principal.Allows("voice:/ws", wantWrite: false)) { - SendHttp("403 Forbidden", "application/json", "{\"ok\":false,\"error\":\"API Key 未授权 voice:/ws\"}"); + SendHttp("403 Forbidden", "application/json", + VoiceErrorJson(Localization.T("API Key 未授权 voice:/ws", "API key is not authorized for voice:/ws"), + Localization.CodeForbidden)); _state = -1; return; } if (CountAuthenticated() >= MaxClients) { SendHttp("503 Service Unavailable", "application/json", - "{\"ok\":false,\"error\":\"语音已鉴权监听数已满\"}"); + VoiceErrorJson(Localization.T("语音已鉴权监听数已满", "Voice listener limit reached"), + Localization.CodeServiceUnavailable)); _state = -1; return; } @@ -745,7 +757,8 @@ private void HandleHttp(string header) ? "null" : "\"" + JsonEscape(TlsCertificateService.Fingerprint) + "\""; SendWsFrame(0x1, Encoding.UTF8.GetBytes( "{\"type\":\"hello\",\"sampleRate\":48000,\"channels\":1,\"format\":\"float32\"," + - "\"tls\":" + (IsTls ? "true" : "false") + ",\"cert_fingerprint\":" + fp + "}")); + "\"tls\":" + (IsTls ? "true" : "false") + ",\"cert_fingerprint\":" + fp + + ",\"lang\":\"" + JsonEscape(Localization.Language) + "\"}")); } else _state = -1; return; @@ -755,7 +768,9 @@ private void HandleHttp(string header) { if (!principal.Allows("voice:/status", wantWrite: false)) { - SendHttp("403 Forbidden", "application/json", "{\"ok\":false,\"error\":\"API Key 未授权 voice:/status\"}"); + SendHttp("403 Forbidden", "application/json", + VoiceErrorJson(Localization.T("API Key 未授权 voice:/status", "API key is not authorized for voice:/status"), + Localization.CodeForbidden)); _state = -1; return; } @@ -764,7 +779,8 @@ private void HandleHttp(string header) return; } - SendHttp("404 Not Found", "application/json", "{\"ok\":false,\"error\":\"not found\"}"); + SendHttp("404 Not Found", "application/json", + VoiceErrorJson(Localization.T("not found", "not found"), Localization.CodeNotFound)); _state = -1; } @@ -871,7 +887,7 @@ public void SendVoice(PcmPacket pkt) string? lastKey; if (pkt.NewBurst || !_speakerKeys.TryGetValue(pkt.PlayerId, out lastKey) || lastKey != key) { - string json = $"{{\"type\":\"speaker\",\"nickname\":\"{JsonEscape(pkt.Nickname)}\",\"userid\":\"{JsonEscape(pkt.UserId)}\",\"playerid\":{pkt.PlayerId},\"role\":\"{JsonEscape(pkt.Role)}\",\"channel\":{pkt.Channel}}}"; + string json = $"{{\"type\":\"speaker\",\"nickname\":\"{JsonEscape(pkt.Nickname)}\",\"userid\":\"{JsonEscape(pkt.UserId)}\",\"playerid\":{pkt.PlayerId},\"role\":\"{JsonEscape(pkt.Role)}\",\"channel\":{pkt.Channel},\"role_code\":\"{JsonEscape(pkt.RoleCode)}\",\"lang\":\"{JsonEscape(Localization.Language)}\"}}"; SendWsFrame(0x1, Encoding.UTF8.GetBytes(json)); _speakerKeys[pkt.PlayerId] = key; } @@ -1034,6 +1050,10 @@ private static ulong FnvHash(byte[] data, int len) return null; } + private static string VoiceErrorJson(string message, string code) => + "{\"ok\":false,\"error\":\"" + JsonEscape(message) + "\",\"code\":\"" + JsonEscape(code) + + "\",\"lang\":\"" + JsonEscape(Localization.Language) + "\"}"; + private static string JsonEscape(string s) { if (string.IsNullOrEmpty(s)) return ""; @@ -1055,35 +1075,4 @@ private static string JsonEscape(string s) } return sb.ToString(); } - - private static string GetRoleCN(RoleTypeId type) - { - switch (type) - { - case RoleTypeId.ClassD: return "D级人员"; - case RoleTypeId.Scientist: return "科学家"; - case RoleTypeId.FacilityGuard: return "设施警卫"; - case RoleTypeId.NtfSpecialist: return "九尾狐-中士"; - case RoleTypeId.NtfSergeant: return "九尾狐-军士"; - case RoleTypeId.NtfCaptain: return "九尾狐-队长"; - case RoleTypeId.NtfPrivate: return "九尾狐-列兵"; - case RoleTypeId.ChaosConscript: return "混沌分裂者-征召兵"; - case RoleTypeId.ChaosRifleman: return "混沌分裂者-步枪手"; - case RoleTypeId.ChaosMarauder: return "混沌分裂者-掠夺者"; - case RoleTypeId.ChaosRepressor: return "混沌分裂者-镇压者"; - case RoleTypeId.Scp049: return "SCP-049"; - case RoleTypeId.Scp0492: return "SCP-049-2"; - case RoleTypeId.Scp079: return "SCP-079"; - case RoleTypeId.Scp096: return "SCP-096"; - case RoleTypeId.Scp106: return "SCP-106"; - case RoleTypeId.Scp173: return "SCP-173"; - case RoleTypeId.Scp939: return "SCP-939"; - case RoleTypeId.Scp3114: return "SCP-3114"; - case RoleTypeId.Tutorial: return "教程角色"; - case RoleTypeId.Spectator: return "旁观者"; - case RoleTypeId.Overwatch: return "观察者"; - case RoleTypeId.Filmmaker: return "摄影者"; - default: return type.ToString(); - } - } } diff --git a/tests/SLDataAPI.Auth.Tests/SLDataAPI.Auth.Tests.csproj b/tests/SLDataAPI.Auth.Tests/SLDataAPI.Auth.Tests.csproj index e70fa8d..c934487 100644 --- a/tests/SLDataAPI.Auth.Tests/SLDataAPI.Auth.Tests.csproj +++ b/tests/SLDataAPI.Auth.Tests/SLDataAPI.Auth.Tests.csproj @@ -27,5 +27,6 @@ + \ No newline at end of file diff --git a/tests/SLDataAPI.Auth.Tests/TlsPolicyTests.cs b/tests/SLDataAPI.Auth.Tests/TlsPolicyTests.cs index b3b1a0c..99fabb6 100644 --- a/tests/SLDataAPI.Auth.Tests/TlsPolicyTests.cs +++ b/tests/SLDataAPI.Auth.Tests/TlsPolicyTests.cs @@ -90,7 +90,9 @@ public void TlsRequiredEnvelope() Assert.False(root.GetProperty("success").GetBoolean()); Assert.False(string.IsNullOrWhiteSpace(root.GetProperty("message").GetString())); Assert.Equal("tls_required", root.GetProperty("data").GetProperty("code").GetString()); - Assert.Equal(3, root.EnumerateObject().Count()); + Assert.Equal("tls_required", root.GetProperty("code").GetString()); + Assert.Contains(root.GetProperty("lang").GetString(), new[] { "zh-CN", "en" }); + Assert.Equal(5, root.EnumerateObject().Count()); Assert.Single(root.GetProperty("data").EnumerateObject()); } diff --git a/tests/SLDataAPI.Features.Tests/AssemblyInfo.cs b/tests/SLDataAPI.Features.Tests/AssemblyInfo.cs new file mode 100644 index 0000000..aeada9f --- /dev/null +++ b/tests/SLDataAPI.Features.Tests/AssemblyInfo.cs @@ -0,0 +1,8 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using Xunit; + +// 本地化测试会切换静态当前语言,禁用并行执行避免与其他测试互相干扰。 +[assembly: CollectionBehavior(DisableTestParallelization = true)] diff --git a/tests/SLDataAPI.Features.Tests/ErrorCodeEnvelopeTests.cs b/tests/SLDataAPI.Features.Tests/ErrorCodeEnvelopeTests.cs new file mode 100644 index 0000000..6ac7ff2 --- /dev/null +++ b/tests/SLDataAPI.Features.Tests/ErrorCodeEnvelopeTests.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using SLDataAPI.Services; +using Xunit; + +namespace SLDataAPI.Features.Tests; + +/// +/// 错误信封 code 追加的字节级回归:只追加,不重新序列化既有字段。 +/// 覆盖浮点数、\uXXXX、转义引号/反斜杠、Unicode、null 与字段顺序。 +/// +public class ErrorCodeEnvelopeTests : System.IDisposable +{ + public ErrorCodeEnvelopeTests() => Localization.SetLanguage("zh-CN"); + + public void Dispose() => Localization.SetLanguage("zh-CN"); + + [Fact] + public void AppendsCodeWithoutReformattingExistingJson() + { + const string original = + "{\"success\":false,\"message\":\"缺少 action 字段\",\"data\":{\"ratio\":1.0,\"escaped\":\"a\\u0001\\\"b\\\\c\",\"zh\":\"中文\",\"nullv\":null}}"; + const string expected = + "{\"success\":false,\"message\":\"缺少 action 字段\",\"data\":{\"ratio\":1.0,\"escaped\":\"a\\u0001\\\"b\\\\c\",\"zh\":\"中文\",\"nullv\":null},\"code\":\"invalid_argument\"}"; + + Assert.Equal(expected, ErrorCodeEnvelope.EnsureErrorCode(400, original)); + } + + [Fact] + public void ExistingDataCodeTakesPrecedence() + { + const string original = + "{\"success\":false,\"message\":\"节日功能未开启\",\"data\":{\"code\":\"holiday_inactive\",\"feature\":\"candy:Evil\"}}"; + const string expected = + "{\"success\":false,\"message\":\"节日功能未开启\",\"data\":{\"code\":\"holiday_inactive\",\"feature\":\"candy:Evil\"},\"code\":\"holiday_inactive\"}"; + + Assert.Equal(expected, ErrorCodeEnvelope.EnsureErrorCode(409, original)); + } + + [Fact] + public void SuccessAndExistingCodeAndNonErrorStatus_AreUnchanged() + { + const string success = "{\"success\":true,\"message\":\"ok\",\"data\":null}"; + Assert.Equal(success, ErrorCodeEnvelope.EnsureErrorCode(400, success)); + + const string already = "{\"success\":false,\"message\":\"x\",\"data\":null,\"code\":\"forbidden\"}"; + Assert.Equal(already, ErrorCodeEnvelope.EnsureErrorCode(400, already)); + + const string okStatus = "{\"success\":false,\"message\":\"x\",\"data\":null}"; + Assert.Equal(okStatus, ErrorCodeEnvelope.EnsureErrorCode(200, okStatus)); + } + + [Fact] + public void EnglishMessage_UsesRecordedChineseMapping() + { + Localization.SetLanguage("en"); + string message = Localization.T("缺少 action 字段", "Missing action field"); + string original = "{\"success\":false,\"message\":\"" + message + "\",\"data\":null}"; + + string result = ErrorCodeEnvelope.EnsureErrorCode(400, original); + + Assert.Equal("{\"success\":false,\"message\":\"" + message + "\",\"data\":null,\"code\":\"invalid_argument\"}", result); + } + + [Fact] + public void InvalidJson_IsReturnedUnchanged() + { + const string invalid = "not-json"; + Assert.Equal(invalid, ErrorCodeEnvelope.EnsureErrorCode(400, invalid)); + } +} diff --git a/tests/SLDataAPI.Features.Tests/LocalizationCodeIndependenceTests.cs b/tests/SLDataAPI.Features.Tests/LocalizationCodeIndependenceTests.cs new file mode 100644 index 0000000..208d7dc --- /dev/null +++ b/tests/SLDataAPI.Features.Tests/LocalizationCodeIndependenceTests.cs @@ -0,0 +1,541 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using SLDataAPI.Services; +using Xunit; + +namespace SLDataAPI.Features.Tests; + +/// +/// error.code 与语言无关的回归测试: +/// - 逐项覆盖审查列出的中英文消息对; +/// - 扫描仓库内所有 Localization.T/F 的 ("zh","en") 字面量对,逐对比较两种语言下的推断结果。 +/// 测试通过 Localization.T/F 真正生成 en 消息,模拟生产路径(会写入英文→中文缓存)。 +/// +public class LocalizationCodeIndependenceTests : IDisposable +{ + public LocalizationCodeIndependenceTests() => Localization.SetLanguage("zh-CN"); + + public void Dispose() => Localization.SetLanguage("zh-CN"); + + [Theory] + [InlineData(403, "服务端未配置访问令牌", "Access token is not configured on the server")] + [InlineData(403, "token 错误或缺失", "Token is incorrect or missing")] + [InlineData(400, "插件不存在", "Plugin does not exist")] + [InlineData(400, "会话不存在或已过期", "Session does not exist or has expired")] + [InlineData(400, "路径越界:不允许访问 FileRoot 之外的目录", "Path escapes the sandbox: access outside FileRoot is not allowed")] + [InlineData(400, "系统目录(Windows)受保护,禁止访问", "The Windows system directory is protected; access is not allowed")] + [InlineData(400, "系统目录(Windows)受保护,禁止读取", "The Windows system directory is protected; reading is not allowed")] + [InlineData(400, "系统目录(Windows)受保护,禁止修改", "The Windows system directory is protected; modification is not allowed")] + [InlineData(400, "消息过大", "Message too large")] + [InlineData(400, "内测端点未开启(config: beta_file_root_ws: false)", "Beta endpoint is disabled (config: beta_file_root_ws: false)")] + [InlineData(404, "控制接口已切换为 WebSocket 模式(control_transport: ws),HTTP /control/* 已禁用", "Control API switched to WebSocket mode (control_transport: ws); HTTP /control/* is disabled")] + [InlineData(400, "数据接口已关闭:verify_token 未设置为强随机值(禁止出厂默认/空/弱口令)。请修改 config.yml 后重启。", "Data API is disabled: verify_token is not a strong random value (factory default, empty, and weak values are rejected). Update config.yml and restart.")] + [InlineData(400, "当前游戏版本不提供假人 API(DummyUtils 不存在)", "This game version does not provide the dummy API (DummyUtils is missing)")] + [InlineData(400, "控制接口仅支持 POST", "Control API only supports POST")] + [InlineData(400, "command=send 需要 level 字段(非负整数目标楼层)", "command=send requires the level field (a non-negative target floor)")] + [InlineData(400, "新上传必须从 offset 0 开始(或携带 upload_id 续传)", "A new upload must start at offset 0 (or include upload_id to resume)")] + [InlineData(400, "不支持扩展位", "Unsupported reserved bits")] + public void ListedMessagePairs_HaveSameCodeInBothLanguages(int status, string zh, string en) + { + AssertSameCode(status, zh, en); + } + + [Theory] + [InlineData(400, "目录不存在: {0}", "Directory does not exist: {0}", "logs")] + [InlineData(400, "文件不存在: {0}", "File does not exist: {0}", "config.yml")] + [InlineData(400, "日志文件不存在: {0}", "Log file does not exist: {0}", "server.log")] + [InlineData(400, "受保护目录(SLDataAPI 配置),禁止{0}", "Protected directory (SLDataAPI configuration); {0} is not allowed", "access")] + [InlineData(400, "effect_intensity 超出范围: {0}(0-255,0=关闭)", "effect_intensity is out of range: {0} (0-255; 0 disables the effect)", 300)] + [InlineData(403, "该来源已因多次鉴权失败被临时锁定,请 {0} 秒后重试", "This source is temporarily locked after repeated authentication failures; retry in {0} seconds", 300)] + public void ListedFormattedPairs_HaveSameCodeInBothLanguages(int status, string zh, string en, object arg) + { + AssertSameCode(status, zh, en, arg); + } + + [Fact] + public void SourceLocalizationPairs_HaveSameCodeInBothLanguages() + { + var pairs = LoadSourcePairs(); + Assert.True(pairs.Count >= 200, $"只解析到 {pairs.Count} 对 Localization.T/F 文本,扫描可能失效"); + + var failures = new List(); + foreach (Pair pair in pairs) + { + try + { + object?[] args = SampleArgs(pair); + AssertSameCode(400, pair.Zh, pair.En, args, failures); + } + catch (Exception ex) + { + failures.Add($"{pair.Zh} / {pair.En}: {ex.GetType().Name}: {ex.Message}"); + } + } + + Localization.SetLanguage("zh-CN"); + Assert.True(failures.Count == 0, + $"以下文本对在 zh-CN / en 下推断出的 error.code 不同(共 {failures.Count} 对):\n" + + string.Join("\n", failures.Take(30))); + } + + [Fact] + public void DuplicateEnglishTranslations_DoNotConflict() + { + var pairs = LoadSourcePairs(); + Localization.SetLanguage("zh-CN"); + + var conflicts = new List(); + foreach (var group in pairs.GroupBy(p => Render(p, english: true))) + { + string[] codes = group + .Select(p => Localization.ErrorCodeFor(400, Render(p, english: false))) + .Distinct(StringComparer.Ordinal) + .ToArray(); + if (codes.Length > 1) + { + conflicts.Add($"{group.Key}: {string.Join(", ", codes)} | " + + string.Join(" | ", group.Select(p => p.Zh))); + } + } + + Assert.True(conflicts.Count == 0, + "同一英文文本对应了不同 error.code,缓存反向映射会引入歧义:\n" + + string.Join("\n", conflicts.Take(20))); + } + + private static List LoadSourcePairs() + { + string root = FindRepoRoot(); + var pairs = new List(); + foreach (string file in EnumerateSourceFiles(root)) + { + string source = File.ReadAllText(file); + bool includeBare = string.Equals(Path.GetFileName(file), "Localization.cs", StringComparison.Ordinal); + ExtractPairs(source, includeBare, pairs); + } + return pairs; + } + + private static string Render(Pair pair, bool english) + { + string template = english ? pair.En : pair.Zh; + if (!pair.IsFormat) return template; + return string.Format(template, SampleArgs(pair)); + } + + private static object?[] SampleArgs(Pair pair) + { + int max = Math.Max(MaxPlaceholder(pair.Zh), MaxPlaceholder(pair.En)); + return Enumerable.Range(0, max + 1).Select(_ => (object?)"X").ToArray(); + } + + private static void AssertSameCode(int status, string zh, string en, params object?[] args) + { + var failures = new List(); + AssertSameCode(status, zh, en, args, failures); + Assert.True(failures.Count == 0, string.Join("\n", failures)); + } + + private static void AssertSameCode(int status, string zh, string en, object?[] args, List failures) + { + Localization.SetLanguage("zh-CN"); + string zhMessage = args.Length == 0 ? Localization.T(zh, en) : Localization.F(zh, en, args); + string zhCode = Localization.ErrorCodeFor(status, zhMessage); + + Localization.SetLanguage("en"); + string enMessage = args.Length == 0 ? Localization.T(zh, en) : Localization.F(zh, en, args); + string enCode = Localization.ErrorCodeFor(status, enMessage); + + if (!string.Equals(zhCode, enCode, StringComparison.Ordinal)) + failures.Add($"{zh} => {en} (status {status}): zh={zhCode}, en={enCode}"); + } + + private static string FindRepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null) + { + if (File.Exists(Path.Combine(dir.FullName, "SLDataAPI.csproj"))) + return dir.FullName; + dir = dir.Parent; + } + throw new InvalidOperationException("找不到仓库根目录(SLDataAPI.csproj)"); + } + + private static IEnumerable EnumerateSourceFiles(string root) + { + foreach (string file in Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)) + { + string[] parts = file.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, + StringSplitOptions.RemoveEmptyEntries); + if (parts.Any(p => p.Equals("bin", StringComparison.OrdinalIgnoreCase) || + p.Equals("obj", StringComparison.OrdinalIgnoreCase))) + continue; + yield return file; + } + } + + private sealed record Pair(string Zh, string En, bool IsFormat); + + private static void ExtractPairs(string source, bool includeBare, List pairs) + { + for (int i = 0; i < source.Length; i++) + { + bool isFormat; + int argsStart; + if (StartsWith(source, i, "Localization.T(")) + { + argsStart = i + "Localization.T(".Length; + isFormat = false; + } + else if (StartsWith(source, i, "Localization.F(")) + { + argsStart = i + "Localization.F(".Length; + isFormat = true; + } + else if (includeBare && MatchesBareCall(source, i, "T(")) + { + argsStart = i + 2; + isFormat = false; + } + else if (includeBare && MatchesBareCall(source, i, "F(")) + { + argsStart = i + 2; + isFormat = true; + } + else + { + continue; + } + + int openParen = argsStart - 1; + int closeParen = FindMatchingParen(source, openParen); + if (closeParen < 0) + { + i = argsStart; + continue; + } + + string argsText = source.Substring(argsStart, closeParen - argsStart); + List args = SplitTopLevel(argsText); + if (args.Count >= 2) + { + string? zh = EvalStringExpression(args[0]); + string? en = EvalStringExpression(args[1]); + if (zh != null && en != null) + pairs.Add(new Pair(zh, en, isFormat)); + } + + i = closeParen; + } + } + + private static bool StartsWith(string source, int index, string token) => + index >= 0 && index + token.Length <= source.Length && + source.AsSpan(index, token.Length).SequenceEqual(token); + + private static bool MatchesBareCall(string source, int index, string token) + { + if (!StartsWith(source, index, token)) return false; + if (index == 0) return true; + char prev = source[index - 1]; + return !char.IsLetterOrDigit(prev) && prev != '_' && prev != '.'; + } + + private static int FindMatchingParen(string source, int openParen) + { + int depth = 0; + bool inString = false, verbatim = false, inChar = false, lineComment = false, blockComment = false; + + for (int i = openParen; i < source.Length; i++) + { + char c = source[i]; + + if (lineComment) + { + if (c == '\n') lineComment = false; + continue; + } + if (blockComment) + { + if (c == '*' && i + 1 < source.Length && source[i + 1] == '/') + { + blockComment = false; + i++; + } + continue; + } + if (inString) + { + if (verbatim) + { + if (c == '"') + { + if (i + 1 < source.Length && source[i + 1] == '"') i++; + else inString = false; + } + } + else + { + if (c == '\\') i++; + else if (c == '"') inString = false; + } + continue; + } + if (inChar) + { + if (c == '\\') i++; + else if (c == '\'') inChar = false; + continue; + } + + if (c == '/' && i + 1 < source.Length) + { + if (source[i + 1] == '/') { lineComment = true; i++; continue; } + if (source[i + 1] == '*') { blockComment = true; i++; continue; } + } + if (c == '"') + { + verbatim = i > 0 && source[i - 1] == '@'; + inString = true; + continue; + } + if (c == '\'') + { + inChar = true; + continue; + } + if (c == '(') depth++; + else if (c == ')') + { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + private static List SplitTopLevel(string text) + { + var result = new List(); + int start = 0, depth = 0; + bool inString = false, verbatim = false, inChar = false, lineComment = false, blockComment = false; + + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + + if (lineComment) + { + if (c == '\n') lineComment = false; + continue; + } + if (blockComment) + { + if (c == '*' && i + 1 < text.Length && text[i + 1] == '/') + { + blockComment = false; + i++; + } + continue; + } + if (inString) + { + if (verbatim) + { + if (c == '"') + { + if (i + 1 < text.Length && text[i + 1] == '"') i++; + else inString = false; + } + } + else + { + if (c == '\\') i++; + else if (c == '"') inString = false; + } + continue; + } + if (inChar) + { + if (c == '\\') i++; + else if (c == '\'') inChar = false; + continue; + } + + if (c == '/' && i + 1 < text.Length) + { + if (text[i + 1] == '/') { lineComment = true; i++; continue; } + if (text[i + 1] == '*') { blockComment = true; i++; continue; } + } + if (c == '"') + { + verbatim = i > 0 && text[i - 1] == '@'; + inString = true; + continue; + } + if (c == '\'') + { + inChar = true; + continue; + } + if (c == '(' || c == '{' || c == '[') depth++; + else if (c == ')' || c == '}' || c == ']') depth--; + else if (c == ',' && depth == 0) + { + result.Add(text.Substring(start, i - start)); + start = i + 1; + } + } + + result.Add(text.Substring(start)); + return result; + } + + private static string? EvalStringExpression(string expression) + { + string text = expression.Trim(); + if (text.Length == 0) return null; + + var sb = new StringBuilder(); + int i = 0; + bool sawLiteral = false; + + while (i < text.Length) + { + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (i >= text.Length) break; + + if (text[i] == '+') + { + i++; + continue; + } + + bool verbatim = false; + if (text[i] == '@') + { + verbatim = true; + i++; + } + if (i >= text.Length || text[i] != '"') return null; + i++; + + if (verbatim) + { + bool closed = false; + while (i < text.Length) + { + char c = text[i++]; + if (c == '"') + { + if (i < text.Length && text[i] == '"') + { + sb.Append('"'); + i++; + } + else + { + closed = true; + break; + } + } + else + { + sb.Append(c); + } + } + if (!closed) return null; + } + else + { + bool closed = false; + while (i < text.Length) + { + char c = text[i++]; + if (c == '"') + { + closed = true; + break; + } + if (c != '\\') + { + sb.Append(c); + continue; + } + + if (i >= text.Length) return null; + char esc = text[i++]; + switch (esc) + { + case 'n': sb.Append('\n'); break; + case 'r': sb.Append('\r'); break; + case 't': sb.Append('\t'); break; + case '\\': sb.Append('\\'); break; + case '"': sb.Append('"'); break; + case '\'': sb.Append('\''); break; + case '0': sb.Append('\0'); break; + case 'u': + if (i + 4 > text.Length) return null; + if (!int.TryParse(text.AsSpan(i, 4), NumberStyles.HexNumber, + CultureInfo.InvariantCulture, out int code)) + return null; + sb.Append((char)code); + i += 4; + break; + case 'x': + { + int len = 0; + while (len < 4 && i + len < text.Length && Uri.IsHexDigit(text[i + len])) len++; + if (len == 0) return null; + sb.Append((char)int.Parse(text.AsSpan(i, len), NumberStyles.HexNumber, + CultureInfo.InvariantCulture)); + i += len; + break; + } + default: + sb.Append(esc); + break; + } + } + if (!closed) return null; + } + + sawLiteral = true; + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (i < text.Length && text[i] != '+') return null; + } + + return sawLiteral ? sb.ToString() : null; + } + + private static int MaxPlaceholder(string template) + { + int max = -1; + for (int i = 0; i + 1 < template.Length; i++) + { + if (template[i] != '{' || !char.IsDigit(template[i + 1])) continue; + int j = i + 1; + int value = 0; + while (j < template.Length && char.IsDigit(template[j])) + { + value = value * 10 + (template[j] - '0'); + j++; + } + if (j < template.Length && template[j] == '}') + { + max = Math.Max(max, value); + i = j; + } + } + return max; + } +} diff --git a/tests/SLDataAPI.Features.Tests/LocalizationTests.cs b/tests/SLDataAPI.Features.Tests/LocalizationTests.cs new file mode 100644 index 0000000..5a9c2dc --- /dev/null +++ b/tests/SLDataAPI.Features.Tests/LocalizationTests.cs @@ -0,0 +1,276 @@ +// Copyright (C) 2026 DNT_OF +// SPDX-License-Identifier: Apache-2.0 +// Original project: https://github.com/DNTOF/SLDataAPI + +using SLDataAPI.Services; +using Xunit; + +namespace SLDataAPI.Features.Tests; + +/// +/// i18n 回归测试: +/// a) zh-CN 下所有既有映射表与关键字逐项锁定; +/// b) en 下输出英文; +/// c) 稳定 code 在 zh-CN / en 下完全一致; +/// d) 非法 language 回退 zh-CN。 +/// 本地化使用静态当前语言,因此本测试程序集禁用了并行执行(见 AssemblyInfo.cs)。 +/// +public class LocalizationTests : IDisposable +{ + public LocalizationTests() => Localization.SetLanguage("zh-CN"); + + public void Dispose() => Localization.SetLanguage("zh-CN"); + + // ────────────── a) zh-CN 既有映射表逐项锁定 ────────────── + + [Theory] + [InlineData("ClassD", "D级人员")] + [InlineData("Scientist", "科学家")] + [InlineData("FacilityGuard", "保安")] + [InlineData("NtfPrivate", "九尾狐-士兵")] + [InlineData("NtfSergeant", "九尾狐-中士")] + [InlineData("NtfCaptain", "九尾狐-指挥官")] + [InlineData("ChaosConscript", "混沌-征召兵")] + [InlineData("ChaosRifleman", "混沌-步枪手")] + [InlineData("ChaosMarauder", "混沌-掠夺者")] + [InlineData("ChaosRepressor", "混沌-镇压者")] + [InlineData("Scp173", "SCP-173")] + [InlineData("Scp049", "SCP-049")] + [InlineData("Scp096", "SCP-096")] + [InlineData("Scp106", "SCP-106")] + [InlineData("Scp939", "SCP-939")] + [InlineData("Scp079", "SCP-079")] + [InlineData("Scp3114", "SCP-3114")] + [InlineData("Scp0492", "SCP-049-2")] + [InlineData("Spectator", "观察者")] + [InlineData("Tutorial", "教程")] + [InlineData("None", "未分配")] + public void ZhDataRoleNames_MatchPreI18nTable(string role, string expected) + { + Assert.Equal(expected, Localization.DataRoleText(role, 0)); + } + + [Theory] + [InlineData("ClassD", "D级人员")] + [InlineData("Scientist", "科学家")] + [InlineData("FacilityGuard", "设施警卫")] + [InlineData("NtfSpecialist", "九尾狐-中士")] + [InlineData("NtfSergeant", "九尾狐-军士")] + [InlineData("NtfCaptain", "九尾狐-队长")] + [InlineData("NtfPrivate", "九尾狐-列兵")] + [InlineData("ChaosConscript", "混沌分裂者-征召兵")] + [InlineData("ChaosRifleman", "混沌分裂者-步枪手")] + [InlineData("ChaosMarauder", "混沌分裂者-掠夺者")] + [InlineData("ChaosRepressor", "混沌分裂者-镇压者")] + [InlineData("Scp049", "SCP-049")] + [InlineData("Scp0492", "SCP-049-2")] + [InlineData("Scp079", "SCP-079")] + [InlineData("Scp096", "SCP-096")] + [InlineData("Scp106", "SCP-106")] + [InlineData("Scp173", "SCP-173")] + [InlineData("Scp939", "SCP-939")] + [InlineData("Scp3114", "SCP-3114")] + [InlineData("Tutorial", "教程角色")] + [InlineData("Spectator", "旁观者")] + [InlineData("Overwatch", "观察者")] + [InlineData("Filmmaker", "摄影者")] + public void ZhVoiceRoleNames_MatchPreI18nTable(string role, string expected) + { + Assert.Equal(expected, Localization.VoiceRoleText(role)); + } + + [Theory] + [InlineData("SCPs", "SCP")] + [InlineData("FoundationForces", "基金会")] + [InlineData("ClassD", "D级")] + [InlineData("ChaosInsurgency", "混沌")] + [InlineData("Dead", "观察者")] + [InlineData("OtherAlive", "其他")] + public void ZhTeamNames_MatchPreI18nTable(string team, string expected) + { + Assert.Equal(expected, Localization.TeamText(team)); + } + + [Fact] + public void ZhUnknownFallbacks_MatchPreI18nBehavior() + { + // 数据接口未知职业保留「未知(数值)」诊断兜底 + Assert.Equal("未知(42)", Localization.DataRoleText("NotARole", 42)); + // 语音接口未知职业保留枚举成员名兜底 + Assert.Equal("NotARole", Localization.VoiceRoleText("NotARole")); + // 未知阵营沿用「未知」 + Assert.Equal("未知", Localization.TeamText("NotATeam")); + } + + [Fact] + public void ZhPhaseNukeAndKeywordTexts_AreLocked() + { + Assert.Equal("等待开始", Localization.PhaseText(false, false)); + // zh-CN 保持既有两态文案:回合已结束时仍未开始 → 等待开始 + Assert.Equal("等待开始", Localization.PhaseText(false, true)); + Assert.Equal("进行中", Localization.PhaseText(true, false)); + + Assert.Equal("未激活", Localization.WarheadText(false, false, 0)); + // 拉杆已拉起但尚未开始倒计时:zh-CN 保持既有「未激活」,稳定 code 为 armed + Assert.Equal("未激活", Localization.WarheadText(false, false, 0, armed: true)); + Assert.Equal("倒计时:42秒", Localization.WarheadText(false, true, 42)); + Assert.Equal("已爆炸", Localization.WarheadText(true, false, 0)); + + // app 依赖的关键字 + Assert.Contains("超时", Localization.TimeoutRequestHeaders); + Assert.Contains("超时", Localization.TimeoutRequestBody); + Assert.Contains("超时", Localization.TimeoutMainThread); + Assert.Contains("符号链接", Localization.SymlinkForbidden); + Assert.Contains("D级", Localization.TeamText("ClassD")); + Assert.Contains("混沌", Localization.TeamText("ChaosInsurgency")); + Assert.Contains("基金会", Localization.TeamText("FoundationForces")); + Assert.Contains("九尾狐", Localization.DataRoleText("NtfCaptain", 0)); + Assert.Contains("教程", Localization.DataRoleText("Tutorial", 0)); + // 源码既有文案是「观察者」/「旁观者」,不是「观众」;按 zh-CN 逐字不变约束保留原值。 + Assert.Contains("观察者", Localization.TeamText("Dead")); + Assert.Contains("观察者", Localization.DataRoleText("Spectator", 0)); + } + + // ────────────── b) en 输出英文 ────────────── + + [Fact] + public void EnglishOutput_IsTranslated() + { + Localization.SetLanguage("en"); + + Assert.Equal("Class-D Personnel", Localization.DataRoleText("ClassD", 0)); + Assert.Equal("NTF Captain", Localization.DataRoleText("NtfCaptain", 0)); + Assert.Equal("NTF Specialist", Localization.DataRoleText("NtfSpecialist", 0)); + Assert.Equal("Unknown", Localization.DataRoleText("NotARole", 42)); + Assert.Equal("Facility Guard", Localization.VoiceRoleText("FacilityGuard")); + Assert.Equal("Foundation", Localization.TeamText("FoundationForces")); + Assert.Equal("Waiting to start", Localization.PhaseText(false, false)); + Assert.Equal("Ended", Localization.PhaseText(false, true)); + Assert.Equal("In progress", Localization.PhaseText(true, false)); + Assert.Equal("Inactive", Localization.WarheadText(false, false, 0)); + Assert.Equal("Armed", Localization.WarheadText(false, false, 0, armed: true)); + Assert.Equal("Detonating: 42s", Localization.WarheadText(false, true, 42)); + Assert.Equal("Detonated", Localization.WarheadText(true, false, 0)); + + Assert.Contains("timed out", Localization.TimeoutRequestHeaders); + Assert.Contains("symbolic link", Localization.SymlinkForbidden); + } + + // ────────────── c) code 与语言无关 ────────────── + + [Theory] + [InlineData("ClassD")] + [InlineData("NtfCaptain")] + [InlineData("ChaosInsurgency")] + [InlineData("NotARole")] + public void RoleAndTeamCodes_AreLanguageIndependent(string code) + { + Localization.SetLanguage("zh-CN"); + string zhRoleCode = Localization.RoleCode(code); + string zhTeamCode = Localization.TeamCode(code); + + Localization.SetLanguage("en"); + Assert.Equal(zhRoleCode, Localization.RoleCode(code)); + Assert.Equal(zhTeamCode, Localization.TeamCode(code)); + Assert.Equal(code, zhRoleCode); + Assert.Equal(code, zhTeamCode); + } + + [Fact] + public void PhaseWarheadAndErrorCodes_AreLanguageIndependent() + { + foreach (bool started in new[] { false, true }) + foreach (bool ended in new[] { false, true }) + { + Localization.SetLanguage("zh-CN"); + string zh = Localization.PhaseCode(started, ended); + Localization.SetLanguage("en"); + Assert.Equal(zh, Localization.PhaseCode(started, ended)); + } + + foreach (bool detonated in new[] { false, true }) + foreach (bool detonating in new[] { false, true }) + foreach (bool armed in new[] { false, true }) + { + Localization.SetLanguage("zh-CN"); + string zh = Localization.WarheadCode(detonated, detonating, armed); + Localization.SetLanguage("en"); + Assert.Equal(zh, Localization.WarheadCode(detonated, detonating, armed)); + } + + Localization.SetLanguage("zh-CN"); + string zhTimeout = Localization.ErrorCodeFor(408, "请求超时:头部长时间未收完"); + string zhSymlink = Localization.ErrorCodeFor(400, "路径经过符号链接或目录联接(junction),已拒绝"); + string zhUnauthorized = Localization.ErrorCodeFor(401, "API Key 无效"); + string zhForbidden = Localization.ErrorCodeFor(403, "API Key 有效但未授权该端点"); + string zhNotFound = Localization.ErrorCodeFor(404, "路径不存在"); + string zhInvalid = Localization.ErrorCodeFor(400, "缺少 action 字段"); + + Localization.SetLanguage("en"); + Assert.Equal(zhTimeout, Localization.ErrorCodeFor(408, Localization.TimeoutRequestHeaders)); + Assert.Equal(zhSymlink, Localization.ErrorCodeFor(400, Localization.SymlinkForbidden)); + Assert.Equal(zhUnauthorized, Localization.ErrorCodeFor(401, "Invalid API key")); + Assert.Equal(zhForbidden, Localization.ErrorCodeFor(403, "not authorized")); + Assert.Equal(zhNotFound, Localization.ErrorCodeFor(404, "Path not found")); + Assert.Equal(zhInvalid, Localization.ErrorCodeFor(400, "Missing action field")); + } + + [Fact] + public void RequiredErrorCodes_AreStable() + { + Localization.SetLanguage("zh-CN"); + Assert.Equal("timeout", Localization.ErrorCodeFor(408, "请求超时")); + Assert.Equal("symlink_forbidden", Localization.ErrorCodeFor(400, "路径经过符号链接")); + Assert.Equal("unauthorized", Localization.ErrorCodeFor(401, "API Key 无效")); + Assert.Equal("forbidden", Localization.ErrorCodeFor(403, "未授权")); + Assert.Equal("not_found", Localization.ErrorCodeFor(404, "找不到玩家")); + Assert.Equal("invalid_argument", Localization.ErrorCodeFor(400, "缺少 target 字段")); + Assert.Equal("armed", Localization.WarheadCode(false, false, armed: true)); + Assert.Equal("method_not_allowed", Localization.ErrorCodeFor(405, "Method Not Allowed")); + Assert.Equal("payload_too_large", Localization.ErrorCodeFor(413, "payload too large")); + Assert.Equal("internal_error", Localization.ErrorCodeFor(500, "内部错误")); + } + + // ────────────── d) 非法 language 回退 ────────────── + + [Fact] + public void InvalidLanguage_FallsBackToZhCn() + { + Localization.SetLanguage("en"); + Assert.False(Localization.SetLanguage("fr-FR")); + Assert.Equal("zh-CN", Localization.Language); + Assert.Equal("zh-CN", Localization.Lang); + + Assert.Equal("zh-CN", Localization.NormalizeLanguage("fr-FR")); + Assert.Equal("zh-CN", Localization.NormalizeLanguage("zh")); + Assert.Equal("zh-CN", Localization.NormalizeLanguage(null)); + Assert.Equal("en", Localization.NormalizeLanguage("EN")); + } + + [Fact] + public void ConfigLanguage_DefaultsToZhCn() + { + Assert.Equal("zh-CN", new Config().Language); + Assert.Equal("zh-CN", Localization.DefaultLanguage); + } + + [Fact] + public void SetLanguage_AcceptsSupportedValuesCaseInsensitively() + { + Assert.True(Localization.SetLanguage("EN")); + Assert.Equal("en", Localization.Language); + Assert.True(Localization.SetLanguage(" zh-cn ")); + Assert.Equal("zh-CN", Localization.Language); + Assert.True(Localization.SetLanguage("")); + Assert.Equal("zh-CN", Localization.Language); + } + + [Fact] + public void Format_UsesCurrentLanguageTemplate() + { + Localization.SetLanguage("zh-CN"); + Assert.Equal("值=7", Localization.F("值={0}", "value={0}", 7)); + Localization.SetLanguage("en"); + Assert.Equal("value=7", Localization.F("值={0}", "value={0}", 7)); + } +} diff --git a/tests/SLDataAPI.Features.Tests/SLDataAPI.Features.Tests.csproj b/tests/SLDataAPI.Features.Tests/SLDataAPI.Features.Tests.csproj index 2ed4886..4280e07 100644 --- a/tests/SLDataAPI.Features.Tests/SLDataAPI.Features.Tests.csproj +++ b/tests/SLDataAPI.Features.Tests/SLDataAPI.Features.Tests.csproj @@ -8,6 +8,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive @@ -20,5 +21,8 @@ + + +