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 LoginRewardsApi(ItemCatalog catalog, TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["loginRewardsController", "loginRewardsSelectionController", "giveLoginRewardController"];
    private static SeededRng Rng(JObject account) => new((ulong)SeededRng.Mix(unchecked((int)uint.Parse(account.RequiredString("id")[16..], NumberStyles.HexNumber, CultureInfo.InvariantCulture)), account.Value<int>("LoginDays")));
    private static bool Milestone(int day, long build) => day > 0 && (build < GameVersion.Of("23.10.0") ? day % 50 == 0 && day <= 1000 : day == 5 || day % 50 == 0);
    public ApiResponse Handle(string controller, JObject account, ApiRequest request)
    {
        var inv = account.Obj("Inventory"); var day = account.Value<int>("LoginDays"); var now = clock.GetUtcNow(); var today = now.ToUnixTimeSeconds() / 86400 * 86400; var build = GameVersion.For(account); var milestone = Milestone(day, build); var legacy = build < GameVersion.Of("23.10.0");
        if (controller == "giveLoginRewardController")
        {
            if (account.Value<long>("LastLoginRewardDate") == today) return ApiResponse.Json(new JObject());
            if (inv.Value<bool>("disableDailyTribute")) throw new ApiException(409, "Daily tribute is disabled");
            var type = (request.ObjectBody()["reward"] as JObject ?? throw new ApiException(400, "Missing reward")).RequiredString("StoreItemType");
            var reward = (Pending(account, today, build)["Rewards"] as JArray ?? []).OfType<JObject>().FirstOrDefault(x => x.Value<string>("StoreItemType") == type) ?? throw new ApiException(400, "Reward was not offered today");
            var changes = Claim(account, reward); Complete(account, today, new JObject { ["DailyTributeInfo"] = new JObject { ["ChosenReward"] = reward.DeepClone(), ["NewInventory"] = changes.DeepClone() } }); return ApiResponse.Json(changes);
        }
        if (controller == "loginRewardsSelectionController")
        {
            var body = request.ObjectBody(); if (body["ChosenReward"]?.Type != JTokenType.String || body.Value<string>("ChosenReward")!.Length > 512) throw new ApiException(400, "Invalid ChosenReward"); var type = body.Value<string>("ChosenReward")!;
            if (account.Value<long>("LastLoginRewardDate") == today)
            {
                if (account["LoginRewardClaim"] is JObject claim && claim["DailyTributeInfo"]?["ChosenReward"]?.Value<string>("StoreItemType") == type) return ApiResponse.Json(claim);
                throw new ApiException(409, "Today's login reward was already claimed");
            }
            if (inv.Value<bool>("disableDailyTribute")) throw new ApiException(409, "Daily tribute is disabled");
            JObject chosen;
            if (body.Value<bool>("IsMilestoneReward"))
            {
                if (!milestone) throw new ApiException(400, "Today is not a milestone");
                var evergreen = WorldData.Get("evergreenRewards").Any(x => x.ToString() == type);
                var known = WorldData.Get("legacyMilestones").Any(x => x.Value<string>("StoreItemType") == type) || type == "/Lotus/Types/StoreItems/Packages/Login5Pack" || evergreen;
                if (!known || (day == 5 && type != "/Lotus/Types/StoreItems/Packages/Login5Pack") || (!evergreen && inv.Array("LoginMilestoneRewards").Any(x => x.ToString() == type))) throw new ApiException(400, "Invalid or previously claimed milestone reward");
                chosen = new JObject { ["RewardType"] = "RT_STORE_ITEM", ["StoreItemType"] = type, ["Amount"] = 1 }; if (!evergreen) inv.Array("LoginMilestoneRewards").Add(type);
            }
            else chosen = (JObject)(Pending(account, today, build)["Rewards"] as JArray ?? []).FirstOrDefault(x => x.Value<string>("StoreItemType") == type)! ?? throw new ApiException(400, "Reward was not offered today");
            var result = new JObject { ["DailyTributeInfo"] = new JObject { ["NewInventory"] = Claim(account, chosen), ["ChosenReward"] = chosen.DeepClone() } }; Complete(account, today, result); return ApiResponse.Json(result);
        }
        var choice = Rng(account).Float() < .25;
        var info = new JObject { ["IsMilestoneDay"] = milestone, ["IsChooseRewardSet"] = choice, ["IsHiddenRewardSet"] = choice, ["LoginDays"] = day, ["NextMilestoneReward"] = "", ["NextMilestoneDay"] = legacy && day >= 1000 ? 1000 : !legacy && day < 5 ? 5 : (day / 50 + 1) * 50 };
        var response = new JObject { ["DailyTributeInfo"] = info };
        if (account.Value<long>("LastLoginRewardDate") == today || inv.Value<bool>("disableDailyTribute")) return ApiResponse.Json(response);
        var rewards = milestone && legacy ? new JArray(WorldData.Get("legacyMilestones")[day / 50 - 1]!.DeepClone()) : (JArray)Pending(account, today, build)["Rewards"]!.DeepClone();
        info["Rewards"] = rewards; info["IsChooseRewardSet"] = rewards.Count > 1; info["IsHiddenRewardSet"] = rewards.Count > 1; info["HasChosenReward"] = false; response["LastLoginRewardDate"] = today;
        if (!milestone && rewards.Count == 1 || legacy)
        {
            var chosen = (JObject)rewards[0]; info["HasChosenReward"] = true; info["ChosenReward"] = chosen.DeepClone(); info["NewInventory"] = Claim(account, chosen);
            if (milestone) inv.Array("LoginMilestoneRewards").UniqueAdd(chosen["StoreItemType"]!); Complete(account, today, response);
        }
        if (build < GameVersion.Of("18.0.2"))
        {
            foreach (var reward in rewards.OfType<JObject>())
                if (reward.Value<string>("Icon") == "/Lotus/Interface/Icons/StoreIcons/Currency/CreditsLarge.png") reward["Icon"] = "/Lotus/Interface/Icons/Store/CreditBooster.png";
                else if (reward.Value<string>("RewardType") == "RT_RESOURCE") reward["Icon"] = (GameData.Find("Resources", reward.Value<string>("ItemType"))?.Value<string>("icon") ?? "").Replace("/Lotus/Interface/Icons/StoreIcons/Resources/CraftingComponents/", "/Lotus/Interface/Icons/Store/", StringComparison.Ordinal);
                else if (reward.Value<string>("RewardType") == "RT_BOOSTER") reward["Icon"] = (GameData.Find("Boosters", reward.Value<string>("StoreItemType"))?.Value<string>("icon") ?? "").Replace("/Lotus/Interface/Icons/StoreIcons/Boosters/", "/Lotus/Interface/Icons/Store/", StringComparison.Ordinal);
            return ApiResponse.Json(new JObject { ["Rewards"] = rewards });
        }
        return ApiResponse.Json(response);
    }
    private JObject Pending(JObject account, long today, long build)
    {
        if (account["PendingLoginReward"] is JObject existing && existing.Value<long>("Date") == today && existing.Value<int>("LoginDays") == account.Value<int>("LoginDays")) return existing;
        var rng = Rng(account); var choice = rng.Float() < .25; var rewards = new JArray();
        for (var attempts = 0; rewards.Count < (choice ? 3 : 1) && attempts < 100; attempts++) { var reward = RandomReward(account, build, rng); if (!rewards.Any(x => x.Value<string>("StoreItemType") == reward.Value<string>("StoreItemType"))) rewards.Add(reward); }
        if (rewards.Count != (choice ? 3 : 1)) throw new ApiException(400, "Not enough eligible daily tribute choices");
        var result = new JObject { ["Date"] = today, ["LoginDays"] = account.Value<int>("LoginDays"), ["Rewards"] = rewards }; account["PendingLoginReward"] = result; return result;
    }
    private static JObject RandomReward(JObject account, long build, SeededRng rng)
    {
        var inv = account.Obj("Inventory"); var day = Math.Min(account.Value<int>("LoginDays"), 3000); var pool = WorldData.Get("randomRewards").OfType<JObject>().Where(x => x.Value<string>("minBuildLabel") is not string label || build >= GameVersion.Parse(label)).ToArray();
        var rarityCounts = pool.GroupBy(x => x.RequiredString("Rarity")).ToDictionary(x => x.Key, x => x.Count()); var weighted = new JArray(pool.Select(x => { var entry = (JObject)x.DeepClone(); entry["probability"] = WorldData.Get("randomRewardsWeights").Value<double>(x.RequiredString("Rarity")) / rarityCounts[x.RequiredString("Rarity")]; return entry; }));
        for (var attempt = 0; attempt < 100; attempt++)
        {
            var reward = rng.Reward(weighted)!; var type = reward.Value<string>("StoreItemType") ?? "";
            if (reward.Value<string>("RewardType") == "RT_RANDOM_RECIPE")
            {
                var mastered = inv.Array("XPInfo").Select(x => x.Value<string>("ItemType")).ToHashSet(); var eligible = new HashSet<string>();
                foreach (var category in new[] { "Weapons", "Warframes" }) foreach (var item in GameData.Table(category).Properties()) if (item.Value.Value<string>("variantType") == "VT_NORMAL" && !mastered.Contains(item.Name) && item.Value.Value<long>("introducedAt") is > 0 and var introduced && (category != "Weapons" || item.Value.Value<double>("totalDamage") != 0) && GameVersion.Parse(DateTimeOffset.FromUnixTimeSeconds(introduced).ToString("yyyy.MM.dd.HH.mm")) <= build) eligible.Add(item.Name);
                var recipes = GameData.Table("Recipes").Properties().Where(x => !x.Value.Value<bool>("excludeFromMarket") && eligible.Contains(x.Value.Value<string>("resultType") ?? "")).ToArray(); if (recipes.Length == 0) continue; type = GameData.StoreType(rng.Element(recipes).Name);
            }
            else if (type == "/Lotus/StoreItems/Types/BoosterPacks/LoginRewardRandomProjection") { var pack = GameData.Find("BoosterPacks", build >= GameVersion.Of("18.16.0") ? "/Lotus/Types/BoosterPacks/LoginRewardRandomProjection" : "/Lotus/Types/BoosterPacks/RandomKey"); type = GameData.StoreType(rng.Element(((JArray)pack!["components"]!).ToArray()).Value<string>("Item")!); }
            var scale = reward.Value<double>("ScalingMultiplier"); var multiplier = inv.Value<double?>("dailyTributeRewardMultiplier") ?? 1;
            if (!double.IsFinite(multiplier) || multiplier <= 0 || multiplier > 1000) throw new ApiException(400, "Invalid daily tribute multiplier");
            var duration = reward.Value<double>("Duration"); var amount = reward.Value<double>("Amount");
            return new JObject { ["RewardType"] = reward["RewardType"]!.DeepClone(), ["Icon"] = reward.Value<string>("Icon") ?? "", ["ItemType"] = GameData.ItemType(type), ["StoreItemType"] = type, ["Amount"] = duration > 0 ? 1 : (int)Math.Floor(amount * (1 + day * scale / 200) * multiplier + .5), ["ScalingMultiplier"] = scale, ["Duration"] = duration > 0 ? (int)Math.Floor(duration * (1 + day * scale / 200) * multiplier + .5) : 0, ["Transmission"] = reward.Value<string>("Transmission") ?? "" };
        }
        throw new ApiException(400, "Unable to select a daily tribute reward");
    }
    private JObject Claim(JObject account, JObject reward)
    {
        var inv = account.Obj("Inventory");
        if (reward.Value<string>("RewardType") == "RT_CREDITS") return Inventory.ChangeCurrency(inv, "RegularCredits", reward.Integer("Amount", 1));
        return new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItemType"), (int)reward.Integer("Amount", 1, 100000), premium: true, durabilityDays: reward.Value<string>("RewardType") == "RT_BOOSTER" ? reward.Value<double>("Duration") / 24 : 3);
    }
    private static void Complete(JObject account, long today, JObject response)
    {
        var day = account.Value<int>("LoginDays"); account["LoginDays"] = account.Obj("Inventory").Value<bool>("incrementDailyTributeBy50") ? Math.Max(50, (day / 50 + 1) * 50) : day + 1;
        account["LastLoginRewardDate"] = today; account["LoginRewardClaim"] = response.DeepClone(); account.Remove("PendingLoginReward");
    }
}