XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;
using System.Text;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

/// <summary>Public PC event snapshots. Never imports accounts, sessions or commerce settings.</summary>
public static class OfficialEvents
{
    public const string Source = "https://api.warframe.com/cdn/worldState.php";
    public static readonly string[] Fields = ["Goals", "Alerts", "Events", "GlobalUpgrades", "FlashSales", "NodeOverrides", "HubEvents"];
    public static bool Enabled(JObject state, bool fallback = true) => state["worldState"]?.Value<bool?>("officialEventsEnabled") ?? fallback;

    public static JObject Validate(string json, long receivedAt)
    {
        using var text = new StringReader(json);
        using var reader = new JsonTextReader(text) { MaxDepth = 48, FloatParseHandling = FloatParseHandling.Decimal, DateParseHandling = DateParseHandling.None };
        var source = JObject.Load(reader, new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error });
        if (reader.Read()) throw new InvalidDataException("Official world state contains trailing data.");
        if (source["Time"]?.Type != JTokenType.Integer || !long.TryParse(source["Time"]!.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var timestamp) || timestamp is < 1_400_000_000 or > 10_000_000_000)
            throw new InvalidDataException("Official world state has no valid clock.");
        if (Math.Abs(timestamp * 1000 - receivedAt) > TimeSpan.FromMinutes(20).TotalMilliseconds)
            throw new InvalidDataException("Official world state is stale or the local clock is incorrect.");
        try { _ = GameVersion.Parse(source.RequiredString("BuildLabel", 256)); }
        catch (ApiException ex) { throw new InvalidDataException("Official world state has an invalid build label.", ex); }
        var selected = new JObject { ["Time"] = source["Time"]!.DeepClone(), ["BuildLabel"] = source["BuildLabel"]!.DeepClone() };
        foreach (var field in Fields)
        {
            if (source[field] is not JArray array || array.Count > 10000 || array.Any(x => x is not JObject))
                throw new InvalidDataException("Invalid official event collection: " + field);
            selected[field] = array.DeepClone();
        }
        if (source["Tmp"] is JValue { Type: JTokenType.String } tmp)
        {
            using var flagsText = new StringReader(tmp.Value<string>()!);
            using var flagsReader = new JsonTextReader(flagsText) { MaxDepth = 48, FloatParseHandling = FloatParseHandling.Decimal, DateParseHandling = DateParseHandling.None };
            var data = JObject.Load(flagsReader, new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error });
            if (flagsReader.Read()) throw new InvalidDataException("Official event flags contain trailing data.");
            selected["Tmp"] = data.ToString(Formatting.None);
        }
        else throw new InvalidDataException("Official world state has no valid event flags.");
        return selected;
    }

    public static void Store(JObject state, JObject world, long fetchedAt)
    {
        var snapshot = state.Obj("officialEvents");
        snapshot["lastAttempt"] = fetchedAt;
        if (snapshot.Value<long?>("sourceTime") > world.Value<long>("Time") * 1000) return;
        snapshot["source"] = Source;
        snapshot["fetchedAt"] = fetchedAt;
        snapshot["sourceTime"] = world.Value<long>("Time") * 1000;
        snapshot["buildLabel"] = world["BuildLabel"]!.DeepClone();
        snapshot["sha256"] = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(world.ToString(Formatting.None))));
        OfficialEventCompatibility.Observe(snapshot, world);
        snapshot["world"] = world.DeepClone();
        snapshot.Remove("lastError");
        snapshot["lastAttempt"] = fetchedAt;
    }

    public static JObject Status(JObject state, long now, bool enabled, int intervalSeconds)
    {
        var snapshot = state["officialEvents"] as JObject ?? new();
        var fetched = snapshot.Value<long?>("fetchedAt");
        var world = snapshot["world"] as JObject;
        return new JObject {
            ["enabled"] = enabled, ["source"] = Source, ["intervalSeconds"] = intervalSeconds,
            ["hasSnapshot"] = world is not null, ["fetchedAt"] = fetched,
            ["sourceTime"] = snapshot["sourceTime"]?.DeepClone(), ["buildLabel"] = snapshot["buildLabel"]?.DeepClone(),
            ["stale"] = fetched is null || now - fetched > Math.Max(180, intervalSeconds * 3L) * 1000,
            ["lastError"] = snapshot["lastError"]?.DeepClone(), ["sha256"] = snapshot["sha256"]?.DeepClone(),
            ["goals"] = new JArray((world?["Goals"] as JArray ?? []).OfType<JObject>().Where(x => NotExpired(x, now)).Select(x => x.DeepClone())),
            ["counts"] = new JObject(Fields.Select(field => new JProperty(field, (world?[field] as JArray ?? []).OfType<JObject>().Count(x => NotExpired(x, now))))) };
    }

    public static void Apply(JObject world, JObject state, long now, long build, bool enabledByDefault = true)
    {
        if (!Enabled(state, enabledByDefault) || state["officialEvents"]?["world"] is not JObject source) return;
        var snapshot = (JObject)state["officialEvents"]!;
        foreach (var field in Fields)
        {
            var official = new JArray((source[field] as JArray ?? []).OfType<JObject>().Where(x => NotExpired(x, now) && OfficialEventCompatibility.Supports(snapshot, field, x, build)).Select(x => x.DeepClone()));
            if (world[field] is JArray local)
            {
                var tags = official.OfType<JObject>().Select(x => x.Value<string>("Tag")).Where(x => !string.IsNullOrEmpty(x)).ToHashSet(StringComparer.Ordinal);
                foreach (var extra in local.OfType<JObject>().Where(x => NotExpired(x, now)))
                {
                    var id = Identity(extra);
                    if (id.Length > 0 && !tags.Contains(extra.Value<string>("Tag")) && !official.OfType<JObject>().Any(x => Identity(x) == id)) official.Add(extra.DeepClone());
                }
            }
            world[field] = official;
        }
        var officialFlags = JObject.Parse(source.Value<string>("Tmp")!);
        if (!OfficialEventCompatibility.Supports(snapshot, "Tmp", officialFlags, build)) return;
        var localFlags = JObject.Parse(world.Value<string>("Tmp") ?? "{}");
        // These derived schedules are consumed by the local weekly reward APIs.
        foreach (var key in new[] { "lqo", "hqo", "edg" }) if (localFlags[key] is JToken value) officialFlags[key] = value.DeepClone();
        world["Tmp"] = officialFlags.ToString(Formatting.None);
    }

    private static string Identity(JObject item) => Wire.Id(item["_id"]) is { Length: > 0 } id ? id : item.Value<string>("Node") ?? item.Value<string>("TypeName") ?? "";
    private static bool NotExpired(JObject item, long now)
    {
        foreach (var key in new[] { "Expiry", "ExpiryDate", "EndDate" })
            if (item[key] is JToken expiry && Wire.DateMs(expiry) is > 0 and var milliseconds && milliseconds <= now) return false;
        return true;
    }
}