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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

public sealed class HelminthApi(TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["infestedFoundryController"];
    public const string ResourcePrefix = "/Lotus/Types/Items/InfestedFoundry/Helminth";
    public static readonly string[] Resources = ["Calx", "Biotics", "Synthetics", "Pheromones", "Bile", "Oxides"];
    private static readonly string[] Colors = ["RED", "YELLOW", "BLUE", "GREEN", "ORANGE", "PURPLE"];
    public static string Shard(string color)
    {
        var basic = color.Replace("_MYTHIC", "", StringComparison.Ordinal); var index = Array.IndexOf(Colors, basic.StartsWith("ACC_", StringComparison.Ordinal) ? basic[4..] : ""); if (index < 0) throw new ApiException(400, "Unknown archon crystal color");
        return "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystal" + new[] { "Amar", "Nira", "Boreal", "Green", "Orange", "Violet" }[index] + (color.EndsWith("_MYTHIC", StringComparison.Ordinal) ? "Mythic" : "");
    }
    public static JObject Client(JObject inv)
    {
        var result = (JObject)inv.Obj("InfestedFoundry").DeepClone(); if (inv.Value<bool>("infiniteHelminthMaterials")) result["Resources"] = new JArray(Resources.Select(x => new JObject { ["ItemType"] = ResourcePrefix + x, ["Count"] = 1000 })); return result;
    }
    public static void Spend(JObject inv, string type, long count)
    {
        if (!Resources.Any(x => type == ResourcePrefix + x) || count is < 0 or > 1000) throw new ApiException(400, "Invalid Helminth resource cost"); if (inv.Value<bool>("infiniteHelminthMaterials")) return;
        var owned = inv.Obj("InfestedFoundry").Array("Resources").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type); if ((owned?.Value<long>("Count") ?? 0) < count) throw new ApiException(400, "Insufficient Helminth resources"); if (owned is not null) owned["Count"] = owned.Value<long>("Count") - count;
    }
    public static JArray AddXp(JObject inv, double gain)
    {
        if (!double.IsFinite(gain) || gain < 0 || gain > 999999999) throw new ApiException(400, "Invalid Helminth experience"); var foundry = inv.Obj("InfestedFoundry"); var before = foundry.Value<double>("XP"); var after = Math.Min(999999999, before + gain); foundry["XP"] = after; var recipes = new JArray();
        foreach (var (threshold, slots) in new[] { (225000, 3), (1575000, 10), (3937500, 20) }) if (before < threshold && after >= threshold) foundry["Slots"] = foundry.Value<int>("Slots") + slots;
        if (before < 7312500 && after >= 7312500) foundry["Slots"] = 1;
        foreach (var (threshold, name) in new[] { (562500, "Shields"), (1012500, "Hack"), (2250000, "AmmoEfficiency"), (3037500, "Stun"), (6075000, "Status"), (8662500, "ShieldArmor"), (10125000, "ProcBlock"), (11700000, "EnergyShare"), (13387500, "MaxStatus"), (15187500, "Treasure") })
            if (before < threshold && after >= threshold) { var type = "/Lotus/Types/Recipes/AbilityOverrides/Helminth" + name + "Blueprint"; Inventory.AddCount(inv, "Recipes", type, 1); recipes.Add(new JObject { ["ItemType"] = type, ["ItemCount"] = 1 }); }
        return recipes;
    }
    public static JArray CompleteSubsume(JObject inv)
    {
        var foundry = inv.Obj("InfestedFoundry"); if (foundry["LastConsumedSuit"] is not JObject suit) throw new ApiException(409, "No warframe is being subsumed"); var recipes = new JArray();
        foreach (var recipe in GameData.Table("Recipes").Properties().Where(x => x.Value.Value<string>("secretIngredientAction") == "SIA_WARFRAME_ABILITY" && x.Value["secretIngredients"]?.FirstOrDefault()?.Value<string>("ItemType") == suit.Value<string>("ItemType")))
        { if (inv.Array("Recipes").Any(x => x.Value<string>("ItemType") == recipe.Name && x.Value<int>("ItemCount") > 0)) continue; Inventory.AddCount(inv, "Recipes", recipe.Name, 1); recipes.Add(new JObject { ["ItemType"] = recipe.Name, ["ItemCount"] = 1 }); }
        foundry.Remove("LastConsumedSuit"); foundry.Remove("AbilityOverrideUnlockCooldown"); return recipes;
    }
    public static void Refresh(JObject inv, long now)
    {
        if (inv["InfestedFoundry"] is JObject f && f["LastConsumedSuit"] is JObject && f["AbilityOverrideUnlockCooldown"] is JToken end && Wire.DateMs(end) <= now) CompleteSubsume(inv);
        foreach (var suit in inv.Array("Suits").OfType<JObject>().Where(x => x["UpgradesExpiry"] is JToken date && Wire.DateMs(date) <= now)) foreach (var key in new[] { "OffensiveUpgrade", "DefensiveUpgrade", "UpgradesExpiry" }) suit.Remove(key);
    }
    public ApiResponse Handle(JObject account, ApiRequest request)
    {
        var inv = account.Obj("Inventory"); var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); Refresh(inv, now); var body = request.ObjectBody(); var foundry = inv.Obj("InfestedFoundry"); var changes = new JObject(); var response = new JObject { ["InventoryChanges"] = changes };
        switch (request.Q("mode"))
        {
            case "n": foundry["Name"] = body.RequiredString("newName", 64); break;
            case "s":
            {
                var suit = Inventory.Equipment(inv, "Suits", Wire.Id(body["SuitId"])); var slot = (int)body.Integer("Slot", 0, 4); var color = body.RequiredString("Color"); var type = Shard(color); var crystals = suit.Array("ArchonCrystalUpgrades"); var upgrade = body.RequiredString("UpgradeType");
                if (!upgrade.StartsWith("/Lotus/Upgrades/", StringComparison.Ordinal)) throw new ApiException(400, "Invalid archon upgrade"); while (crystals.Count <= slot) crystals.Add(new JObject());
                if (crystals[slot].Value<string>("Color") is { Length: > 0 }) throw new ApiException(409, "Remove the installed shard before replacing it"); Inventory.AddCount(inv, "MiscItems", type, -1); crystals[slot] = new JObject { ["Color"] = color, ["UpgradeType"] = upgrade }; Misc(changes, type, -1); break;
            }
            case "x":
            {
                var suit = Inventory.Equipment(inv, "Suits", Wire.Id(body["SuitId"])); var slot = (int)body.Integer("Slot", 0, 4); var crystals = suit.Array("ArchonCrystalUpgrades"); var color = crystals.ElementAtOrDefault(slot)?.Value<string>("Color"); if (string.IsNullOrEmpty(color)) throw new ApiException(409, "No shard is installed in this slot");
                var type = Shard(color); var oldBuild = GameVersion.For(account) < GameVersion.Of("38.6.0"); var resource = oldBuild ? "Bile" : new[] { "Oxides", "Bile", "Synthetics", "Biotics", "Pheromones", "Calx" }[Array.IndexOf(Colors, color.Replace("_MYTHIC", "", StringComparison.Ordinal)[4..])];
                Spend(inv, ResourcePrefix + resource, oldBuild || color.EndsWith("_MYTHIC", StringComparison.Ordinal) ? 300 : 150); Inventory.AddCount(inv, "MiscItems", type, 1); crystals[slot] = new JObject(); Misc(changes, type, 1); response["SuitId"] = body["SuitId"]!.DeepClone(); response["Slot"] = slot; break;
            }
            case "c": Feed(inv, body, changes, now); break;
            case "a":
            {
                if (foundry["LastConsumedSuit"] is JObject) throw new ApiException(409, "A warframe is already being subsumed"); var suit = Inventory.Equipment(inv, "Suits", Wire.Id(body["SuitId"])); var type = suit.RequiredString("ItemType"); var recipe = GameData.Find("Recipes", body.RequiredString("Recipe")) ?? throw new ApiException(400, "Unknown subsume recipe");
                if (recipe.Value<string>("secretIngredientAction") != "SIA_WARFRAME_ABILITY" || recipe["secretIngredients"]?.FirstOrDefault()?.Value<string>("ItemType") != type) throw new ApiException(400, "Recipe does not match this warframe");
                if (foundry.Array("ConsumedSuits").Any(x => x.Value<string>("s") == type)) throw new ApiException(409, "This warframe ability has already been subsumed"); if (foundry.Value<double>("XP") < 7312500 && foundry.Value<int>("Slots") <= 0) throw new ApiException(409, "No Helminth subsume slots are available");
                foreach (var ingredient in (recipe["secretIngredients"] as JArray ?? []).OfType<JObject>().Where(x => x.Value<string>("ItemType") != type)) Spend(inv, ingredient.RequiredString("ItemType"), ingredient.Integer("ItemCount", 1, 1000));
                var consumed = new JObject { ["s"] = type }; if (suit["Configs"]?.FirstOrDefault()?["pricol"] is JToken colors) consumed["c"] = colors.DeepClone(); foundry.Array("ConsumedSuits").Add(consumed); foundry["LastConsumedSuit"] = suit.DeepClone(); foundry["AbilityOverrideUnlockCooldown"] = Wire.Date(now + WorldData.Day);
                if (foundry.Value<double>("XP") < 7312500) foundry["Slots"] = foundry.Value<int>("Slots") - 1; changes["Recipes"] = AddXp(inv, 160000); changes["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = suit["ItemId"]!.DeepClone() }); suit.Remove(); Inventory.FreeSlot(inv, "Suits"); changes["SuitBin"] = new JObject { ["count"] = -1, ["platinum"] = 0, ["Slots"] = 1 }; break;
            }
            case "r":
                if (foundry["LastConsumedSuit"] is not JObject) throw new ApiException(409, "No subsume project to rush"); Inventory.Combine(changes, Inventory.ChangeCurrency(inv, "PremiumCredits", -50)); changes["Recipes"] = CompleteSubsume(inv); break;
            case "o":
            {
                var index = body.Integer("OfferingsIndex", 0, 1000000); if (index < foundry.Value<long>("InvigorationIndex")) throw new ApiException(409, "Invigoration offerings are outdated"); var types = body["SuitTypes"] as JArray ?? throw new ApiException(400, "Missing invigorations"); if (types.Count > 3 || types.Any(x => x.Type != JTokenType.String || GameData.Find("Warframes", x.ToString()) is null)) throw new ApiException(400, "Invalid invigoration offerings");
                if (body.Value<bool>("Extra")) { if (foundry.Value<int>("InvigorationsApplied") < 10) throw new ApiException(409, "Invigoration override is not earned"); foundry["InvigorationsApplied"] = 0; }
                foundry["InvigorationIndex"] = index; foundry["InvigorationSuitOfferings"] = types.DeepClone(); break;
            }
            case "u":
            {
                var suit = Inventory.Equipment(inv, "Suits", Wire.Id(body["SuitId"])); if (Wire.DateMs(suit["UpgradesExpiry"]) > now) throw new ApiException(409, "Warframe already has an active invigoration"); var types = body["ResourceTypes"] as JArray ?? throw new ApiException(400, "Missing invigoration costs"); var costs = body["ResourceCosts"] as JArray ?? throw new ApiException(400, "Missing invigoration costs");
                if (types.Count is < 1 or > 6 || costs.Count != types.Count || types.Distinct(JToken.EqualityComparer).Count() != types.Count) throw new ApiException(400, "Invalid invigoration costs");
                for (var i = 0; i < types.Count; i++) Spend(inv, types[i].ToString(), new JObject { ["Cost"] = costs[i].DeepClone() }.Integer("Cost", 1, 1000));
                foreach (var field in new[] { "OffensiveUpgrade", "DefensiveUpgrade" }) { var type = body.RequiredString(field + "Type"); if (!type.StartsWith("/Lotus/Upgrades/", StringComparison.Ordinal)) throw new ApiException(400, "Invalid invigoration upgrade"); suit[field] = type; response[field] = type; }
                suit["UpgradesExpiry"] = Wire.Date(now + WorldData.Week); response["UpgradesExpiry"] = suit["UpgradesExpiry"]!.DeepClone(); response["SuitId"] = suit["ItemId"]!.DeepClone(); changes["Recipes"] = AddXp(inv, 480000); foundry["InvigorationsApplied"] = checked(foundry.Value<int>("InvigorationsApplied") + 1); break;
            }
            case "custom_unlockall": changes["Recipes"] = AddXp(inv, Math.Max(0, 15187500 - foundry.Value<double>("XP"))); return ApiResponse.Text();
            default: throw new ApiException(400, "Unknown Helminth operation");
        }
        changes["InfestedFoundry"] = Client(inv); return ApiResponse.Json(response);
    }
    private static void Misc(JObject changes, string type, long count) => Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = count }) });
    private static double Appetite(double hours) => hours <= 0 ? 30 : hours < 18 ? -.84 * hours + 30 : hours <= 36 ? 15 : hours < 71.9 ? -.3327892 * hours + 26.94135 : 3;
    private static void Feed(JObject inv, JObject body, JObject changes, long now)
    {
        if (inv.Value<bool>("infiniteHelminthMaterials")) throw new ApiException(409, "Feeding is disabled with infinite Helminth materials"); var contributions = body["ResourceContributions"] as JArray ?? throw new ApiException(400, "Missing food contributions"); if (contributions.Count is < 1 or > 1000 || contributions.Any(x => x is not JObject)) throw new ApiException(400, "Invalid food contributions");
        var foundry = inv.Obj("InfestedFoundry"); var seconds = now / 1000; double points = 0;
        foreach (var contribution in contributions.OfType<JObject>())
        {
            var type = contribution.RequiredString("ItemType"); var snack = GameData.Find("Resources", type)?["helminthSnack"] as JObject ?? throw new ApiException(400, "Resource cannot be fed to Helminth"); var count = snack.Integer("count", 1); Inventory.AddCount(inv, "MiscItems", type, -count); Misc(changes, type, -count); var resourceType = snack.RequiredString("type");
            if (resourceType == ResourcePrefix + "AppetiteCooldownReducer")
            {
                var mostDisliked = foundry.Array("Resources").OfType<JObject>().SelectMany(x => x.Array("RecentlyConvertedResources").OfType<JObject>()).OrderByDescending(x => x.Value<long>("Date")).FirstOrDefault(); if (mostDisliked is not null) mostDisliked["Date"] = Math.Min(mostDisliked.Value<long>("Date"), seconds + 86400); continue;
            }
            if (!Resources.Any(x => resourceType == ResourcePrefix + x)) throw new ApiException(400, "Unknown Helminth nutrient"); var nutrient = foundry.Array("Resources").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == resourceType);
            if (nutrient is null) { nutrient = new JObject { ["ItemType"] = resourceType, ["Count"] = 0 }; foundry.Array("Resources").Add(nutrient); }
            if (nutrient.Value<int>("Count") >= 1000) throw new ApiException(409, "This Helminth nutrient is already full"); var record = nutrient.Array("RecentlyConvertedResources").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type);
            if (record is null) { record = new JObject { ["ItemType"] = type, ["Date"] = 0 }; nutrient.Array("RecentlyConvertedResources").Add(record); }
            var hours = (record.Value<long>("Date") - seconds) / 3600d; var gain = Math.Min(1000 - nutrient.Value<int>("Count"), (int)(snack.Value<double>("gain") * 1000 * Appetite(hours) / 30)); nutrient["Count"] = nutrient.Value<int>("Count") + gain; points += gain / 10d; record["Date"] = seconds + (hours >= 18 ? 72 : 24) * 3600;
        }
        changes["Recipes"] = AddXp(inv, 666 * points);
    }
    public static JObject Override(JObject inv, JObject suit, JObject operation)
    {
        var requirement = operation.Value<string>("UpgradeRequirement") ?? ""; var remap = operation["PolarityRemap"] as JArray ?? throw new ApiException(400, "Missing ability configurations"); if (remap.Count == 0 || remap.Any(x => x is not JObject)) throw new ApiException(400, "No valid ability configuration was selected"); JObject? ability = null; long consumed = 0;
        if (remap.OfType<JObject>().Any(x => suit.Array("Configs").ElementAtOrDefault((int)x.Integer("Slot", 0, 7))?[ExperimentalAbilities.Field] is JObject))
            throw new ApiException(409, "此配置使用多技能实验方案,请在桌面端编辑或切换回单技能模式后使用 Helminth。");
        if (requirement.Length > 0)
        {
            var entry = GameData.Table("Recipes").Properties().FirstOrDefault(x => x.Value.Value<string>("resultType") is string result && (result == requirement || result.EndsWith('/' + requirement.Split('/').Last(), StringComparison.Ordinal)) && x.Name.Contains("/AbilityOverrides/", StringComparison.Ordinal)) ?? throw new ApiException(400, "Unknown ability override recipe");
            if (!inv.Array("Recipes").Any(x => x.Value<string>("ItemType") == entry.Name && x.Value<long>("ItemCount") > 0)) throw new ApiException(403, "Ability override has not been unlocked");
            ability = new JObject { ["Ability"] = entry.Value["resultType"]!.DeepClone(), ["Index"] = operation.Integer("PolarizeSlot", 0, 3) };
            if (remap.OfType<JObject>().All(x => JToken.DeepEquals(suit.Array("Configs").ElementAtOrDefault((int)x.Integer("Slot", 0, 7))?["AbilityOverride"], ability))) throw new ApiException(409, "This ability override is already installed");
            foreach (var ingredient in ((JArray)entry.Value["ingredients"]!).OfType<JObject>()) { var cost = ingredient.Integer("ItemCount", 1, 1000); Spend(inv, ingredient.RequiredString("ItemType"), cost); consumed += cost; }
        }
        var configs = suit.Array("Configs"); foreach (var value in remap.OfType<JObject>()) { var slot = (int)value.Integer("Slot", 0, 7); while (configs.Count <= slot) configs.Add(new JObject()); var config = (JObject)configs[slot]; if (ability is null) config.Remove("AbilityOverride"); else config["AbilityOverride"] = ability.DeepClone(); }
        var recipes = AddXp(inv, consumed / 10d * 8); return new JObject { ["Recipes"] = recipes, ["InfestedFoundry"] = Client(inv) };
    }
}