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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class PurchaseApi(ItemCatalog catalog, TimeProvider clock, bool syncOfficialEvents = true)
{
    private long Price(string type, bool premium, int durability, JArray sales, int depth = 0)
    {
        if (depth > 8) throw new ApiException(400, "Recursive bundle price"); var (category, meta) = catalog.Get(type);
        var sale = sales.FirstOrDefault(x => catalog.ResolveType(x.Value<string>("TypeName") ?? "") == catalog.ResolveType(type));
        if (sale?[premium ? "PremiumOverride" : "RegularOverride"] is JToken price) return price.Value<long>();
        if (category == "Boosters") return premium && !type.Contains("Blessing", StringComparison.Ordinal) ? durability == 2 ? 200 : 40L * (durability + 1) : throw new ApiException(400, "Booster is not sold for this currency");
        if (meta[premium ? "platinumCost" : "creditsCost"] is JToken cost && cost.Type == JTokenType.Integer) return cost.Value<long>();
        if (category == "Bundles")
        {
            var total = 0L; foreach (var part in (meta["components"] as JArray ?? []).OfType<JObject>()) total = checked(total + Price(part.RequiredString("typeName"), premium, Array.IndexOf(new[] { 3, 7, 30, 90 }, part.Value<int?>("durabilityDays") ?? 3), sales, depth + 1) * part.Integer("purchaseQuantity", 1, 100000));
            return (long)Math.Floor(total * (1 - (meta.Value<double?>("packageDiscount") ?? .25)) + .5);
        }
        throw new ApiException(400, "Item has no price for the selected currency");
    }
    public ApiResponse Handle(JObject state, JObject account, ApiRequest request, bool gift = false)
    {
        var body = request.ObjectBody(); var p = body["PurchaseParams"] as JObject ?? new JObject
        {
            ["StoreItem"] = request.Q("productName") ?? body.Value<string>("productName"), ["Quantity"] = body.Value<int?>("quantity") ?? 1,
            ["UsePremium"] = (request.Q("usePremium") ?? body.Value<string>("usePremium")) == "1", ["Source"] = body["voidTraderId"] is null ? 0 : 1, ["SourceId"] = body["voidTraderId"]?.DeepClone(), ["Durability"] = int.TryParse(request.Q("durability"), out var d) ? d : 0
        };
        var inv = account.Obj("Inventory"); var source = (int)p.Integer("Source", 0, 24); var count = (int)p.Integer("Quantity", 1, 100); var premium = p.Value<bool>("UsePremium"); var durability = (int)(p["Durability"] is null ? 0 : p.Integer("Durability", 0, 3));
        var type = p.RequiredString("StoreItem").Replace("/Brass Knuckles/", "/BrassKnuckles/", StringComparison.Ordinal); var (category, meta) = catalog.Get(type); var delta = new JObject(); var response = new JObject { ["InventoryChanges"] = delta };
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); var build = GameVersion.For(account); var quantity = count; ulong? seed = null;
        if (gift && (source is not (0 or 3) || source == 0 && !premium)) throw new ApiException(400, "Only platinum market purchases and daily deals can be gifted");
        void Currency(string field, long cost)
        {
            if (cost < 0) throw new ApiException(400, "Invalid price");
            if (AccountRules.InfiniteCurrency(inv, field)) return;
            if (field == "RegularCredits" && inv.Value<bool>("dontSubtractPurchaseCreditCost") || field == "PremiumCredits" && inv.Value<bool>("dontSubtractPurchasePlatinumCost")) return;
            if (gift && field == "PremiumCredits") { if (inv.Value<long>(field) - inv.Value<long>("PremiumCreditsFree") < cost) throw new ApiException(400, "Insufficient paid platinum"); inv[field] = inv.Value<long>(field) - cost; Inventory.Combine(delta, new JObject { [field] = -cost }); }
            else Inventory.Combine(delta, Inventory.ChangeCurrency(inv, field, -cost));
        }
        void Items(JArray prices)
        {
            if (inv.Value<bool>("dontSubtractPurchaseItemCost")) return;
            foreach (var item in prices.OfType<JObject>())
            {
                var itemType = item.RequiredString("ItemType"); var itemCount = checked(count * item.Integer("ItemCount")); var itemCategory = catalog.Get(itemType).Category;
                if (!Inventory.CountedKeys.Contains(itemCategory)) throw new ApiException(400, "Vendor requires a counted payment item");
                Inventory.AddCount(inv, itemCategory, itemType, -itemCount); Inventory.Combine(delta, new JObject { [itemCategory] = new JArray(new JObject { ["ItemType"] = itemType, ["ItemCount"] = -itemCount }) });
            }
        }
        void StandingCost(string tag, long price)
        {
            if (inv.Value<bool>("dontSubtractPurchaseStandingCost")) return;
            var modifications = new JArray(); Standing.Spend(inv, tag, checked(price * count), modifications); response.Array("Standing").Add(new JObject { ["Tag"] = tag, ["Standing"] = price * count });
        }
        if (source == 2)
        {
            var tag = p.RequiredString("SyndicateTag"); var favour = (Standing.Metadata(tag)["favours"] as JArray ?? []).OfType<JObject>().FirstOrDefault(x => x.Value<string>("storeItem") == type) ?? throw new ApiException(400, "Syndicate favour is not offered");
            var affiliation = Standing.Affiliation(inv, tag); if (affiliation.Value<int>("Title") < favour.Value<int>("requiredLevel")) throw new ApiException(403, "Syndicate rank is too low");
            if (p.Value<bool>("UseFreeFavor"))
            {
                var title = affiliation.Array("FreeFavorsEarned").FirstOrDefault(x => !affiliation.Array("FreeFavorsUsed").Any(y => JToken.DeepEquals(x, y)) && x.Value<int>() == favour.Value<int>("requiredLevel"));
                if (count != 1 || !favour.Value<bool>("rankUpReward") || title is null) throw new ApiException(400, "No applicable free favour");
                affiliation.Array("FreeFavorsUsed").Add(title.DeepClone()); response["FreeFavorsUsed"] = new JArray(new JObject { ["Tag"] = tag, ["Title"] = title.DeepClone() });
            }
            else { Currency("RegularCredits", favour.Value<long>("creditsCost") * count); if (favour.Value<long>("standingCost") > 0) StandingCost(tag, favour.Value<long>("standingCost")); }
        }
        else if (source is 1 or 18)
        {
            var world = WorldApi.Generate(state, account.Value<string>("BuildLabel") ?? "2026.05.13.13.07", now, syncOfficialEvents);
            var traders = world[source == 1 ? "VoidTraders" : "PrimeVaultTraders"] as JArray ?? [];
            var trader = traders.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["_id"]) == p.Value<string>("SourceId")) ?? throw new ApiException(404, "Trader not found");
            var worldTime = world.Value<long>("Time") * 1000;
            if (Wire.DateMs(trader["Activation"]) > worldTime || Wire.DateMs(trader["Expiry"]) <= worldTime) throw new ApiException(409, "Trader is not currently available");
            var offer = trader.Array("Manifest").Concat(trader["EvergreenManifest"] as JArray ?? []).OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type) ?? throw new ApiException(400, "Item is not offered by this trader");
            if (source == 1) { Currency("RegularCredits", offer.Value<long>("RegularPrice") * count); Items(new JArray(new JObject { ["ItemType"] = "/Lotus/Types/Items/MiscItems/PrimeBucks", ["ItemCount"] = offer.Value<long>("PrimePrice") })); }
            else if (offer.Value<long>("RegularPrice") > 0) Items(new JArray(new JObject { ["ItemType"] = "/Lotus/Types/Items/MiscItems/SchismKey", ["ItemCount"] = offer.Value<long>("RegularPrice") }));
            else Currency("PrimeTokens", offer.Value<long>("PrimePrice") * count);
            if (offer.Value<int>("Limit") > 0) Tally(inv, delta, source == 1 ? "VoidTrader" : "PrimeVaultTrader", type, count, offer.Value<int>("Limit"), Wire.DateMs(trader["Expiry"]), now);
        }
        else if (source == 3)
        {
            var worldTime = WorldClock.ReportedTime(now, state.Obj("worldState"));
            var deals = WorldTrade.DailyDeals(state, worldTime, build, state.Obj("worldState")); var deal = deals.OfType<JObject>().FirstOrDefault(x => x.Value<string>("StoreItem") == type && Wire.DateMs(x["Activation"]) <= worldTime && Wire.DateMs(x["Expiry"]) > worldTime) ?? throw new ApiException(404, "Daily deal not found");
            if (count != 1 || deal.Value<long>("AmountSold") >= deal.Value<long>("AmountTotal")) throw new ApiException(409, "Daily deal is out of stock");
            Tally(inv, delta, "DailyDeal", type, 1, 1, Wire.DateMs(deal["Expiry"]), worldTime); Currency("PremiumCredits", deal.Integer("SalePrice"));
            var original = state.Obj("worldRuntime").Array("DailyDeals").First(x => x.Value<string>("StoreItem") == type); original["AmountSold"] = original.Value<int>("AmountSold") + 1;
            inv.Array("UsedDailyDeals").UniqueAdd(type); response["DailyDealUsed"] = type; premium = true;
        }
        else if (source == 7)
        {
            var vendor = VendorApi.Generate(state, VendorApi.ResolveId(p.RequiredString("SourceId"), build), build, now, inv);
            var itemId = p.Value<string>("ExtraPurchaseInfoJson") is { Length: > 0 } extra ? JObject.Parse(extra).Value<string>("ItemId") : null;
            var offer = vendor.Array("ItemManifest").OfType<JObject>().FirstOrDefault(x => itemId is null ? x.Value<string>("StoreItem") == type : Wire.Id(x["Id"]) == itemId && x.Value<string>("StoreItem") == type) ?? throw new ApiException(400, "Vendor offer is not available");
            if (Wire.DateMs(offer["Expiry"]) <= now) throw new ApiException(409, "Vendor offer expired");
            if (offer.Value<string>("Affiliation") is string tag)
            {
                if (Standing.Affiliation(inv, tag).Value<int>("Title") < offer.Value<int>("MinAffiliationRank")) throw new ApiException(403, "Vendor rank requirement is not met");
                if (offer.Value<long>("StandingCost") > 0) StandingCost(tag, offer.Value<long>("StandingCost"));
            }
            if (offer["RegularPrice"] is JArray credits) Currency("RegularCredits", credits[0].Value<long>() * count);
            if (offer["PremiumPrice"] is JArray platinum) Currency("PremiumCredits", platinum[0].Value<long>() * count);
            if (offer["ItemPrices"] is JArray prices) Items(prices);
            if (offer["FocusXpCost"] is JObject focus)
            {
                var polarity = focus.RequiredString("polarity"); var cost = checked(focus.Integer("cost") * count); if (inv.Obj("FocusXP").Value<long>(polarity) < cost) throw new ApiException(400, "Insufficient focus points");
                inv.Obj("FocusXP")[polarity] = inv.Obj("FocusXP").Value<long>(polarity) - cost; response["FocusCost"] = new JObject { ["Polarity"] = polarity, ["Cost"] = cost };
            }
            Tally(inv, delta, vendor.RequiredString("TypeName"), Wire.Id(offer["Id"]), count, offer.Value<int>("PurchaseQuantityLimit"), p.Value<bool>("IsWeekly") ? WorldData.Epoch + (WorldData.WeekOf(now) + 1L) * WorldData.Week : Wire.DateMs(offer["Expiry"]), now);
            quantity = checked(count * (int)offer.Integer("QuantityMultiplier", 1, 100000));
            if (ulong.TryParse(offer.Value<string>("LocTagRandSeed"), out var s)) seed = s;
        }
        else
        {
            var world = WorldApi.Generate(state, account.Value<string>("BuildLabel")!, now, syncOfficialEvents); var worldTime = world.Value<long>("Time") * 1000;
            var sales = new JArray(world.Array("FlashSales").Where(x => (x["StartDate"] is null || Wire.DateMs(x["StartDate"]) <= worldTime) && (x["EndDate"] is null || Wire.DateMs(x["EndDate"]) > worldTime)));
            if (meta.Value<bool>("excludeFromMarket") && !sales.Any(x => catalog.ResolveType(x.Value<string>("TypeName") ?? "") == catalog.ResolveType(type) && x.Value<bool?>("ShowInMarket") != false)) throw new ApiException(400, "Item is not available in the market");
            var price = checked(Price(type, premium, durability, sales) * count);
            if (p.Value<long>("ExpectedPrice") > 0 && p.Value<long>("ExpectedPrice") != price) throw new ApiException(409, "Market price changed"); Currency(premium ? "PremiumCredits" : "RegularCredits", price);
        }
        if (category is "MiscItems" or "Consumables") quantity = checked(quantity * (meta.Value<int?>("purchaseQuantity") ?? 1));
        if (gift) return ApiResponse.Json(response);
        var packResults = new JArray(); Inventory.Combine(delta, new ItemAcquisition(catalog, clock, account, packResults).Add(inv, type, quantity, premium, durabilityDays: new[] { 3, 7, 30, 90 }[durability], seed: seed));
        if (packResults.Count > 0)
        {
            var packed = string.Concat(packResults.Select(x => x.Value<string>("StoreItem") + "," + x["Fingerprint"]!.ToString(Formatting.None) + ";")); response["BoosterPackItems"] = packed; response["Body"] = packed.Replace("{", "", StringComparison.Ordinal).Replace("}", "", StringComparison.Ordinal).Replace("\"", "", StringComparison.Ordinal).Replace(':', '=');
        }
        if (request.Method == "GET") return response.Value<string>("Body") is string legacyBody ? ApiResponse.Text(legacyBody.Replace("/StoreItems", "", StringComparison.Ordinal)) : ApiResponse.Text(catalog.ResolveType(type));
        return ApiResponse.Json(response);
    }
    public static void Tally(JObject inv, JObject delta, string vendor, string id, int count, int limit, long expiry, long now)
    {
        if (inv.Value<bool>("noVendorPurchaseLimits")) return;
        var entry = inv.Array("RecentVendorPurchases").OfType<JObject>().FirstOrDefault(x => x.Value<string>("VendorType") == vendor);
        if (entry is null) { entry = new JObject { ["VendorType"] = vendor, ["PurchaseHistory"] = new JArray() }; inv.Array("RecentVendorPurchases").Add(entry); }
        var purchase = entry.Array("PurchaseHistory").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemId") == id);
        if (purchase is null) { purchase = new JObject { ["ItemId"] = id, ["NumPurchased"] = 0, ["Expiry"] = Wire.Date(expiry) }; entry.Array("PurchaseHistory").Add(purchase); }
        var previous = Wire.DateMs(purchase["Expiry"]) <= now ? 0 : purchase.Value<int>("NumPurchased"); if (limit > 0 && previous + count > limit) throw new ApiException(409, "Vendor purchase limit exceeded");
        purchase["NumPurchased"] = checked(previous + count); purchase["Expiry"] = Wire.Date(expiry); var change = new JObject { ["VendorType"] = vendor, ["PurchaseHistory"] = new JArray(purchase.DeepClone()) }; delta["NewVendorPurchase"] = change; delta["RecentVendorPurchases"] = change.DeepClone();
    }
}