From 7ac4c6091c0df966011faa7aacd65c79d3199eca Mon Sep 17 00:00:00 2001
From: DNT_OF <3174600270@qq.com>
Date: Sat, 14 Nov 2026 23:58:41 +0800
Subject: [PATCH 1/2] =?UTF-8?q?feat(i18n):=20=E6=96=B0=E5=A2=9E=E4=B8=AD?=
=?UTF-8?q?=E8=8B=B1=E6=96=87=E8=BE=93=E5=87=BA=E4=B8=8E=E7=A8=B3=E5=AE=9A?=
=?UTF-8?q?=20code=20=E5=AD=97=E6=AE=B5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 新增 language 配置(zh-CN 默认 / en),非法值回退并告警
- get_sl_data 追加 phase_code / warhead_code,玩家项追加 role_code / team_code
- 控制面与语音错误补齐稳定 code,所有 JSON 根对象追加 lang
- 数据 / 控制 / 语音文本按语言本地化,zh-CN 既有输出保持不变
- 修正 error.code 推断:en 下先还原中文文本,确保中英文 code 一致
- 补充 Commands 提示、README、CHANGELOG 与回归测试
---
Auth/ApiKeyService.cs | 21 +-
Auth/RemoteCommandGuard.cs | 12 +-
CHANGELOG.md | 20 +-
Commands/ApikeyParentCommand.cs | 3 +-
Commands/SldataapiParentCommand.cs | 6 +-
Config.cs | 8 +
Control/ControlAuth.cs | 9 +-
Control/ControlController.Features.cs | 107 ++--
Control/ControlController.cs | 329 +++++++----
Control/ControlMessageValidation.cs | 7 +-
Control/WsControlService.cs | 94 ++-
Data/ControlModels.cs | 7 +
Data/Models.cs | 15 +
Integrations/DntofDetector.cs | 3 +-
Integrations/ExiledInterop.cs | 11 +-
Integrations/PluginEndpointRegistry.cs | 9 +-
Integrations/SlPlayerController.cs | 30 +-
Plugin.cs | 9 +-
README.md | 13 +
Services/DataCollector.cs | 103 ++--
Services/ErrorCodeEnvelope.cs | 49 ++
Services/FileSandbox.cs | 19 +-
Services/FileService.cs | 64 ++-
Services/FileUploadSessions.cs | 22 +-
Services/HolidayGate.cs | 13 +-
Services/HttpServer.cs | 79 ++-
Services/Localization.cs | 383 +++++++++++++
Services/MainThreadExecutor.cs | 8 +-
Services/ServerLogService.cs | 18 +-
Services/TlsPolicy.cs | 8 +-
Voice/VoiceService.cs | 77 ++-
.../SLDataAPI.Auth.Tests.csproj | 1 +
tests/SLDataAPI.Auth.Tests/TlsPolicyTests.cs | 4 +-
.../SLDataAPI.Features.Tests/AssemblyInfo.cs | 8 +
.../ErrorCodeEnvelopeTests.cs | 73 +++
.../LocalizationCodeIndependenceTests.cs | 541 ++++++++++++++++++
.../LocalizationTests.cs | 276 +++++++++
.../SLDataAPI.Features.Tests.csproj | 4 +
38 files changed, 2059 insertions(+), 404 deletions(-)
create mode 100644 Services/ErrorCodeEnvelope.cs
create mode 100644 Services/Localization.cs
create mode 100644 tests/SLDataAPI.Features.Tests/AssemblyInfo.cs
create mode 100644 tests/SLDataAPI.Features.Tests/ErrorCodeEnvelopeTests.cs
create mode 100644 tests/SLDataAPI.Features.Tests/LocalizationCodeIndependenceTests.cs
create mode 100644 tests/SLDataAPI.Features.Tests/LocalizationTests.cs
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..6f2fe96 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,19 @@
# Changelog
+## 未发布 / Unreleased
+
+### 多语言(i18n)
+
+- 新增 `language` 配置(`zh-CN` 默认 / `en`);`zh-CN` 下既有字段名、字段顺序与中文文本保持不变,新增字段只追加在既有字段之后
+- `get_sl_data` 新增 `phase_code` / `warhead_code`,玩家项新增 `role_code` / `team_code`;控制面错误新增稳定 `code`;所有插件生成的 JSON 根对象新增 `lang`
+- `error.code` 推断在 en 下先还原为中文文本,再复用 zh-CN 的同一套规则,避免中英文推断结果不一致
+- 语音 `/status` 与 speaker 帧新增 `role_code`,语音角色名按语言本地化;`zh-CN` 输出不变
+- 新增纯逻辑本地化类与回归测试,覆盖 `zh-CN` 逐字回归、`en` 输出、code 与语言无关、非法值回退
+
+### 许可证
+
+- 由 **GPL-3.0-only** 变更为 **Apache-2.0**(允许闭源使用;须保留版权 / SPDX 头、NOTICE,并注明来自 DNTOF/SLDataAPI;禁止删改署名后换皮发布)。语音转发 / 录音仍标注为本项目原创。详见 `LICENSE`、`NOTICE`、README「许可证」。
+
## 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 +33,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