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 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("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("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("LastLoginRewardDate") == today) return ApiResponse.Json(new JObject()); if (inv.Value("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().FirstOrDefault(x => x.Value("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("ChosenReward")!.Length > 512) throw new ApiException(400, "Invalid ChosenReward"); var type = body.Value("ChosenReward")!; if (account.Value("LastLoginRewardDate") == today) { if (account["LoginRewardClaim"] is JObject claim && claim["DailyTributeInfo"]?["ChosenReward"]?.Value("StoreItemType") == type) return ApiResponse.Json(claim); throw new ApiException(409, "Today's login reward was already claimed"); } if (inv.Value("disableDailyTribute")) throw new ApiException(409, "Daily tribute is disabled"); JObject chosen; if (body.Value("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("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("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("LastLoginRewardDate") == today || inv.Value("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()) if (reward.Value("Icon") == "/Lotus/Interface/Icons/StoreIcons/Currency/CreditsLarge.png") reward["Icon"] = "/Lotus/Interface/Icons/Store/CreditBooster.png"; else if (reward.Value("RewardType") == "RT_RESOURCE") reward["Icon"] = (GameData.Find("Resources", reward.Value("ItemType"))?.Value("icon") ?? "").Replace("/Lotus/Interface/Icons/StoreIcons/Resources/CraftingComponents/", "/Lotus/Interface/Icons/Store/", StringComparison.Ordinal); else if (reward.Value("RewardType") == "RT_BOOSTER") reward["Icon"] = (GameData.Find("Boosters", reward.Value("StoreItemType"))?.Value("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("Date") == today && existing.Value("LoginDays") == account.Value("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("StoreItemType") == reward.Value("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("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("LoginDays"), 3000); var pool = WorldData.Get("randomRewards").OfType().Where(x => x.Value("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(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("StoreItemType") ?? ""; if (reward.Value("RewardType") == "RT_RANDOM_RECIPE") { var mastered = inv.Array("XPInfo").Select(x => x.Value("ItemType")).ToHashSet(); var eligible = new HashSet(); foreach (var category in new[] { "Weapons", "Warframes" }) foreach (var item in GameData.Table(category).Properties()) if (item.Value.Value("variantType") == "VT_NORMAL" && !mastered.Contains(item.Name) && item.Value.Value("introducedAt") is > 0 and var introduced && (category != "Weapons" || item.Value.Value("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("excludeFromMarket") && eligible.Contains(x.Value.Value("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("Item")!); } var scale = reward.Value("ScalingMultiplier"); var multiplier = inv.Value("dailyTributeRewardMultiplier") ?? 1; if (!double.IsFinite(multiplier) || multiplier <= 0 || multiplier > 1000) throw new ApiException(400, "Invalid daily tribute multiplier"); var duration = reward.Value("Duration"); var amount = reward.Value("Amount"); return new JObject { ["RewardType"] = reward["RewardType"]!.DeepClone(), ["Icon"] = reward.Value("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("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("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("RewardType") == "RT_BOOSTER" ? reward.Value("Duration") / 24 : 3); } private static void Complete(JObject account, long today, JObject response) { var day = account.Value("LoginDays"); account["LoginDays"] = account.Obj("Inventory").Value("incrementDailyTributeBy50") ? Math.Max(50, (day / 50 + 1) * 50) : day + 1; account["LastLoginRewardDate"] = today; account["LoginRewardClaim"] = response.DeepClone(); account.Remove("PendingLoginReward"); } }