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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

/// <summary>A CDN hotfix version is not an event's minimum client version.</summary>
public static class OfficialEventCompatibility
{
    private static readonly Lazy<JObject> Baseline = new(() => (JObject)Assets.Json("world/officialEventCompatibility.json"));
    // These nodes, mission types, levels and enemy specs were already in the
    // versioned 2016 solar map. Do not infer resource support from a new alert ID.
    private static readonly Lazy<JObject> AlertMap = new(() => (JObject)Assets.Json("fixed_responses/data/OriginSolarMapRedux/2016.11.11.17.46.json"));
    private static readonly Lazy<HashSet<string>> AlertResources = new(() => AlertMap.Value.Properties().SelectMany(p => p.Value is JObject row
        ? new[] { row.Value<string>("levelOverride"), row.Value<string>("enemySpec") } : []).OfType<string>().ToHashSet(StringComparer.Ordinal));
    private static readonly Lazy<HashSet<string>> AlertMissionTypes = new(() => AlertMap.Value.Properties().Select(p => p.Value.Value<string>("missionType")).OfType<string>().ToHashSet(StringComparer.Ordinal));
    private static readonly HashSet<string> Volatile = new(StringComparer.OrdinalIgnoreCase)
        { "_id", "id", "Activation", "Expiry", "ExpiryDate", "EndDate", "StartDate", "Date", "Timestamp", "LastUpdate" };
    public static string Fingerprint(string field, JToken entry)
    {
        JToken Normalize(JToken value) => value switch
        {
            JObject obj => new JObject(obj.Properties().Where(p => !Volatile.Contains(p.Name)).OrderBy(p => p.Name, StringComparer.Ordinal).Select(p => new JProperty(p.Name, Normalize(p.Value)))),
            JArray array => new JArray(array.Select(Normalize)),
            JValue scalar when scalar.Type is JTokenType.Integer or JTokenType.Float => new JValue("#number"),
            JValue scalar when scalar.Type == JTokenType.String && double.TryParse(scalar.Value<string>(), NumberStyles.Float, CultureInfo.InvariantCulture, out _) => new JValue("#number-string"),
            _ => value.DeepClone()
        };
        return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(field + ":" + Normalize(entry).ToString(Formatting.None))));
    }
    public static string? AlertRotationFingerprint(JToken entry)
    {
        if (entry is not JObject row || row["MissionInfo"] is not JObject) return null;
        var contract = (JObject)row.DeepClone(); var mission = (JObject)contract["MissionInfo"]!;
        foreach (var field in new[] { "missionType", "location", "levelOverride", "enemySpec", "extraEnemySpec", "maxWaveNum" }) mission.Remove(field);
        return Fingerprint("Alerts.rotation", contract);
    }
    private static long? RotatingAlertMinimum(JToken entry)
    {
        var key = AlertRotationFingerprint(entry);
        if (key is null || Baseline.Value["rotatingAlerts"]?[key] is not JValue { Type: JTokenType.Integer } version) return null;
        var mission = (JObject)entry["MissionInfo"]!;
        if (mission["location"]?.Type != JTokenType.String || AlertMap.Value[mission.Value<string>("location")!] is not JObject ||
            mission["missionType"]?.Type != JTokenType.String || !AlertMissionTypes.Value.Contains(mission.Value<string>("missionType")!)) return null;
        foreach (var field in new[] { "levelOverride", "enemySpec", "extraEnemySpec" })
        {
            if (mission[field] is null) continue;
            if (mission[field]!.Type != JTokenType.String) return null;
            var path = mission.Value<string>(field)!;
            if (path.Length > 0 && !AlertResources.Value.Contains(path)) return null;
        }
        if (mission["maxWaveNum"] is JToken waves && (waves.Type != JTokenType.Integer || waves.Value<long>() is < 0 or > 100000)) return null;
        return Math.Max(version.Value<long>(), GameVersion.Parse("2016.11.11.17.46"));
    }
    public static void Observe(JObject snapshot, JObject world)
    {
        var versions = snapshot.Obj("contentBuilds"); var build = GameVersion.Parse(world.Value<string>("BuildLabel"));
        void Remember(string field, JToken value)
        {
            var key = Fingerprint(field, value);
            var prior = versions[key]?.Type == JTokenType.Integer ? versions.Value<long>(key) : long.MaxValue;
            if ((versions.ContainsKey(key) || versions.Count < 4096) && build < prior) versions[key] = build;
        }
        foreach (var field in OfficialEvents.Fields)
            foreach (var row in (world[field] as JArray ?? []).OfType<JObject>()) Remember(field, row);
        Remember("Tmp", JObject.Parse(world.Value<string>("Tmp")!));
    }
    public static long Minimum(JObject snapshot, string field, JToken entry)
    {
        var key = Fingerprint(field, entry); var minimum = GameVersion.Parse(snapshot.Value<string>("buildLabel"));
        foreach (var candidate in new[] { Baseline.Value["entries"]?[key], snapshot["contentBuilds"]?[key] })
            if (candidate?.Type == JTokenType.Integer && candidate.Value<long>() is > 0 and var build) minimum = Math.Min(minimum, build);
        if (field == "Alerts" && RotatingAlertMinimum(entry) is > 0 and var rotatingBuild) minimum = Math.Min(minimum, rotatingBuild);
        if (entry is JObject row)
            foreach (var property in new[] { "MinBuildLabel", "minBuildLabel" })
                if (row[property] is JToken explicitBuild)
                {
                    try { minimum = Math.Max(minimum, GameVersion.Parse(explicitBuild.Value<string>())); }
                    catch (ApiException) { return long.MaxValue; }
                }
        return minimum;
    }
    public static bool Supports(JObject snapshot, string field, JToken entry, long clientBuild) => clientBuild >= Minimum(snapshot, field, entry);
}