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;

/// <summary>Modern, catalog-backed acquisition shared by foundry, inbox and administration.</summary>
public sealed class ItemAcquisition(ItemCatalog catalog, TimeProvider? clock = null, JObject? account = null, JArray? packResults = null)
{
    public JObject Add(JObject inv, string type, int count = 1, bool premium = false, bool withSlots = true, int depth = 0, double durabilityDays = 3, ulong? seed = null, string? targetFingerprint = null)
    {
        var result = AddCore(inv, type, count, premium, withSlots, depth, durabilityDays, seed, targetFingerprint);
        type = catalog.ResolveType(type);
        if (catalog.Get(type).Meta.Value<bool>("oneTimePurchasable") && !inv.Array("OneTimePurchases").Any(x => x.ToString() == type)) { inv.Array("OneTimePurchases").Add(type); result["OneTimePurchases"] = new JArray(type); }
        return result;
    }
    private JObject AddCore(JObject inv, string type, int count, bool premium, bool withSlots, int depth, double durabilityDays, ulong? seed, string? targetFingerprint)
    {
        if (count is < 1 or > 100_000 || depth > 8) throw new ApiException(400, "Invalid acquisition quantity or recursion");
        type = catalog.ResolveType(type);
        if (targetFingerprint is not null && type.Contains("/ZanukaPetParts/", StringComparison.Ordinal) && JObject.Parse(targetFingerprint)["Parts"] is JArray houndParts)
            type = "/Lotus/Types/Friendly/Pets/ZanukaPets/ZanukaPet" + houndParts[0].ToString()[^1] + "PowerSuit";
        var (category, meta) = catalog.Get(type);
        if (type == InfestationKing.Type) return InfestationKing.Add(inv, count);
        if (type == XFEWarframe.Mods.PetFetchMod.Type) return FetchOverdrive.Add(inv, count);
        var delta = new JObject();
        if (LegacyMods.Find(type) is JObject legacy)
        {
            var result = new JArray();
            var fingerprint = new JObject { ["reqLevel"] = 0, ["fits"] = legacy["fits"]![0]!["type"]!.DeepClone(), ["upgrades"] = new JArray(new JObject { ["upgrade"] = legacy["upgrades"]![0]!["type"]!.DeepClone(), ["valueRarity"] = "COMMON", ["value"] = 1d }) };
            for (var i = 0; i < count; i++) { var item = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["UpgradeFingerprint"] = fingerprint.ToString(Newtonsoft.Json.Formatting.None) }; inv.Array("Upgrades").Add(item); result.Add(item.DeepClone()); }
            return new JObject { ["Upgrades"] = result };
        }
        if (category == "CrewShipWeapons" && meta["defaultUpgrades"] is JArray { Count: > 0 } || category == "CrewShipWeaponSkins" && (meta["subroutines"] is not null || meta["randomisedUpgrades"] is not null)) return Inventory.AddItem(inv, "CrewShipRawSalvage", type, count);
        if (category == "BoosterPacks") return BoosterPacks.Open(inv, meta, count, this, depth, packResults);
        if (category == "SlotItems")
        {
            var bin = meta.RequiredString("bin"); var quantity = checked(count * meta.Value<int>("purchaseQuantity")); var slots = inv.Obj(bin);
            slots["Slots"] = slots.Value<int>("Slots") + quantity; slots["Extra"] = slots.Value<int>("Extra") + quantity;
            return new JObject { [bin] = new JObject { ["count"] = 0, ["platinum"] = 1, ["Slots"] = quantity, ["Extra"] = quantity } };
        }
        if (category == "CreditBundles") return Inventory.ChangeCurrency(inv, "RegularCredits", checked(count * meta.Value<long>("credits")));
        if (category == "Bundles")
        {
            foreach (var component in meta.Array("components").OfType<JObject>())
                Inventory.Combine(delta, Add(inv, component.RequiredString("typeName"), checked(count * (int)component.Integer("purchaseQuantity", 1, 100_000)), premium: true, depth: depth + 1, durabilityDays: component.Value<double?>("durabilityDays") ?? 3));
            return delta;
        }
        if (category == "Boosters")
        {
            var boosterType = meta.RequiredString("typeName");
            if (!double.IsFinite(durabilityDays) || durabilityDays <= 0 || durabilityDays > 3650) throw new ApiException(400, "Invalid booster duration");
            var seconds = checked((long)(durabilityDays * 86400 * count));
            InventoryProgress.Booster(inv, boosterType, seconds, (clock ?? TimeProvider.System).GetUtcNow());
            return new JObject { ["Boosters"] = new JArray(new JObject { ["ItemType"] = boosterType, ["ExpiryDate"] = seconds }) };
        }
        if (category == "EmailItems")
        {
            if (account is null) throw new ApiException(400, "Email item needs an account context");
            if (meta["message"] is not JObject message) throw new ApiException(400, "Email item lacks a message");
            if (meta.Value<bool>("sendOnlyOnce") && inv.Array("EmailItems").Any(x => x.Value<string>("ItemType") == type)) return delta;
            InboxApi.Create(account, InboxApi.FromExport(message), (clock ?? TimeProvider.System).GetUtcNow());
            Inventory.AddCount(inv, "EmailItems", type, 1);
            delta["EmailItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = 1 });
            return delta;
        }
        if (category == "FusionBundles")
            return Inventory.ChangeCurrency(inv, "FusionPoints", checked(count * meta.Value<long>("fusionPoints")));
        if (category == "KubrowPetPrints")
        {
            var prints = new JArray();
            if (meta["DominantTraits"] is not JObject traits) throw new ApiException(400, "Missing predefined imprint genetics");
            for (var i = 0; i < count; i++)
            {
                var imprint = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["Name"] = "", ["IsMale"] = false,
                    ["Size"] = 1, ["DominantTraits"] = traits.DeepClone(), ["RecessiveTraits"] = new JObject() };
                inv.Array("KubrowPetPrints").Add(imprint); prints.Add(imprint.DeepClone());
            }
            return new JObject { ["KubrowPetPrints"] = prints };
        }
        if (category is "FlavourItems" or "WeaponSkins")
        {
            if (inv.Array(category).Any(x => x.Value<string>("ItemType") == type)) return delta;
            var item = new JObject { ["ItemType"] = type };
            if (category == "WeaponSkins") item["ItemId"] = Wire.Oid(Wire.NewId());
            inv.Array(category).Add(item);
            delta[category] = new JArray(item.DeepClone());
        }
        else if (category == "FusionTreasures")
        {
            var item = inv.Array(category).OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type && x.Value<int>("Sockets") == 0);
            if (item is null) { item = new JObject { ["ItemType"] = type, ["Sockets"] = 0, ["ItemCount"] = 0 }; inv.Array(category).Add(item); }
            item["ItemCount"] = checked(item.Value<long>("ItemCount") + count);
            delta[category] = new JArray(new JObject { ["ItemType"] = type, ["Sockets"] = 0, ["ItemCount"] = count });
        }
        else if (category == "LevelKeys" && meta["chainStages"] is JArray)
        {
            if (inv.Array("QuestKeys").Any(x => x.Value<string>("ItemType") == type)) return delta;
            var key = new JObject { ["ItemType"] = type, ["Progress"] = new JArray() };
            inv.Array("QuestKeys").Add(key); delta["QuestKeys"] = new JArray(key.DeepClone());
        }
        else if (Inventory.EquipmentKeys.Contains(category))
        {
            if (category == "MoaPets")
            {
                if (account is null || count != 1) throw new ApiException(400, "Robotic companions require an account and a quantity of one"); var fp = targetFingerprint is null ? null : JObject.Parse(targetFingerprint); var parts = PetFactory.RoboticParts(type, fp); var changes = new ModularApi(catalog, clock ?? TimeProvider.System).Create(account, type, parts, premium);
                if (fp?.Value<string>("Name") is string name) { var gear = Inventory.Equipment(inv, category, Wire.Id(changes[category]![0]!["ItemId"])); gear["ItemName"] = name; changes[category] = new JArray(gear.DeepClone()); } return changes;
            }
            if (category is "SpecialItems" or "Antiques" && inv.Array(category).Any(x => x.Value<string>("ItemType") == type)) return category == "Antiques" ? TauronFocus.EnsureOwned(inv) : delta;
            if (category == "Antiques" && count != 1) throw new ApiException(400, "Acquire one Tektolyst artifact at a time");
            if (category is "Horses" or "Motorcycles" or "CrewShips" or "CrewShipHarnesses" && inv.Array(category).Count > 0) return delta;
            if (withSlots) Inventory.Combine(delta, Inventory.OccupySlots(inv, category, count, premium));
            Inventory.Combine(delta, Inventory.AddItem(inv, category, type, count));
            foreach (var copy in (JArray)delta[category]!)
            {
                var equipment = Inventory.Equipment(inv, category, Wire.Id(copy["ItemId"]));
                equipment["Features"] = premium || category == "SpecialItems" ? 1 : 0;
                if (category == "KubrowPets") equipment["Details"] = PetFactory.Details(inv, type, premium, (clock ?? TimeProvider.System).GetUtcNow(), account is null ? GameVersion.Of("42.0.0") : GameVersion.For(account));
                if (category == "Drones") equipment["CurrentHP"] = meta.Value<int>("durability");
                if (category == "Ships") equipment["ShipExterior"] = new JObject();
                if (type == FocusApi.TrainingAmpType) equipment["ModularParts"] = new JArray(new[] { "Grip", "Chassis", "Barrel" }.Select(x => "/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTraining" + x));
                if (category == "CrewMembers")
                {
                    var crewSeed = seed ?? unchecked((ulong)Wire.Seed()); if (account is not null) crewSeed |= Convert.ToUInt64(account.RequiredString("id")[2..8], 16) << 32;
                    equipment["Seed"] = crewSeed.ToString(System.Globalization.CultureInfo.InvariantCulture); equipment["NemesisFingerprint"] = "0"; equipment["SkillEfficiency"] = new JObject(new[] { "PILOTING", "GUNNERY", "ENGINEERING", "COMBAT", "SURVIVABILITY" }.Select(x => new JProperty(x, new JObject { ["Assigned"] = 0 })));
                    if (!type.Contains("JadeShadowsPart2Mission", StringComparison.Ordinal)) equipment["PowersuitType"] = "/Lotus/Powersuits/NpcPowersuits/CrewMember" + (new[] { "Arbiters", "Perrin", "RedVeil" }.Any(x => type.Contains(x, StringComparison.Ordinal)) ? "Male" : "Female") + "Suit";
                }
                if (meta.Value<int>("maxLevelCap") == 40 && !type.Contains("BallasSword", StringComparison.Ordinal))
                {
                    var rng = new SeededRng(seed ?? unchecked((ulong)Wire.Seed())); var tag = rng.Element(new[] { "InnateElectricityDamage", "InnateFreezeDamage", "InnateHeatDamage", "InnateImpactDamage", "InnateMagDamage", "InnateRadDamage", "InnateToxinDamage" }); var value = rng.Float();
                    equipment["UpgradeType"] = "/Lotus/Weapons/Grineer/KuvaLich/Upgrades/InnateDamageRandomMod";
                    equipment["UpgradeFingerprint"] = new JObject { ["compat"] = type, ["buffs"] = new JArray(new JObject { ["Tag"] = tag, ["Value"] = (long)((value >= .941428 ? 1 : value) * 0x40000000) }) }.ToString(Newtonsoft.Json.Formatting.None);
                }
                if (meta.Value<string>("bayonetOtherWeaponType") is string counterpart && !meta.Value<bool>("excludeFromMarket"))
                {
                    var pair = Add(inv, counterpart, premium: premium, withSlots: false, depth: depth + 1); var otherCategory = catalog.Get(counterpart).Category; var otherCopy = (JObject)pair[otherCategory]![0]!;
                    var other = Inventory.Equipment(inv, otherCategory, Wire.Id(otherCopy["ItemId"])); other["AltWeaponModeId"] = equipment["ItemId"]!.DeepClone(); other["IsNew"] = false; equipment["AltWeaponModeId"] = other["ItemId"]!.DeepClone(); otherCopy.Merge(other, new() { MergeArrayHandling = Newtonsoft.Json.Linq.MergeArrayHandling.Replace }); Inventory.Combine(delta, pair);
                }
                if (meta["defaultUpgrades"] is JArray defaults)
                {
                    var upgrades = new JArray();
                    foreach (var upgrade in defaults.OfType<JObject>())
                    {
                        Inventory.Combine(delta, Add(inv, upgrade.RequiredString("ItemType"), depth: depth + 1));
                        var slot = upgrade.Value<int>("Slot");
                        if (slot < 0) continue;
                        if (slot > 63) throw new ApiException(400, "Invalid default mod slot");
                        while (upgrades.Count <= slot) upgrades.Add("");
                        upgrades[slot] = upgrade["ItemType"]!.DeepClone();
                    }
                    if (upgrades.Count > 0) equipment["Configs"] = new JArray(new JObject { ["Upgrades"] = upgrades });
                }
                if (targetFingerprint is not null)
                {
                    var fingerprint = JObject.Parse(targetFingerprint);
                    if (fingerprint["UpgradeFingerprint"] is JObject innate) { equipment["UpgradeType"] = fingerprint["ItemType"]?.DeepClone(); equipment["UpgradeFingerprint"] = innate.ToString(Newtonsoft.Json.Formatting.None); equipment["ItemName"] = fingerprint["Name"]?.DeepClone(); }
                    else equipment["UpgradeFingerprint"] = targetFingerprint;
                }
                ((JObject)copy).Merge(equipment, new() { MergeArrayHandling = MergeArrayHandling.Replace });
            }
            if (meta.Value<string>("defaultWeapon") is string weapon)
                Inventory.Combine(delta, Add(inv, weapon, count, premium, withSlots, depth + 1));
            if (meta["exalted"] is JArray exalted)
                foreach (var item in exalted) Inventory.Combine(delta, Add(inv, item.ToString(), withSlots: false, depth: depth + 1));
            if (category == "CrewShips") Inventory.Combine(delta, Add(inv, "/Lotus/Types/Game/CrewShip/RailJack/DefaultHarness", withSlots: false, depth: depth + 1));
            if (category == "Antiques") Inventory.Combine(delta, TauronFocus.EnsureOwned(inv));
        }
        else if (category == "MiscItems")
        {
            var actual = InventoryProgress.Misc(inv, type, count);
            delta[category] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = actual });
        }
        else if (Inventory.CountedKeys.Contains(category)) Inventory.Combine(delta, Inventory.AddItem(inv, category, type, count));
        else throw new ApiException(501, $"Acquisition for {category} has not been ported");
        if (meta["additionalItems"] is JArray extras)
            foreach (var item in extras)
                if ((meta["exalted"] as JArray)?.Any(x => JToken.DeepEquals(x, item)) != true)
                    Inventory.Combine(delta, Add(inv, item.ToString(), depth: depth + 1));
        return delta;
    }
}