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 TradingApi(TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["tradingController"];
    private static readonly string[] Counted = ["RawUpgrades", "MiscItems", "Recipes"];
    private static readonly string[] Instances = ["RandomUpgrades", "Upgrades", "LongGuns", "Pistols", "Melee"];
    public ApiResponse Handle(JObject state, JObject account, ApiRequest request)
    {
        var op = request.Q("op"); var id = account.RequiredString("id"); var inv = account.Obj("Inventory");
        if (op == "5")
        {
            var guild = GuildApi.Own(state, account, request.Q("guildId")); ResearchApi.Access(account); GuildApi.Require(guild, account, 64);
            if (!int.TryParse(request.Q("tax"), out var tax) || tax is < 0 or > 100) throw new ApiException(400, "Clan tax must be a percentage between 0 and 100"); guild["TradeTax"] = tax; return ApiResponse.Json(tax);
        }
        var buddy = request.Q("buddyId") ?? throw new ApiException(400, "Missing trading partner"); if (buddy == id) throw new ApiException(400, "Cannot trade with yourself");
        var other = GuildApi.Account(state, buddy); var side = string.CompareOrdinal(id, buddy) < 0 ? "a" : "b"; var theirs = side == "a" ? "b" : "a"; var key = side == "a" ? id + ":" + buddy : buddy + ":" + id; var trades = state.Obj("pendingTrades"); var trade = trades[key] as JObject;
        if (op == "3") { trades.Remove(key); return ApiResponse.Text(); }
        if (op == "0")
        {
            if (trade is not null) throw new ApiException(409, "A pending trade already exists with this partner");
            new PlayerApi(clock).DailyReset(inv); new PlayerApi(clock).DailyReset(other.Obj("Inventory")); Eligible(account); Eligible(other);
            if (account.Array("Ignored").Any(x => x.ToString() == buddy) || other.Array("Ignored").Any(x => x.ToString() == id)) throw new ApiException(403, "Trading partner is ignored");
            JObject? guild = null; if (request.Q("guildId") is string guildId)
            {
                guild = GuildApi.Find(state, guildId) ?? throw new ApiException(404, "Trading clan not found"); if (!guild.Array("Members").Any(x => x.Value<int>("status") == 0 && (x.Value<string>("accountId") == id || x.Value<string>("accountId") == buddy))) throw new ApiException(403, "One trading partner must belong to the trading clan");
            }
            trade = new JObject { [side] = id, [theirs] = buddy, ["aOffer"] = EmptyOffer(), ["bOffer"] = EmptyOffer(), ["revision"] = 0, ["clanTax"] = guild?.Value<int>("TradeTax") ?? 10, ["guildId"] = guild?.Value<string>("id") };
            trade[side + "Offer"] = Offer(inv, request.ObjectBody()); Reset(trade); trades[key] = trade;
        }
        else
        {
            if (trade is null) throw new ApiException(404, "Pending trade not found");
            switch (op)
            {
                case "1": trade[side + "Offer"] = Offer(inv, request.ObjectBody()); trade["revision"] = checked(trade.Value<int>("revision") + 1); Reset(trade); break;
                case "2":
                    Revision(trade, request); if (!trade.Value<bool>("aReady") || !trade.Value<bool>("bReady")) throw new ApiException(409, "Both players must confirm the current offer first");
                    trade[side + "Accepted"] = true;
                    if (trade.Value<bool>(theirs + "Accepted")) { Complete(state, trade); trades.Remove(key); return ApiResponse.Text(GameVersion.For(account) < GameVersion.Of("40.0.0") ? "9" : "12"); }
                    return ApiResponse.Text(GameVersion.For(account) < GameVersion.Of("40.0.0") ? "8" : "11");
                case "4": break;
                case "6": Revision(trade, request); trade[side + "Ready"] = true; break;
                case "7": trade[side + "Ready"] = false; trade["aAccepted"] = trade["bAccepted"] = false; break;
                default: throw new ApiException(400, "Unknown trading operation");
            }
        }
        return ApiResponse.Json(new JObject { ["PendingTrades"] = new JArray(Client(trade, id)) });
    }
    public static JArray Pending(JObject state, string accountId) => new(state.Obj("pendingTrades").Properties().Select(x => x.Value).OfType<JObject>().Where(x => x.Value<string>("a") == accountId || x.Value<string>("b") == accountId).Select(x => Client(x, accountId)));
    private static JObject Client(JObject trade, string accountId)
    {
        var us = trade.Value<string>("a") == accountId ? "a" : "b"; var them = us == "a" ? "b" : "a";
        return new JObject { ["ItemId"] = Wire.Oid(trade.RequiredString(them)), ["Giving"] = trade[us + "Offer"]!.DeepClone(), ["Getting"] = trade[them + "Offer"]!.DeepClone(), ["SelfReady"] = trade.Value<bool>(us + "Ready"), ["BuddyReady"] = trade.Value<bool>(them + "Ready"), ["State"] = trade.Value<bool>(us + "Accepted") ? trade.Value<bool>(them + "Accepted") ? 4 : 3 : 2, ["Revision"] = trade.Value<int>("revision"), ["ClanTax"] = trade.Value<int>("clanTax") };
    }
    private static JObject EmptyOffer() => new() { ["_SlotOrderInfo"] = new JArray("", "", "", "", "", "") };
    private static void Reset(JObject trade) { foreach (var field in new[] { "aReady", "bReady", "aAccepted", "bAccepted" }) trade[field] = false; }
    private static void Revision(JObject trade, ApiRequest request) { if (!int.TryParse(request.Q("revision"), out var revision) || revision != trade.Value<int>("revision")) throw new ApiException(409, "Trade offer has changed"); }
    private static void Eligible(JObject account)
    {
        var inv = account.Obj("Inventory"); if (account.Value<bool>("Banned")) throw new ApiException(403, "Trading account is banned"); if (!inv.Value<bool>("infiniteTrades") && inv.Value<int>("TradesRemaining") <= 0) throw new ApiException(409, "No trades remaining today");
        if (inv.Value<int>("PlayerLevel") < 2) throw new ApiException(403, "Trading requires mastery rank 2");
    }
    private static JObject Offer(JObject inv, JObject upload)
    {
        var result = EmptyOffer(); var unique = new HashSet<string>(); var slots = 0;
        foreach (var field in upload.Properties()) if (!Counted.Contains(field.Name) && !Instances.Contains(field.Name) && field.Name is not ("FusionTreasures" or "NemesisHistory" or "PremiumCredits" or "_SlotOrderInfo")) throw new ApiException(400, "Unknown trade category");
        if (upload["_SlotOrderInfo"] is JArray order) { if (order.Count > 6 || order.Any(x => x.Type != JTokenType.String || x.ToString().Length > 512)) throw new ApiException(400, "Invalid trade slot order"); result["_SlotOrderInfo"] = order.DeepClone(); }
        foreach (var category in Counted)
        {
            foreach (var item in Entries(upload, category))
            {
                var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 1000000); if (!unique.Add(category + ":" + type)) throw new ApiException(400, "Duplicate trade item");
                if (!inv.Array(category).Any(x => x.Value<string>("ItemType") == type && x.Value<long>("ItemCount") >= count)) throw new ApiException(400, "Offered items are not owned");
                var meta = category == "RawUpgrades" ? GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type) : GameData.Find(category == "Recipes" ? "Recipes" : "Resources", type);
                if (category == "Recipes" && meta?.Value<bool>("consumeOnUse") == true && inv.Array("Recipes").First(x => x.Value<string>("ItemType") == type).Value<long>("ItemCount") - inv.Array("PendingRecipes").Count(x => (x.Value<string>("OwnedRecipeType") ?? FoundryApi.OwnedRecipe(x.Value<string>("ItemType") ?? "")) == type) < count) throw new ApiException(409, "Blueprint is reserved by a pending recipe");
                if (meta?.Value<bool?>("tradable") == false) throw new ApiException(400, "Item cannot be traded"); result.Array(category).Add(new JObject { ["ItemType"] = type, ["ItemCount"] = count }); slots++;
            }
        }
        foreach (var category in Instances)
        {
            var field = category == "RandomUpgrades" ? "Upgrades" : category;
            foreach (var item in Entries(upload, category))
            {
                var id = Wire.Id(item["ItemId"]); if (id.Length != 24 || !unique.Add(id)) throw new ApiException(400, "Invalid or duplicate item identifier"); var owned = inv.Array(field).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == id) ?? throw new ApiException(404, "Trade item is not owned");
                var type = owned.RequiredString("ItemType"); if (item["ItemType"] is JToken asked && asked.ToString() != type) throw new ApiException(400, "Offered item type does not match its identifier");
                if (field != "Upgrades") { if (GameData.Find("Weapons", type)?.Value<bool>("tradable") != true || owned.Value<long>("XP") > 0) throw new ApiException(400, "Only unused tradable weapons can be traded"); }
                else if ((GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type))?.Value<bool?>("tradable") == false) throw new ApiException(400, "Mod cannot be traded");
                Inventory.RequireNotInResearch(inv, id); result.Array(category).Add(owned.DeepClone()); slots++;
            }
        }
        foreach (var item in Entries(upload, "FusionTreasures"))
        {
            var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 1000000); var sockets = item.Integer("Sockets", 0, 65535);
            if (!unique.Add(type + ":" + sockets) || !inv.Array("FusionTreasures").Any(x => x.Value<string>("ItemType") == type && x.Value<long>("Sockets") == sockets && x.Value<long>("ItemCount") >= count)) throw new ApiException(400, "Sculpture stack is duplicated or not owned");
            result.Array("FusionTreasures").Add(new JObject { ["ItemType"] = type, ["ItemCount"] = count, ["Sockets"] = sockets }); slots++;
        }
        if (upload["NemesisHistory"] is JObject nemesis)
        {
            var owned = inv.Array("NemesisHistory").OfType<JObject>().FirstOrDefault(x => x["fp"]?.ToString() == nemesis["fp"]?.ToString()) ?? throw new ApiException(404, "Converted nemesis is not owned");
            if (owned.Value<bool>("k") || owned.Value<bool>("Traded") || owned.Value<int>("PrevOwners") > 0) throw new ApiException(400, "Nemesis cannot be traded again"); NemesisData.Systems(owned.RequiredString("manifest")); result["NemesisHistory"] = owned.DeepClone(); slots++;
        }
        if (upload["PremiumCredits"] is not null)
        {
            var platinum = upload.Integer("PremiumCredits", 0, 999999999); if (!AccountRules.InfiniteCurrency(inv, "PremiumCredits") && platinum > inv.Value<long>("PremiumCredits") - inv.Value<long>("PremiumCreditsFree")) throw new ApiException(400, "Insufficient tradable platinum"); result["PremiumCredits"] = platinum; if (platinum > 0) slots++;
        }
        if (slots > 6) throw new ApiException(400, "A trade offer may contain at most six slots"); return result;
    }
    private static IEnumerable<JObject> Entries(JObject offer, string key)
    {
        if (offer[key] is null) return []; if (offer[key] is not JArray array || array.Any(x => x is not JObject)) throw new ApiException(400, "Invalid trade item array"); return array.OfType<JObject>();
    }
    private static void Complete(JObject state, JObject trade)
    {
        var a = GuildApi.Account(state, trade.RequiredString("a")); var b = GuildApi.Account(state, trade.RequiredString("b")); Eligible(a); Eligible(b); var ai = a.Obj("Inventory"); var bi = b.Obj("Inventory");
        var ao = (JObject)trade["aOffer"]!; var bo = (JObject)trade["bOffer"]!;
        if (!JToken.DeepEquals(ao, Offer(ai, ao)) || !JToken.DeepEquals(bo, Offer(bi, bo))) throw new ApiException(409, "An offered item changed; update and confirm the trade again");
        // Remove both offers before assigning either one, so occupied slots can be exchanged atomically.
        if (!ai.Value<bool>("tradesDontTouchInventory")) Transfer(ai, ao, -1);
        if (!bi.Value<bool>("tradesDontTouchInventory")) Transfer(bi, bo, -1);
        if (!ai.Value<bool>("tradesDontTouchInventory")) { Transfer(ai, bo, 1); Charge(state, trade, ai, bo); if (!ai.Value<bool>("infiniteTrades")) ai["TradesRemaining"] = ai.Value<int>("TradesRemaining") - 1; }
        if (!bi.Value<bool>("tradesDontTouchInventory")) { Transfer(bi, ao, 1); Charge(state, trade, bi, ao); if (!bi.Value<bool>("infiniteTrades")) bi["TradesRemaining"] = bi.Value<int>("TradesRemaining") - 1; }
    }
    private static void Transfer(JObject inv, JObject offer, int direction)
    {
        foreach (var category in Counted) foreach (var item in Entries(offer, category)) Inventory.AddCount(inv, category, item.RequiredString("ItemType"), item.Integer("ItemCount", 1) * direction);
        foreach (var category in Instances) foreach (var item in Entries(offer, category))
        {
            var field = category == "RandomUpgrades" ? "Upgrades" : category; var id = Wire.Id(item["ItemId"]);
            if (direction < 0) { var owned = inv.Array(field).First(x => Wire.Id(x["ItemId"]) == id); owned.Remove(); Inventory.FreeSlot(inv, field); }
            else
            {
                if (inv.Array(field).Any(x => Wire.Id(x["ItemId"]) == id)) throw new ApiException(409, "Recipient already owns this item identifier");
                if (field != "Upgrades" && GameData.Find("Weapons", item.Value<string>("ItemType"))?.Value<int>("masteryReq") > inv.Value<int>("PlayerLevel")) throw new ApiException(403, "Recipient does not meet the weapon mastery requirement");
                Inventory.OccupySlots(inv, field, 1, false); inv.Array(field).Add(item.DeepClone());
            }
        }
        foreach (var item in Entries(offer, "FusionTreasures")) VaultApi.Treasure(inv, "FusionTreasures", item.RequiredString("ItemType"), item.Value<int>("Sockets"), item.Integer("ItemCount", 1) * direction);
        if (offer["NemesisHistory"] is JObject nemesis)
        {
            if (direction < 0) inv.Array("NemesisHistory").First(x => x["fp"]?.ToString() == nemesis["fp"]?.ToString()).Remove();
            else { if (inv["Nemesis"] is JObject { Count: > 0 }) throw new ApiException(409, "Recipient already has an active nemesis"); inv["Nemesis"] = NemesisData.FromTrade(nemesis); }
        }
        if (offer.Value<long>("PremiumCredits") > 0)
        {
            if (direction < 0 && AccountRules.InfiniteCurrency(inv, "PremiumCredits")) return;
            var value = checked(inv.Value<long>("PremiumCredits") + offer.Value<long>("PremiumCredits") * direction); if (value < inv.Value<long>("PremiumCreditsFree") || value > 999999999) throw new ApiException(400, "Invalid platinum balance after trade"); inv["PremiumCredits"] = value;
        }
    }
    private static long Rarity(string? rarity) => rarity switch { "UNCOMMON" => 4000, "RARE" => 8000, "LEGENDARY" => 1000000, _ => 2000 };
    public static long Tax(JObject offer)
    {
        long value = offer.Value<long>("PremiumCredits") * 500 + Entries(offer, "RandomUpgrades").Count() * 8000;
        foreach (var item in Entries(offer, "Upgrades"))
        {
            var type = item.RequiredString("ItemType"); var arcane = GameData.Find("Arcanes", type); var rank = item.Value<string>("UpgradeFingerprint") is string fp ? JObject.Parse(fp).Value<int>("lvl") : 0;
            if (arcane is not null && rank is < 0 or > 5) throw new ApiException(400, "Invalid arcane rank");
            value = checked(value + (arcane?.Value<string>("rarity") == "LEGENDARY" ? new[] { 100000, 300000, 600000, 1000000, 1500000, 2100000 }[rank] : Rarity((arcane ?? GameData.Find("Upgrades", type))?.Value<string>("rarity")) * (arcane is null ? 1 : new[] { 1, 3, 6, 10, 15, 21 }[rank])));
        }
        foreach (var category in Counted) foreach (var item in Entries(offer, category))
        {
            var type = item.RequiredString("ItemType"); var meta = category == "RawUpgrades" ? GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type) : GameData.Find("Resources", type);
            var rate = category == "Recipes" ? 2000 : type.StartsWith("/Lotus/Types/Game/Projections/T3", StringComparison.Ordinal) || type.StartsWith("/Lotus/Types/Game/Projections/T4", StringComparison.Ordinal) ? 4000 : Rarity(meta?.Value<string>("rarity")); value = checked(value + rate * item.Integer("ItemCount", 1));
        }
        value += new[] { "LongGuns", "Pistols", "Melee" }.Sum(x => Entries(offer, x).Count()) * 2000;
        foreach (var item in Entries(offer, "FusionTreasures")) value = checked(value + item.Integer("ItemCount", 1) * (item.Value<int>("Sockets") > 0 ? 12000 : 4000)); if (offer["NemesisHistory"] is JObject) value += 8000; return value;
    }
    private static void Charge(JObject state, JObject trade, JObject inv, JObject incoming)
    {
        var tax = Tax(incoming); var extra = tax * trade.Value<int>("clanTax") / 100; if (!inv.Value<bool>("infiniteCredits")) Inventory.ChangeCurrency(inv, "RegularCredits", -checked(tax + extra));
        if (extra > 0 && GuildApi.Find(state, trade.Value<string>("guildId")) is JObject guild) ResearchApi.Credit(guild, "VaultRegularCredits", extra);
    }
}