using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class Announcements(ItemCatalog catalog, TimeProvider clock)
{
public static JArray News(JObject state) => new(state.Array("news").OrderByDescending(x => x.Value<bool>("priority")).ThenByDescending(x => x.Value<string>("updatedAt")));
public static JArray History(JObject state) => new(state.Array("mailPublications").Reverse().Take(100).Select(x =>
{
var row = (JObject)x.DeepClone(); row.Remove("fingerprint"); return row;
}));
public JObject SaveNews(JObject state, JObject body)
{
var id = body.Value<string>("id");
var existing = string.IsNullOrEmpty(id) ? null : state.Array("news").OfType<JObject>().FirstOrDefault(x => x.Value<string>("id") == id) ?? throw new ApiException(404, "新闻不存在。");
if (existing is not null && body.Integer("version", 1) != existing.Value<long>("version")) throw new ApiException(409, "新闻已被修改,请刷新后重新编辑。");
if (existing is null && state.Array("news").Count >= 200) throw new ApiException(400, "最多保存 200 条新闻,请先删除不再需要的内容。");
if (body["published"]?.Type != JTokenType.Boolean || body["priority"]?.Type != JTokenType.Boolean) throw new ApiException(400, "缺少新闻发布状态。");
var published = body.Value<bool>("published");
var row = new JObject
{
["id"] = existing?.Value<string>("id") ?? Wire.NewId(), ["version"] = (existing?.Value<long>("version") ?? 0) + 1,
["title"] = body.RequiredString("title", 300).Trim(), ["englishTitle"] = Optional(body, "englishTitle", 300),
["url"] = Link(body, "url"), ["imageUrl"] = Link(body, "imageUrl"), ["priority"] = body.Value<bool>("priority"),
["published"] = published, ["updatedAt"] = clock.GetUtcNow().ToString("O"),
["publishedAt"] = published ? existing?.Value<string>("publishedAt") ?? clock.GetUtcNow().ToString("O") : existing?.Value<string>("publishedAt")
};
if (existing is null) state.Array("news").Add(row); else existing.Replace(row);
return row;
}
public static void DeleteNews(JObject state, JObject body)
{
var row = state.Array("news").OfType<JObject>().FirstOrDefault(x => x.Value<string>("id") == body.RequiredString("id", 24)) ?? throw new ApiException(404, "新闻不存在。");
if (row.Value<long>("version") != body.Integer("version", 1)) throw new ApiException(409, "新闻已被修改,请刷新后再删除。");
row.Remove();
}
public static JArray GameNews(JObject state, long build)
{
return new JArray(News(state).Where(x => x.Value<bool>("published")).Select(x =>
{
var title = x.Value<string>("title")!;
var english = string.IsNullOrEmpty(x.Value<string>("englishTitle")) ? title : x.Value<string>("englishTitle")!;
var row = new JObject { ["_id"] = GameVersion.Oid(x.Value<string>("id")!, build), ["Msg"] = english,
["Messages"] = new JArray(new JObject { ["LanguageCode"] = "zh", ["Message"] = title }, new JObject { ["LanguageCode"] = "tc", ["Message"] = title }, new JObject { ["LanguageCode"] = "en", ["Message"] = english }),
["Prop"] = x.Value<string>("url") ?? "", ["Priority"] = x.Value<bool>("priority"),
["Date"] = GameVersion.Date(DateTimeOffset.Parse(x.Value<string>("publishedAt")!).ToUnixTimeMilliseconds(), build) };
if (!string.IsNullOrEmpty(x.Value<string>("imageUrl"))) row["ImageUrl"] = x["imageUrl"]!.DeepClone();
return row;
}));
}
public JObject PublishMail(JObject state, JObject body)
{
if (!Guid.TryParseExact(body.RequiredString("requestId", 36), "D", out var id)) throw new ApiException(400, "Invalid requestId");
var audience = body.RequiredString("audience", 20);
if (audience is not ("all" or "selected")) throw new ApiException(400, "请选择邮件收件范围。");
var ids = body["targetIds"] as JArray ?? new();
if (ids.Count > 1000 || ids.Any(x => x.Type != JTokenType.String)) throw new ApiException(400, "收件人列表无效。");
var template = new JObject { ["sndr"] = body.RequiredString("sender", 80).Trim(), ["sub"] = body.RequiredString("subject", 160).Trim(), ["msg"] = body.RequiredString("body", 32000) };
foreach (var (source, target) in new[] { ("credits", "RegularCredits"), ("platinum", "PremiumCredits") })
if (body[source] is not null) { var amount = body.Integer(source, 0, 10_000_000); if (amount > 0) template[target] = amount; }
var attachments = body["attachments"] as JArray ?? new();
if (attachments.Count > 50 || attachments.Any(x => x is not JObject)) throw new ApiException(400, "最多添加 50 个附件。");
template["countedAtt"] = new JArray(attachments.OfType<JObject>().Select(x =>
{
var type = catalog.ResolveType(x.RequiredString("type")); catalog.Get(type);
return new JObject { ["ItemType"] = type, ["ItemCount"] = x.Integer("count", 1, 100) };
}));
var normalizedIds = new JArray(ids.Select(x => x.ToString()).Distinct().Order());
var fingerprint = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(new JObject { ["audience"] = audience, ["targets"] = normalizedIds, ["message"] = template }.ToString(Formatting.None))));
var previous = state.Array("mailPublications").OfType<JObject>().FirstOrDefault(x => x.Value<string>("requestId") == id.ToString("D"));
if (previous is not null)
{
if (previous.Value<string>("fingerprint") != fingerprint) throw new ApiException(409, "发布编号已用于另一封邮件。");
var receipt = (JObject)previous.DeepClone(); receipt.Remove("fingerprint"); return receipt;
}
var targets = audience == "all" ? Accounts.All(state).ToArray() : normalizedIds.Select(x => state.Obj("accounts")[x.ToString()] as JObject ?? throw new ApiException(404, "收件账号不存在。")).ToArray();
if (targets.Length == 0) throw new ApiException(400, "没有可接收邮件的玩家。");
foreach (var target in targets) InboxApi.Create(target, template, clock.GetUtcNow());
var publication = new JObject { ["requestId"] = id.ToString("D"), ["audience"] = audience, ["targetIds"] = normalizedIds, ["recipients"] = targets.Length,
["sender"] = template["sndr"]!.DeepClone(), ["subject"] = template["sub"]!.DeepClone(), ["body"] = template["msg"]!.DeepClone(),
["credits"] = body.Value<long>("credits"), ["platinum"] = body.Value<long>("platinum"), ["attachments"] = attachments.DeepClone(),
["publishedAt"] = clock.GetUtcNow().ToString("O"), ["fingerprint"] = fingerprint };
state.Array("mailPublications").Add(publication);
var result = (JObject)publication.DeepClone(); result.Remove("fingerprint"); return result;
}
private static string Optional(JObject body, string key, int length)
{
if (body[key] is null || body[key]!.Type == JTokenType.Null) return "";
if (body[key]!.Type != JTokenType.String || body.Value<string>(key)!.Length > length) throw new ApiException(400, "Invalid " + key);
return body.Value<string>(key)!.Trim();
}
private static string Link(JObject body, string key)
{
var value = Optional(body, key, 2048);
if (value.Length > 0 && (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https") || uri.UserInfo.Length > 0))
throw new ApiException(400, "链接必须为有效的 HTTP 或 HTTPS 地址。");
return value;
}
}
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class Announcements(ItemCatalog catalog, TimeProvider clock)
{
public static JArray News(JObject state) => new(state.Array("news").OrderByDescending(x => x.Value<bool>("priority")).ThenByDescending(x => x.Value<string>("updatedAt")));
public static JArray History(JObject state) => new(state.Array("mailPublications").Reverse().Take(100).Select(x =>
{
var row = (JObject)x.DeepClone(); row.Remove("fingerprint"); return row;
}));
public JObject SaveNews(JObject state, JObject body)
{
var id = body.Value<string>("id");
var existing = string.IsNullOrEmpty(id) ? null : state.Array("news").OfType<JObject>().FirstOrDefault(x => x.Value<string>("id") == id) ?? throw new ApiException(404, "新闻不存在。");
if (existing is not null && body.Integer("version", 1) != existing.Value<long>("version")) throw new ApiException(409, "新闻已被修改,请刷新后重新编辑。");
if (existing is null && state.Array("news").Count >= 200) throw new ApiException(400, "最多保存 200 条新闻,请先删除不再需要的内容。");
if (body["published"]?.Type != JTokenType.Boolean || body["priority"]?.Type != JTokenType.Boolean) throw new ApiException(400, "缺少新闻发布状态。");
var published = body.Value<bool>("published");
var row = new JObject
{
["id"] = existing?.Value<string>("id") ?? Wire.NewId(), ["version"] = (existing?.Value<long>("version") ?? 0) + 1,
["title"] = body.RequiredString("title", 300).Trim(), ["englishTitle"] = Optional(body, "englishTitle", 300),
["url"] = Link(body, "url"), ["imageUrl"] = Link(body, "imageUrl"), ["priority"] = body.Value<bool>("priority"),
["published"] = published, ["updatedAt"] = clock.GetUtcNow().ToString("O"),
["publishedAt"] = published ? existing?.Value<string>("publishedAt") ?? clock.GetUtcNow().ToString("O") : existing?.Value<string>("publishedAt")
};
if (existing is null) state.Array("news").Add(row); else existing.Replace(row);
return row;
}
public static void DeleteNews(JObject state, JObject body)
{
var row = state.Array("news").OfType<JObject>().FirstOrDefault(x => x.Value<string>("id") == body.RequiredString("id", 24)) ?? throw new ApiException(404, "新闻不存在。");
if (row.Value<long>("version") != body.Integer("version", 1)) throw new ApiException(409, "新闻已被修改,请刷新后再删除。");
row.Remove();
}
public static JArray GameNews(JObject state, long build)
{
return new JArray(News(state).Where(x => x.Value<bool>("published")).Select(x =>
{
var title = x.Value<string>("title")!;
var english = string.IsNullOrEmpty(x.Value<string>("englishTitle")) ? title : x.Value<string>("englishTitle")!;
var row = new JObject { ["_id"] = GameVersion.Oid(x.Value<string>("id")!, build), ["Msg"] = english,
["Messages"] = new JArray(new JObject { ["LanguageCode"] = "zh", ["Message"] = title }, new JObject { ["LanguageCode"] = "tc", ["Message"] = title }, new JObject { ["LanguageCode"] = "en", ["Message"] = english }),
["Prop"] = x.Value<string>("url") ?? "", ["Priority"] = x.Value<bool>("priority"),
["Date"] = GameVersion.Date(DateTimeOffset.Parse(x.Value<string>("publishedAt")!).ToUnixTimeMilliseconds(), build) };
if (!string.IsNullOrEmpty(x.Value<string>("imageUrl"))) row["ImageUrl"] = x["imageUrl"]!.DeepClone();
return row;
}));
}
public JObject PublishMail(JObject state, JObject body)
{
if (!Guid.TryParseExact(body.RequiredString("requestId", 36), "D", out var id)) throw new ApiException(400, "Invalid requestId");
var audience = body.RequiredString("audience", 20);
if (audience is not ("all" or "selected")) throw new ApiException(400, "请选择邮件收件范围。");
var ids = body["targetIds"] as JArray ?? new();
if (ids.Count > 1000 || ids.Any(x => x.Type != JTokenType.String)) throw new ApiException(400, "收件人列表无效。");
var template = new JObject { ["sndr"] = body.RequiredString("sender", 80).Trim(), ["sub"] = body.RequiredString("subject", 160).Trim(), ["msg"] = body.RequiredString("body", 32000) };
foreach (var (source, target) in new[] { ("credits", "RegularCredits"), ("platinum", "PremiumCredits") })
if (body[source] is not null) { var amount = body.Integer(source, 0, 10_000_000); if (amount > 0) template[target] = amount; }
var attachments = body["attachments"] as JArray ?? new();
if (attachments.Count > 50 || attachments.Any(x => x is not JObject)) throw new ApiException(400, "最多添加 50 个附件。");
template["countedAtt"] = new JArray(attachments.OfType<JObject>().Select(x =>
{
var type = catalog.ResolveType(x.RequiredString("type")); catalog.Get(type);
return new JObject { ["ItemType"] = type, ["ItemCount"] = x.Integer("count", 1, 100) };
}));
var normalizedIds = new JArray(ids.Select(x => x.ToString()).Distinct().Order());
var fingerprint = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(new JObject { ["audience"] = audience, ["targets"] = normalizedIds, ["message"] = template }.ToString(Formatting.None))));
var previous = state.Array("mailPublications").OfType<JObject>().FirstOrDefault(x => x.Value<string>("requestId") == id.ToString("D"));
if (previous is not null)
{
if (previous.Value<string>("fingerprint") != fingerprint) throw new ApiException(409, "发布编号已用于另一封邮件。");
var receipt = (JObject)previous.DeepClone(); receipt.Remove("fingerprint"); return receipt;
}
var targets = audience == "all" ? Accounts.All(state).ToArray() : normalizedIds.Select(x => state.Obj("accounts")[x.ToString()] as JObject ?? throw new ApiException(404, "收件账号不存在。")).ToArray();
if (targets.Length == 0) throw new ApiException(400, "没有可接收邮件的玩家。");
foreach (var target in targets) InboxApi.Create(target, template, clock.GetUtcNow());
var publication = new JObject { ["requestId"] = id.ToString("D"), ["audience"] = audience, ["targetIds"] = normalizedIds, ["recipients"] = targets.Length,
["sender"] = template["sndr"]!.DeepClone(), ["subject"] = template["sub"]!.DeepClone(), ["body"] = template["msg"]!.DeepClone(),
["credits"] = body.Value<long>("credits"), ["platinum"] = body.Value<long>("platinum"), ["attachments"] = attachments.DeepClone(),
["publishedAt"] = clock.GetUtcNow().ToString("O"), ["fingerprint"] = fingerprint };
state.Array("mailPublications").Add(publication);
var result = (JObject)publication.DeepClone(); result.Remove("fingerprint"); return result;
}
private static string Optional(JObject body, string key, int length)
{
if (body[key] is null || body[key]!.Type == JTokenType.Null) return "";
if (body[key]!.Type != JTokenType.String || body.Value<string>(key)!.Length > length) throw new ApiException(400, "Invalid " + key);
return body.Value<string>(key)!.Trim();
}
private static string Link(JObject body, string key)
{
var value = Optional(body, key, 2048);
if (value.Length > 0 && (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https") || uri.UserInfo.Length > 0))
throw new ApiException(400, "链接必须为有效的 HTTP 或 HTTPS 地址。");
return value;
}
}