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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

public sealed class PublicExportApi(ItemCatalog catalog)
{
    public static readonly string[] Kinds = ["Customs", "Drones", "Flavour", "FusionBundles", "Keys", "Gear", "Recipes", "Regions", "RelicArcane", "Resources", "Sentinels", "SortieRewards", "Upgrades", "Warframes", "Weapons"];
    private static readonly ConcurrentDictionary<string, Lazy<JToken>> Data = new(StringComparer.Ordinal);
    public static readonly HashSet<string> Languages = ["de", "en", "es", "fr", "it", "ja", "ko", "pl", "pt", "ru", "tc", "th", "tr", "uk", "zh"];
    private static JToken Read(string file) => Data.GetOrAdd(file, x => new(() => Assets.Json(x))).Value;
    private static JObject D(string name) => (JObject)Read($"export/Export{name}.json");
    public ApiResponse Handle(ApiRequest request)
    {
        var path = request.Path;
        if (path.StartsWith("/PublicExport/Lotus/Interface/", StringComparison.Ordinal)) throw new ApiException(404, "Optional game texture is not installed");
        var index = Regex.Match(path, @"^/PublicExport/index_([a-z]{2})\.txt\.lzma$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
        if (index.Success)
        {
            var lang = index.Groups[1].Value;
            if (!Languages.Contains(lang)) throw new ApiException(404, "Index language not found");
            return ApiResponse.Binary(Assets.Binary($"fixed_responses/PublicExport/index_{lang}.txt.lzma"));
        }
        if (path.StartsWith("/PublicExport/Manifest/ExportManifest.json!", StringComparison.Ordinal)) return ApiResponse.Json(Manifest());
        var match = Regex.Match(path, @"^/PublicExport/Manifest/Export(\w+)_([a-z]{2})\.json!.+$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
        if (!match.Success || !Kinds.Contains(match.Groups[1].Value)) throw new ApiException(404, "Unknown PublicExport document");
        return ApiResponse.Json(Create(match.Groups[1].Value, match.Groups[2].Value));
    }
    public JObject Create(string kind, string lang)
    {
        var dict = (JObject)Read($"export/dict.{(Languages.Contains(lang) ? lang : "en")}.json");
        string L(JToken? token) => token is null ? "" : dict.Value<string>(token.ToString()) ?? token.ToString();
        JObject Local(JObject obj, params string[] fields)
        {
            var copy = (JObject)obj.DeepClone();
            foreach (var field in fields) if (copy[field] is not null) copy[field] = L(copy[field]);
            return copy;
        }
        JArray Map(string file, Func<JObject, JObject>? transform = null, Func<JObject, bool>? filter = null) => new(D(file).Properties().Where(p => p.Value is JObject obj && (filter is null || filter(obj))).Select(p =>
        {
            var obj = (JObject)p.Value.DeepClone(); obj["uniqueName"] = p.Name; return transform is null ? obj : transform(obj);
        }));
        JObject Selected(JObject obj, string fields) => new(obj.Properties().Where(x => fields.Split(' ').Contains(x.Name)).Select(x => new JProperty(x.Name, x.Value.DeepClone())));
        bool Has(JObject obj, string fields) => fields.Split(' ').All(x => obj[x] is not null);
        string Fill(string description, JToken values)
        {
            foreach (var p in ((JObject)values).Properties()) description = description.Replace($"|{p.Name}|", p.Value.ToString(), StringComparison.Ordinal);
            return description;
        }
        var result = new JObject();
        switch (kind)
        {
            case "Customs": case "Resources": case "Gear": case "Flavour": case "Keys":
                result["Export" + kind] = Map(kind, x =>
                {
                    var obj = Local(x, "name", "description");
                    if (kind == "Flavour") obj["codexSecret"] = obj.Value<bool?>("codexSecret") ?? false;
                    return obj;
                }, x => kind != "Keys" || x["name"] is not null && x["description"] is not null);
                break;
            case "Drones":
                result["ExportDrones"] = Map(kind, x =>
                {
                    var obj = Local(x, "name", "description");
                    obj["capacityMultiplier"] = new JArray(new[] { "COMMON", "UNCOMMON", "RARE", "LEGENDARY" }.Select(k => x["capacityMultipliers"]?[k]?.DeepClone()));
                    obj["specialities"] = new JArray(); return obj;
                }); break;
            case "FusionBundles": result["ExportFusionBundles"] = Map(kind, x => { var obj = Local(x, "description"); obj["codexSecret"] = false; return obj; }); break;
            case "Recipes":
                result["ExportRecipes"] = Map(kind, x =>
                {
                    foreach (var item in x["ingredients"]!.OfType<JObject>()) item["ProductCategory"] = catalog.Get(item.RequiredString("ItemType")).Category;
                    x["secretIngredients"] ??= new JArray(); return x;
                }); break;
            case "Regions":
                result["ExportRegions"] = Map(kind, x =>
                {
                    var obj = Local(Selected(x, "uniqueName name systemIndex systemName nodeType masteryReq minEnemyLevel maxEnemyLevel"), "name", "systemName");
                    obj["missionIndex"] = D("MissionTypes")[x.Value<string>("missionType")!]?["index"];
                    obj["factionIndex"] = D("Factions")[x.Value<string>("faction")!]?["index"]; return obj;
                }, x => x["faction"] is not null); break;
            case "RelicArcane":
                var rewards = D("Rewards"); var relicName = L("/Lotus/Language/Relics/VoidProjectionName");
                var relics = Map("Relics", x => new JObject
                {
                    ["uniqueName"] = x["uniqueName"], ["name"] = relicName.Replace("|ERA|", x.Value<string>("era"), StringComparison.Ordinal).Replace("|CATEGORY|", x.Value<string>("category"), StringComparison.Ordinal),
                    ["codexSecret"] = x["codexSecret"], ["description"] = L(x["description"]),
                    ["relicRewards"] = new JArray(rewards[x.Value<string>("rewardManifest")!]![0]!.Select(r => new JObject { ["rewardName"] = r["type"], ["rarity"] = r["rarity"], ["tier"] = 0, ["itemCount"] = r["itemCount"] }))
                });
                foreach (var arcane in Map("Arcanes", x => { var obj = Local(Selected(x, "uniqueName name codexSecret rarity"), "name"); obj["levelStats"] = new JArray(); return obj; })) relics.Add(arcane);
                result["ExportRelicArcane"] = relics; break;
            case "Sentinels":
                result["ExportSentinels"] = Map(kind, x => Local(Selected(x, "uniqueName name health shield armor stamina power codexSecret excludeFromCodex description productCategory"), "name", "description"), x => Has(x, "health shield armor stamina power")); break;
            case "SortieRewards":
                result["ExportSortieRewards"] = new JArray(D("Rewards")["/Lotus/Types/Game/MissionDecks/SortieRewards"]![0]!.Select(x => new JObject { ["rewardName"] = x["type"], ["rarity"] = "COMMON", ["tier"] = 0, ["itemCount"] = x["itemCount"], ["probability"] = x["probability"] }));
                var nightwave = D("Nightwave");
                result["ExportNightwave"] = new JObject
                {
                    ["affiliationTag"] = nightwave["affiliationTag"],
                    ["challenges"] = new JArray(((JObject)nightwave["challenges"]!).Properties().Select(p => { var obj = Local((JObject)p.Value, "name", "description"); obj["uniqueName"] = p.Name; return obj; })),
                    ["rewards"] = new JArray(nightwave["rewards"]!.OfType<JObject>().Select(x => { var obj = Local(x, "name", "description"); obj["name"] ??= ""; obj["description"] ??= ""; return obj; }))
                };
                var nodes = new[] { (553,"Flexa"), (554,"H-2 Cloud"), (555,"R-9 Cloud"), (550,"Nsu Grid"), (538,"Calabash"), (539,"Numina"), (540,"Arc Silver"), (541,"Erato"), (542,"Lu-yan"), (543,"Sabmir Cloud") };
                result["ExportRailjack"] = new JObject { ["nodes"] = new JArray(nodes.Select(x => new JObject { ["uniqueName"] = "CrewBattleNode" + x.Item1, ["name"] = x.Item2 })) };
                result["ExportIntrinsics"] = Map("Intrinsics", x => new JObject { ["name"] = x.Value<string>("uniqueName")![4..], ["ranks"] = new JArray(x["ranks"]!.OfType<JObject>().Select(r => Local(r, "name", "description"))) });
                result["ExportOther"] = Read("public-export-other.json").DeepClone(); break;
            case "Upgrades":
                result["ExportUpgrades"] = Map(kind, x => { var obj = Local(x, "name"); if (obj["description"] is not null) obj["description"] = new JArray(L(obj["description"])); return obj; });
                result["ExportModSet"] = Map("ModSet", x => new JObject { ["uniqueName"] = x["uniqueName"], ["numUpgradesInSet"] = x["numUpgradesInSet"], ["stats"] = new JArray(x["levelStats"]!.Select(s => Fill(L(x["description"]), s))) });
                result["ExportAvionics"] = Map("Avionics", x => { var obj = Local(x, "name"); obj["levelStats"] = new JArray(); return obj; });
                result["ExportFocusUpgrades"] = Map("FocusUpgrades", x => { var obj = Local(x, "name"); obj["levelStats"] = new JArray(x["levelStats"]!.Select(s => new JObject { ["stats"] = new JArray(Fill(L(x["description"]), s)) })); return obj; }); break;
            case "Warframes":
                result["ExportWarframes"] = Map(kind, x => { var obj = Local(x, "name", "description", "longDescription", "passiveDescription"); obj["abilities"] = new JArray(x["abilities"]!.Select(a => new JObject { ["abilityUniqueName"] = a["uniqueName"], ["abilityName"] = L(a["name"]), ["description"] = L(a["description"]) })); return obj; });
                result["ExportAbilities"] = Map("Abilities", x => new JObject { ["abilityUniqueName"] = x["uniqueName"], ["abilityName"] = L(x["name"]), ["description"] = L(x["description"]) }, x => Has(x, "name description")); break;
            case "Weapons":
                const string required = "damagePerShot totalDamage criticalChance criticalMultiplier procChance fireRate masteryReq";
                const string fields = "uniqueName name codexSecret damagePerShot totalDamage description criticalChance criticalMultiplier procChance fireRate masteryReq productCategory slot accuracy omegaAttenuation noise trigger magazineSize reloadTime multishot excludeFromCodex";
                result["ExportWeapons"] = Map(kind, x => Local(Selected(x, fields + " blockingAngle comboDuration followThrough range slamAttack slamRadialDamage slamRadius slideAttack heavyAttackDamage heavySlamAttack heavySlamRadialDamage heavySlamRadius windUp maxLevelCap sentinel primeOmegaAttenuation"), "name", "description"), x => Has(x, required));
                result["ExportRailjackWeapons"] = Map("RailjackWeapons", x => { var obj = Local(Selected(x, fields), "name", "description"); obj["excludeFromCodex"] = obj.Value<bool?>("excludeFromCodex") ?? false; return obj; }, x => Has(x, required + " slot accuracy noise trigger magazineSize reloadTime multishot")); break;
            default: throw new ApiException(404, "Unknown PublicExport document");
        }
        return result;
    }
    private static JObject Manifest()
    {
        var result = new JArray();
        void Add(string name, JToken meta) { if (meta.Value<string>("icon") is string icon) result.Add(new JObject { ["uniqueName"] = name, ["textureLocation"] = icon + "!00_abcdefghijklmnopqrstuv" }); }
        foreach (var file in new[] { "Abilities", "Arcanes", "Customs", "Drones", "Flavour", "FocusUpgrades", "FusionBundles", "Gear", "Intrinsics", "Keys", "ModSet", "RailjackWeapons", "Relics", "Resources", "Sentinels", "Upgrades", "Warframes", "Weapons" })
            foreach (var p in D(file).Properties()) Add(p.Name, p.Value);
        foreach (var p in ((JObject)D("Nightwave")["challenges"]!).Properties()) Add(p.Name, p.Value);
        foreach (var item in D("Nightwave")["rewards"]!) Add(item.Value<string>("uniqueName")!, item);
        return new JObject { ["Manifest"] = result };
    }
}