176 lines
7.1 KiB
C#
176 lines
7.1 KiB
C#
using System.Net.Http;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
|
||
namespace Hk4eGm.Services;
|
||
|
||
/// <summary>
|
||
/// muip 指令通道(复刻 hk4eGM.GM.MuipManager)。
|
||
/// GET http://{host}:{port}/api?cmd=..®ion=..&ticket=juliy@{unix}&sign=sha256(query+salt)
|
||
/// </summary>
|
||
public sealed class MuipClient
|
||
{
|
||
public const string Salt = "1d8z98SAKF98bdf878skswa8kdjfy1m9dses";
|
||
public const string TicketPrefix = "juliy@";
|
||
|
||
public const int CmdSendMail = 1005;
|
||
public const int CmdOnlineNum = 1101;
|
||
public const int CmdExec = 1116;
|
||
public const int CmdAddArtifact = 1127;
|
||
|
||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
|
||
|
||
private readonly AppConfig _cfg;
|
||
public string LastUrl { get; private set; } = "";
|
||
|
||
public MuipClient(AppConfig cfg) => _cfg = cfg;
|
||
|
||
public static string Sha256Hex(string text)
|
||
{
|
||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||
var sb = new StringBuilder(bytes.Length * 2);
|
||
foreach (var b in bytes) sb.Append(b.ToString("x2"));
|
||
return sb.ToString();
|
||
}
|
||
|
||
public string BuildUrl(int cmd, IReadOnlyDictionary<string, string>? param = null, long? now = null)
|
||
{
|
||
var ticket = $"{TicketPrefix}{now ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
|
||
var raw = new List<string>();
|
||
if (param != null)
|
||
foreach (var (k, v) in param) raw.Add($"{k}={v}");
|
||
raw.Add($"cmd={cmd}");
|
||
raw.Add($"region={_cfg.MuipRegion}");
|
||
raw.Add($"ticket={ticket}");
|
||
var query = string.Join("&", raw);
|
||
var sign = Sha256Hex(query + Salt);
|
||
|
||
var encoded = new List<string>();
|
||
if (param != null)
|
||
foreach (var (k, v) in param) encoded.Add($"{k}={Uri.EscapeDataString(v)}");
|
||
encoded.Add($"cmd={cmd}");
|
||
encoded.Add($"region={Uri.EscapeDataString(_cfg.MuipRegion)}");
|
||
encoded.Add($"ticket={ticket}");
|
||
encoded.Add($"sign={sign}");
|
||
return $"http://{_cfg.MuipHost}:{_cfg.MuipPort}/api?" + string.Join("&", encoded);
|
||
}
|
||
|
||
public async Task<string> GetAsync(int cmd, IReadOnlyDictionary<string, string>? param = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
var url = BuildUrl(cmd, param);
|
||
LastUrl = url;
|
||
try
|
||
{
|
||
using var resp = await Http.GetAsync(url, ct).ConfigureAwait(false);
|
||
return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
}
|
||
catch (TaskCanceledException)
|
||
{
|
||
throw new MuipException("连接超时:服务端未启动、服务端网络故障、防火墙屏蔽了GM端口");
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
var msg = ex.Message;
|
||
if (msg.Contains("积极拒绝") || msg.Contains("refused", StringComparison.OrdinalIgnoreCase))
|
||
throw new MuipException("目标服务器存在,但它拒绝了连接。可能是因为muip服务未正常运行、muip服务端口设置有误、防火墙未开放muip服务端口或者服务器宕机等");
|
||
if (msg.Contains("主机") || msg.Contains("host", StringComparison.OrdinalIgnoreCase))
|
||
throw new MuipException("主机名解析失败,可能原因为DNS服务器故障、网络连接有问题、主机名/IP地址不存在");
|
||
throw new MuipException(msg);
|
||
}
|
||
}
|
||
|
||
public async Task<int> OnlineCountAsync(CancellationToken ct = default)
|
||
{
|
||
var data = Parse(await GetAsync(CmdOnlineNum, null, ct));
|
||
if (data.Retcode != 0) throw new MuipException($"retcode={data.Retcode} / {data.Message}");
|
||
return data.OnlinePlayers;
|
||
}
|
||
|
||
public Task<MuipResult> ExecAsync(string message, string? uid = null, CancellationToken ct = default)
|
||
=> SendAsync(CmdExec, new Dictionary<string, string>
|
||
{
|
||
["uid"] = uid ?? _cfg.Uid,
|
||
["msg"] = message,
|
||
}, ct);
|
||
|
||
public Task<MuipResult> SendMailAsync(string uid, string sender, string title, string content,
|
||
string itemList, int expireDays = 30, bool collectible = false, CancellationToken ct = default)
|
||
=> SendAsync(CmdSendMail, new Dictionary<string, string>
|
||
{
|
||
["uid"] = uid,
|
||
["sender"] = sender,
|
||
["title"] = title,
|
||
["content"] = content,
|
||
["item_list"] = itemList,
|
||
["expire_time"] = expireDays.ToString(),
|
||
["is_collectible"] = collectible ? "true" : "false",
|
||
}, ct);
|
||
|
||
public Task<MuipResult> AddArtifactAsync(string uid, string itemId, int level, string mainProp,
|
||
IEnumerable<string> subProps, CancellationToken ct = default)
|
||
{
|
||
var extra = JsonSerializer.Serialize(new
|
||
{
|
||
level,
|
||
mainPropId = mainProp,
|
||
appendPropIdList = subProps.Select(s => int.TryParse(s, out var n) ? n : 0).ToArray(),
|
||
});
|
||
return SendAsync(CmdAddArtifact, new Dictionary<string, string>
|
||
{
|
||
["uid"] = uid,
|
||
["item_id"] = itemId,
|
||
["item_count"] = "1",
|
||
["extra_params"] = extra,
|
||
}, ct);
|
||
}
|
||
|
||
private async Task<MuipResult> SendAsync(int cmd, IReadOnlyDictionary<string, string> param,
|
||
CancellationToken ct)
|
||
=> Parse(await GetAsync(cmd, param, ct));
|
||
|
||
public static MuipResult Parse(string text)
|
||
{
|
||
text = (text ?? "").Trim();
|
||
if (text.Length == 0) return new MuipResult(0, "", 0);
|
||
try
|
||
{
|
||
using var doc = JsonDocument.Parse(text);
|
||
var root = doc.RootElement;
|
||
if (root.ValueKind != JsonValueKind.Object) return new MuipResult(-1, text[..Math.Min(500, text.Length)], 0);
|
||
var retcode = root.TryGetProperty("retcode", out var rc) && rc.TryGetInt32(out var n) ? n : 0;
|
||
var msg = root.TryGetProperty("msg", out var m) ? (m.GetString() ?? "") : "";
|
||
var online = 0;
|
||
if (root.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.Object &&
|
||
data.TryGetProperty("online_player_num_except_sub_account", out var op) && op.TryGetInt32(out var cnt))
|
||
online = cnt;
|
||
return new MuipResult(retcode, msg, online);
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
return new MuipResult(-1, text[..Math.Min(500, text.Length)], 0);
|
||
}
|
||
}
|
||
|
||
public static string Describe(MuipResult r)
|
||
{
|
||
if (r.Retcode == 0 && (r.Message is "" or "succ" or "success")) return "成功";
|
||
if (r.Message == "retcode") return $"retcode={r.Retcode}";
|
||
if (r.Message.Contains("recv from nodeserver timeout")) return "节点服务器超时";
|
||
if (r.Message.Contains("RET_FAIL")) return "指令执行失败(RET_FAIL)";
|
||
if (r.Message.Contains("multiserver")) return "该服未开启 multiserver";
|
||
return r.Message.Length > 0 ? $"retcode={r.Retcode} / {r.Message}" : $"retcode={r.Retcode}";
|
||
}
|
||
}
|
||
|
||
public sealed record MuipResult(int Retcode, string Message, int OnlinePlayers)
|
||
{
|
||
public bool Ok => Retcode == 0 && Message is not "retcode";
|
||
}
|
||
|
||
public sealed class MuipException : Exception
|
||
{
|
||
public MuipException(string message) : base(message) { }
|
||
}
|