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 FoundryApi(ItemCatalog catalog, TimeProvider clock)
{
    public ApiResponse Handle(string controller, JObject account, ApiRequest request)
    {
        var inv = account.Obj("Inventory"); var body = request.ObjectBody(); if (controller == "startRecipeController") return Start(account, request, body);
        var requested = body["RecipeIds"] as JArray ?? body["recipeNames"] as JArray ?? (request.Q("recipeName") is string recipeName ? new JArray(recipeName) : throw new ApiException(400, "Missing RecipeIds")); if (requested.Count is < 1 or > 100) throw new ApiException(400, "Invalid recipe selection");
        var delta = new JObject(); var response = new JObject { ["InventoryChanges"] = delta }; var cancel = request.Q("cancel") is not null; var now = clock.GetUtcNow().ToUnixTimeMilliseconds();
        foreach (var target in requested)
        {
            var pending = inv.Array("PendingRecipes").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(target) || x.Value<string>("ItemType") == Wire.Id(target)) ?? throw new ApiException(404, "Pending recipe not found"); var name = pending.RequiredString("ItemType"); var recipe = catalog.Get(name).Meta; var action = recipe.Value<string>("secretIngredientAction");
            if (cancel)
            {
                if (pending.Value<bool>("NemesisReward")) throw new ApiException(400, "Claim the completed nemesis reward instead");
                if (action == "SIA_CREATE_KUBROW") { var pet = Inventory.Equipment(inv, "KubrowPets", Wire.Id(pending["KubrowPet"])); pet.Remove(); Inventory.FreeSlot(inv, "KubrowPets"); delta.Array("RemovedIdItems").Add(new JObject { ["ItemId"] = pending["KubrowPet"]!.DeepClone() }); }
                if (action == "SIA_DISTILL_PRINT") { var details = Inventory.Equipment(inv, "KubrowPets", Wire.Id(pending["KubrowPet"])).Obj("Details"); details["PrintsRemaining"] = details.Value<int>("PrintsRemaining") + 1; }
                Refund(inv, recipe, pending, delta); ClearPendingSpectre(inv, recipe); pending.Remove(); continue;
            }
            if (Wire.DateMs(pending["CompletionDate"]) > now)
            {
                if (request.Q("rush") is null && !request.Path.EndsWith("/instantCompleteRecipe.php", StringComparison.Ordinal)) throw new ApiException(409, "Recipe is not yet completed");
                if (!inv.Value<bool>("dontSubtractRushPlatinumCost"))
                {
                    var progress = Math.Clamp(1 - (Wire.DateMs(pending["CompletionDate"]) - now) / (Math.Max(1, recipe.Value<double>("buildTime")) * 1000), 0, 1); var scale = GameVersion.For(account) >= 201512030000L && progress > .5 ? 1.5 - progress : 1;
                    Inventory.Combine(delta, Inventory.ChangeCurrency(inv, "PremiumCredits", -(long)Math.Floor(recipe.Value<long>("skipBuildTimePrice") * scale + .5)));
                }
            }
            if (recipe.Value<bool>("consumeOnUse")) Inventory.AddCount(inv, "Recipes", pending.Value<string>("OwnedRecipeType") ?? OwnedRecipe(name), -1);
            if (action == "SIA_SPECTRE_LOADOUT_COPY")
            {
                var loadout = inv.Array("PendingSpectreLoadouts").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == recipe.Value<string>("resultType")); if (loadout is not null) { Inventory.Upsert(inv.Array("SpectreLoadouts"), "ItemType", loadout); loadout.Remove(); }
            }
            if (action == "SIA_UNBRAND")
            {
                var branded = inv.Array("BrandedSuits").FirstOrDefault(x => Wire.Id(x) == Wire.Id(pending["SuitToUnbrand"])) ?? throw new ApiException(409, "Warframe is no longer branded"); branded.Remove(); response.Array("BrandedSuits").Add(pending["SuitToUnbrand"]!.DeepClone());
            }
            else if (action == "SIA_CREATE_KUBROW")
            {
                var pet = Inventory.Equipment(inv, "KubrowPets", Wire.Id(pending["KubrowPet"])); pet.Obj("Details")["Status"] = "STATUS_INCUBATED"; pet.Obj("Details")["HatchDate"] = Wire.Date(now);
                if (pending.Value<bool>("DeferredPetDefaults")) PetDefaults(account, pet, delta); delta.Array("KubrowPets").Add(pet.DeepClone());
            }
            else if (action == "SIA_DISTILL_PRINT") Inventory.Combine(delta, PetFactory.Print(inv, pending["PetPrintDetails"] as JObject ?? Inventory.Equipment(inv, "KubrowPets", Wire.Id(pending["KubrowPet"])).Obj("Details")));
            else
            {
                var type = recipe.RequiredString("resultType");
                if (type == "/Lotus/Powersuits/Excalibur/ExcaliburUmbra") Inventory.Combine(delta, Umbra(account));
                else Inventory.Combine(delta, new ItemAcquisition(catalog, clock, account).Add(inv, type == "/Lotus/Types/JadeShadowsPart2Mission/Gameplay/Resources/HunhowTrinketMiscItem" ? "/Lotus/Weapons/Tenno/Melee/Swords/PrimeWar/PrimeWarWeapon" : type, recipe.Value<int?>("num") ?? 1, premium: type == "/Lotus/Types/JadeShadowsPart2Mission/Gameplay/Resources/HunhowTrinketMiscItem", targetFingerprint: pending.Value<string>("TargetFingerprint")));
            }
            if (inv.Value<bool>("claimingBlueprintRefundsIngredients") && action != "SIA_CREATE_KUBROW") Refund(inv, recipe, pending, delta); pending.Remove();
        }
        return ApiResponse.Json(cancel ? delta : response);
    }
    internal static string OwnedRecipe(string type) => WorldData.Get("pseudoRecipeToOwnedRecipeMap").Value<string>(type) ?? type;
    private ApiResponse Start(JObject account, ApiRequest request, JObject body)
    {
        var inv = account.Obj("Inventory"); var name = request.Q("recipeName") ?? body.RequiredString("RecipeName"); var (category, recipe) = catalog.Get(name); var action = recipe.Value<string>("secretIngredientAction"); if (category != "Recipes") throw new ApiException(400, "Not a recipe");
        if (action is "SIA_WARFRAME_ABILITY" or "SIA_GILD_WEAPON") throw new ApiException(400, "Use the Helminth or syndicate interface for this recipe");
        var ownedType = OwnedRecipe(name); var available = inv.Array("Recipes").FirstOrDefault(x => x.Value<string>("ItemType") == ownedType)?.Value<int>("ItemCount") ?? 0;
        if (available <= 0 && action is not ("SIA_CREATE_KUBROW" or "SIA_DISTILL_PRINT") && !recipe.Value<bool>("alwaysAvailable")) throw new ApiException(400, "Blueprint not owned");
        if (recipe.Value<bool>("consumeOnUse") && inv.Array("PendingRecipes").Count(x => (x.Value<string>("OwnedRecipeType") ?? OwnedRecipe(x.Value<string>("ItemType") ?? "")) == ownedType) >= available) throw new ApiException(409, "Blueprint is already reserved by a pending recipe");
        if (inv.Array("PendingRecipes").Any(x => x.Value<string>("ItemType") == name)) throw new ApiException(409, "Recipe is already being crafted");
        var ingredients = (recipe["ingredients"] as JArray ?? []).OfType<JObject>().ToArray(); var ids = body["Ids"] as JArray ?? []; var pending = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = name, ["OwnedRecipeType"] = ownedType, ["CompletionDate"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds() + recipe.Value<long>("buildTime") * 1000), ["PaidCredits"] = recipe.Value<long>("buildPrice"), ["ConsumedCounted"] = new JArray(), ["ConsumedEquipment"] = new JObject() };
        Inventory.ChangeCurrency(inv, "RegularCredits", -recipe.Value<long>("buildPrice"));
        for (var i = 0; i < ingredients.Length; i++)
        {
            var ingredient = ingredients[i]; var type = ingredient.RequiredString("ItemType"); var count = ingredient.Integer("ItemCount", 1, 1000000); var field = catalog.Get(type).Category; var id = Wire.Id(ids.ElementAtOrDefault(i));
            if (Inventory.EquipmentKeys.Contains(field) || field == "RawUpgrades" && id.Length == 24 && !id.StartsWith('/'))
            {
                if (count != 1) throw new ApiException(400, "Equipment ingredient requires one owned identifier"); if (field == "RawUpgrades") field = "Upgrades";
                var equipment = inv.Array(field).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == id && x.Value<string>("ItemType") == type) ?? throw new ApiException(404, "Required equipment ingredient is not owned"); Inventory.RequireNotInResearch(inv, id);
                if (equipment["AltWeaponModeId"] is JToken alternate)
                {
                    var other = field == "LongGuns" ? "Melee" : "LongGuns"; var pair = Inventory.Equipment(inv, other, Wire.Id(alternate)); pending.Obj("ConsumedEquipment").Array(other).Add(pair.DeepClone()); pair.Remove();
                }
                pending.Obj("ConsumedEquipment").Array(field).Add(equipment.DeepClone()); equipment.Remove(); Inventory.FreeSlot(inv, field);
            }
            else if (Inventory.CountedKeys.Contains(field)) { Inventory.AddCount(inv, field, type, -count); pending.Array("ConsumedCounted").Add(new JObject { ["Category"] = field, ["ItemType"] = type, ["ItemCount"] = count }); }
            else throw new ApiException(400, "Unsupported foundry ingredient category");
        }
        var changes = new JObject();
        if (action == "SIA_CREATE_KUBROW")
        {
            if (inv.Array("KubrowPets").Any(x => x["Details"]?.Value<string>("Status") is "STATUS_INCUBATING" or "STATUS_INCUBATED")) throw new ApiException(409, "Finish the existing incubation first"); var choices = (recipe["secretIngredients"] as JArray ?? []).OfType<JObject>().ToArray(); if (choices.Length == 0) throw new ApiException(400, "No pet breeds in recipe"); var type = choices[Random.Shared.Next(choices.Length)].RequiredString("ItemType");
            var infected = ids.Count > ingredients.Length && ids.Last is JToken last ? inv.Array("Suits").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(last)) : null;
            if (infected is not null)
            {
                if (!name.Contains("/KubrowPet/", StringComparison.Ordinal) || Wire.DateMs(infected["InfestationDate"]) <= 0) throw new ApiException(400, "Warframe has no cyst to incubate"); type = "/Lotus/Types/Game/KubrowPet/ChargerKubrowPetPowerSuit"; pending["CystSuit"] = infected["ItemId"]!.DeepClone(); pending["CystDate"] = infected["InfestationDate"]!.DeepClone(); infected["InfestationDate"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds());
            }
            Inventory.Combine(changes, Inventory.OccupySlots(inv, "KubrowPets", 1, false)); var acquired = Inventory.AddItem(inv, "KubrowPets", type, 1); var pet = Inventory.Equipment(inv, "KubrowPets", Wire.Id(acquired["KubrowPets"]![0]!["ItemId"])); pet["Details"] = PetFactory.Details(inv, type, false, clock.GetUtcNow(), GameVersion.For(account)); pet.Obj("Details")["HatchDate"] = pending["CompletionDate"]!.DeepClone(); pending["KubrowPet"] = pet["ItemId"]!.DeepClone(); pending["DeferredPetDefaults"] = true; changes["KubrowPets"] = new JArray(pet.DeepClone());
        }
        if (action == "SIA_DISTILL_PRINT")
        {
            var pet = Inventory.Equipment(inv, "KubrowPets", Wire.Id(ids.ElementAtOrDefault(ingredients.Length))); var details = pet.Obj("Details"); if (details.Value<int>("PrintsRemaining") <= 0 || details.Value<string>("Status") is "STATUS_INCUBATING" or "STATUS_INCUBATED") throw new ApiException(409, "Pet has no imprint available"); details["PrintsRemaining"] = details.Value<int>("PrintsRemaining") - 1; pending["KubrowPet"] = pet["ItemId"]!.DeepClone(); pending["PetPrintDetails"] = details.DeepClone();
        }
        if (action == "SIA_SPECTRE_LOADOUT_COPY")
        {
            var loadout = new JObject { ["ItemType"] = recipe["resultType"]!.DeepClone() }; var preserve = false;
            foreach (var (secret, i) in (recipe["secretIngredients"] as JArray ?? []).Select((x, i) => (x, i)))
            {
                var id = Wire.Id(ids.ElementAtOrDefault(ingredients.Length + i)); if (id == new string('f', 24)) { preserve = true; break; }
                var field = secret.Value<string>("ItemType") switch { "/Lotus/Types/Game/PowerSuits/PlayerPowerSuit" => "Suits", "/Lotus/Weapons/Tenno/Pistol/LotusPistol" => "Pistols", "/Lotus/Weapons/Tenno/LotusLongGun" => "LongGuns", _ => "Melee" }; var gear = Inventory.Equipment(inv, field, id); loadout[field] = gear["ItemType"]!.DeepClone(); if (gear["ModularParts"] is JToken parts) loadout[field + "ModularParts"] = parts.DeepClone();
            }
            if (!preserve) Inventory.Upsert(inv.Array("PendingSpectreLoadouts"), "ItemType", loadout);
        }
        if (action == "SIA_UNBRAND") { var suitId = Wire.Id(ids.ElementAtOrDefault(ingredients.Length)); Inventory.Equipment(inv, "Suits", suitId); if (!inv.Array("BrandedSuits").Any(x => Wire.Id(x) == suitId)) throw new ApiException(400, "Selected warframe has no Grustrag bolt"); pending["SuitToUnbrand"] = Wire.Oid(suitId); }
        inv.Array("PendingRecipes").Add(pending); var response = new JObject { ["RecipeId"] = pending["ItemId"]!.DeepClone() }; if (changes.Count > 0) response["InventoryChanges"] = changes; return ApiResponse.Json(response);
    }
    private void Refund(JObject inv, JObject recipe, JObject pending, JObject delta)
    {
        Inventory.Combine(delta, Inventory.ChangeCurrency(inv, "RegularCredits", pending.Value<long?>("PaidCredits") ?? recipe.Value<long>("buildPrice"))); var refundedTypes = new HashSet<string>(); var pairs = new HashSet<string>();
        var stored = pending["ConsumedEquipment"] as JObject ?? new JObject(new[] { "LongGuns", "Pistols", "Melee" }.Where(x => pending[x] is JArray).Select(x => new JProperty(x, pending[x]!.DeepClone())));
        foreach (var category in stored.Properties()) foreach (var gear in ((JArray)category.Value).OfType<JObject>())
        {
            var id = Wire.Id(gear["ItemId"]); if (inv.Array(category.Name).Any(x => Wire.Id(x["ItemId"]) == id)) throw new ApiException(409, "Refunded equipment identifier already exists"); var pair = gear["AltWeaponModeId"] is null ? id : string.Join(':', new[] { id, Wire.Id(gear["AltWeaponModeId"]) }.Order(StringComparer.Ordinal)); if (pairs.Add(pair)) Inventory.Combine(delta, Inventory.OccupySlots(inv, category.Name, 1, false)); inv.Array(category.Name).Add(gear.DeepClone()); delta.Array(category.Name).Add(gear.DeepClone()); refundedTypes.Add(gear.RequiredString("ItemType"));
        }
        if (pending["ConsumedCounted"] is JArray consumed) foreach (var item in consumed.OfType<JObject>()) { var field = item.RequiredString("Category"); var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1); Inventory.AddCount(inv, field, type, count); Inventory.Combine(delta, new JObject { [field] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = count }) }); }
        else foreach (var ingredient in (recipe["ingredients"] as JArray ?? []).OfType<JObject>().Where(x => !refundedTypes.Contains(x.RequiredString("ItemType")))) Inventory.Combine(delta, Inventory.AddItem(inv, catalog.Get(ingredient.RequiredString("ItemType")).Category, ingredient.RequiredString("ItemType"), (int)ingredient.Integer("ItemCount", 1, 100000)));
        if (pending["CystSuit"] is JToken cyst && inv.Array("Suits").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(cyst)) is JObject suit) suit["InfestationDate"] = pending["CystDate"]!.DeepClone();
    }
    private static void ClearPendingSpectre(JObject inv, JObject recipe) { foreach (var entry in inv.Array("PendingSpectreLoadouts").Where(x => x.Value<string>("ItemType") == recipe.Value<string>("resultType")).ToArray()) entry.Remove(); }
    private void PetDefaults(JObject account, JObject pet, JObject changes)
    {
        var inv = account.Obj("Inventory"); var meta = GameData.Find("Sentinels", pet.Value<string>("ItemType")); var acquire = new ItemAcquisition(catalog, clock, account); var mods = new JArray();
        foreach (var item in (meta?["defaultUpgrades"] as JArray ?? []).OfType<JObject>()) { var type = item.RequiredString("ItemType"); Inventory.Combine(changes, acquire.Add(inv, type)); var slot = item.Value<int>("Slot"); if (slot >= 0) { if (slot > 63) throw new ApiException(400, "Invalid default pet mod slot"); while (mods.Count <= slot) mods.Add(""); mods[slot] = type; } }
        if (mods.Count > 0) pet["Configs"] = new JArray(new JObject { ["Upgrades"] = mods }); foreach (var extra in meta?["exalted"] as JArray ?? []) Inventory.Combine(changes, acquire.Add(inv, extra.ToString(), withSlots: false));
    }
    private JObject Umbra(JObject account)
    {
        var inv = account.Obj("Inventory"); var delta = new JObject(); var acquired = new ItemAcquisition(catalog, clock, account); var modIds = new List<string>();
        foreach (var type in new[] { "/Lotus/Upgrades/Mods/Sets/Umbra/WarframeUmbraModA", "/Lotus/Upgrades/Mods/Sets/Umbra/WarframeUmbraModB", "/Lotus/Upgrades/Mods/Sets/Umbra/WarframeUmbraModC", "/Lotus/Upgrades/Mods/Sets/Sacrifice/MeleeSacrificeModA", "/Lotus/Upgrades/Mods/Sets/Sacrifice/MeleeSacrificeModB" })
        { var id = Wire.NewId(); var mod = new JObject { ["ItemId"] = Wire.Oid(id), ["ItemType"] = type, ["UpgradeFingerprint"] = "{\"lvl\":5}" }; inv.Array("Upgrades").Add(mod); delta.Array("Upgrades").Add(mod.DeepClone()); modIds.Add(id); }
        foreach (var (type, field, xp, mods) in new[] { ("/Lotus/Powersuits/Excalibur/ExcaliburUmbra", "Suits", 900000, modIds.Take(3).ToArray()), ("/Lotus/Weapons/Tenno/Melee/Swords/UmbraKatana/UmbraKatana", "Melee", 450000, modIds.Skip(3).ToArray()) })
        {
            var change = acquired.Add(inv, type, premium: true); var gear = Inventory.Equipment(inv, field, Wire.Id(change[field]![0]!["ItemId"])); gear["XP"] = xp; gear["Features"] = 1; gear["Configs"] = new JArray(new JObject { ["Upgrades"] = new JArray(Enumerable.Repeat("", 8 - mods.Length).Concat(mods)) }); change[field] = new JArray(gear.DeepClone()); Inventory.Combine(delta, change);
            var previous = inv.Array("XPInfo").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type); if (previous is null) inv.Array("XPInfo").Add(new JObject { ["ItemType"] = type, ["XP"] = xp }); else previous["XP"] = Math.Max(previous.Value<int>("XP"), xp);
        }
        return delta;
    }
}