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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class SellApi
{
    public static readonly HashSet<string> Controllers = ["sellController"];
    private static readonly HashSet<string> EquipmentCategories = ["Suits", "LongGuns", "Pistols", "Melee", "SpaceSuits", "SpaceGuns", "SpaceMelee", "MechSuits", "Sentinels", "SentinelWeapons", "MoaPets", "OperatorAmps", "Hoverboards", "Drones", "KubrowPetPrints", "CrewMembers", "WeaponSkins"];
    public ApiResponse Handle(JObject account, ApiRequest request)
    {
        var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var items = body["Items"] as JObject ?? throw new ApiException(400, "Missing sale items"); var price = body.Integer("SellPrice"); var currency = body.Value<string>("SellCurrency") ?? (body.Value<bool>("SellForPrimeBucks") ? "SC_PrimeBucks" : body.Value<bool>("SellForFusionPoints") ? "SC_FusionPoints" : "SC_RegularCredits");
        if (currency is not ("SC_RegularCredits" or "SC_FusionPoints" or "SC_CrewShipFusionPoints" or "SC_PrimeBucks" or "SC_DistillPoints" or "SC_Resources")) throw new ApiException(400, "Unknown sale currency");
        long calculated = 0; var changes = new JObject(); var seen = new HashSet<string>(); var total = 0;
        foreach (var category in items.Properties())
        {
            if (category.Value is not JArray array || array.Any(x => x is not JObject)) throw new ApiException(400, "Invalid sale items");
            foreach (var sale in array.OfType<JObject>())
            {
                if (++total > 1000) throw new ApiException(400, "Too many sale items"); var key = sale.RequiredString("String"); var count = sale.Integer("Count", 0, 1000000); if (!seen.Add(category.Name + ":" + key)) throw new ApiException(400, "Duplicate sale item"); string type; var units = count; var rank = 0;
                if (category.Name is "Consumables" or "Recipes" or "MiscItems" || category.Name == "Upgrades" && key.StartsWith('/') && count > 0)
                {
                    if (count == 0) throw new ApiException(400, "Sale count must be positive"); type = key; Inventory.AddCount(inv, category.Name == "Upgrades" ? "RawUpgrades" : category.Name, type, -count);
                    if (category.Name == "Recipes" && inv.Array("PendingRecipes").Any(x => x.Value<string>("ItemType") == type || x.Value<string>("OwnedRecipeType") == type)) throw new ApiException(409, "Cannot sell a blueprint that is being crafted");
                }
                else if (category.Name == "FusionTreasures" && key.StartsWith('/'))
                {
                    if (count == 0) throw new ApiException(400, "Sale count must be positive"); var split = key.LastIndexOf('_'); type = split < 0 ? key : key[..split]; var sockets = split < 0 ? 0 : int.Parse(key[(split + 1)..], NumberStyles.HexNumber, CultureInfo.InvariantCulture); VaultApi.Treasure(inv, "FusionTreasures", type, sockets, -count);
                }
                else if (category.Name is "CrewShipWeapons" or "CrewShipWeaponSkins" && key.StartsWith('/'))
                {
                    if (count == 0 || currency == "SC_Resources") throw new ApiException(400, "Unrepaired salvage cannot refund build resources"); type = key; Inventory.AddCount(inv, "CrewShipRawSalvage", type, -count);
                }
                else
                {
                    if (count > 1) throw new ApiException(400, "An equipment identifier represents one item"); units = 1;
                    var field = category.Name switch { "FusionTreasures" => "HybridFusionTreasures", "Upgrades" => "Upgrades", _ => category.Name };
                    if (!EquipmentCategories.Contains(field) && field is not ("HybridFusionTreasures" or "Upgrades" or "CrewShipWeapons" or "CrewShipWeaponSkins")) throw new ApiException(400, "Unknown sale category");
                    var owned = inv.Array(field).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == key); var repaired = owned is not null;
                    if (owned is null && field is "CrewShipWeapons" or "CrewShipWeaponSkins") owned = inv.Array(field.Replace("CrewShip", "CrewShipSalvaged", StringComparison.Ordinal)).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == key);
                    if (owned is null) throw new ApiException(404, "Sale item is not owned"); Inventory.RequireNotInResearch(inv, key); type = owned.RequiredString("ItemType");
                    if (field == "Drones" && owned["DeployTime"] is not null) throw new ApiException(409, "Recall the extractor before selling it");
                    if (field == "Upgrades" && owned.Value<string>("UpgradeFingerprint") is string fingerprint) rank = JObject.Parse(fingerprint).Value<int>("lvl");
                    if (currency == "SC_Resources")
                    {
                        if (!repaired || field is not ("CrewShipWeapons" or "CrewShipWeaponSkins")) throw new ApiException(400, "Only repaired Railjack components refund resources"); RefundBuildCosts(inv, type, changes);
                    }
                    if (field == "LongGuns" && owned["AltWeaponModeId"] is JToken alternate)
                    {
                        var paired = Inventory.Equipment(inv, "Melee", Wire.Id(alternate)); changes.Array("RemovedIdItems").Add(new JObject { ["ItemId"] = paired["ItemId"]!.DeepClone() }); paired.Remove();
                    }
                    if (repaired) Inventory.FreeSlot(inv, field); owned.Remove();
                }
                if (currency == "SC_Resources" && category.Name is not ("CrewShipWeapons" or "CrewShipWeaponSkins")) throw new ApiException(400, "Invalid resource refund category");
                if (currency == "SC_PrimeBucks")
                {
                    var value = (GameData.Find("Resources", type) ?? GameData.Find("Recipes", type))?.Value<long>("primeSellingPrice") ?? 0; if (value <= 0) throw new ApiException(400, "Item cannot be exchanged for ducats"); calculated = checked(calculated + value * units);
                }
                if (currency == "SC_DistillPoints")
                {
                    var value = GameData.Find("Arcanes", type)?.Value<long>("distillPointValue") ?? 0; if (value <= 0 || rank is < 0 or > 5) throw new ApiException(400, "Item cannot be distilled"); calculated = checked(calculated + value * units * new[] { 1, 3, 6, 10, 15, 21 }[rank]);
                }
            }
        }
        if (total == 0) throw new ApiException(400, "Sale must contain an item");
        if (currency is "SC_PrimeBucks" or "SC_DistillPoints") { if (price != calculated) throw new ApiException(400, "Sale price does not match item values"); Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Items/MiscItems/" + (currency == "SC_PrimeBucks" ? "PrimeBucks" : "DistillPoints"), calculated); }
        // The original protocol reports credit/Endo prices from the game; these prices are absent from PublicExport.
        else if (currency != "SC_Resources") Inventory.ChangeCurrency(inv, currency[3..], price);
        return ApiResponse.Json(new JObject { ["inventoryChanges"] = changes });
    }
    private static void RefundBuildCosts(JObject inv, string type, JObject changes)
    {
        var recipes = GameData.Table("DojoRecipes"); var recipe = new[] { "research", "fabrications" }.SelectMany(x => (recipes[x] as JObject ?? new()).Properties()).Select(x => x.Value).FirstOrDefault(x => x.Value<string>("resultType") == type) ?? throw new ApiException(400, "No repair recipe exists for this component");
        foreach (var ingredient in (recipe["ingredients"] as JArray ?? []).OfType<JObject>()) { var count = ingredient.Integer("ItemCount") * 8 / 10; Inventory.AddCount(inv, "MiscItems", ingredient.RequiredString("ItemType"), count); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = ingredient["ItemType"]!.DeepClone(), ["ItemCount"] = count }) }); }
    }
}