using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed partial class WeeklyApi(ItemCatalog catalog, TimeProvider clock) { public static readonly HashSet Controllers = ["endlessXpController", "descentRewardsController", "entratiLabConquestModeController"]; private long Now => clock.GetUtcNow().ToUnixTimeMilliseconds(); private long WeekEnd => WorldData.Epoch + (WorldData.WeekOf(Now) + 1) * WorldData.Week; public ApiResponse Handle(string controller, JObject account, ApiRequest request) { var inv = account.Obj("Inventory"); var body = request.ObjectBody(); if (controller == "entratiLabConquestModeController") return Conquest(inv, body); var category = body.RequiredString("Category"); var circuit = controller == "endlessXpController"; if (!(circuit ? new[] { "EXC_NORMAL", "EXC_HARD" } : new[] { "DM_COH_NORMAL", "DM_COH_HARD" }).Contains(category)) throw new ApiException(400, "Invalid weekly reward category"); var entries = inv.Array(circuit ? "EndlessXP" : "DescentRewards"); var entry = entries.OfType().FirstOrDefault(x => x.Value("Category") == category); var mode = body.RequiredString("Mode"); if (mode == "r") { if (entry is null) { entry = new JObject { ["Category"] = category }; entries.Add(entry); } if (Wire.DateMs(entry["Expiry"]) != WeekEnd) { entry["Expiry"] = Wire.Date(WeekEnd); if (circuit) { var choices = body["Choices"] as JArray ?? throw new ApiException(400, "Missing reward choices"); ValidateChoices(account, category, choices); entry["Choices"] = choices.DeepClone(); entry["Earn"] = 0; entry["Claim"] = 0; entry["BonusAvailable"] = Wire.Date(WeekEnd - WorldData.Week); entry["PendingRewards"] = CircuitRewards(category, choices); } else { entry["FloorClaimed"] = 0; entry["Seed"] = Random.Shared.Next(-1_000_000_000, 1_000_000_001); entry["SelectedUpgrades"] = new JArray(); entry["PendingRewards"] = DescentRewards(category); } } else if (circuit && !JToken.DeepEquals(entry["Choices"], body["Choices"])) throw new ApiException(409, "This week's reward choices are already locked"); } else { if (entry is null || Wire.DateMs(entry["Expiry"]) != WeekEnd) throw new ApiException(409, "Weekly rewards must be initialized for the current week"); if (circuit && mode == "c") { var changes = new JObject(); foreach (var threshold in entry.Array("PendingRewards").OfType().Where(x => entry.Value("Claim") < x.Value("RequiredTotalXp") && x.Value("RequiredTotalXp") <= entry.Value("Earn"))) foreach (var reward in threshold.Array("Rewards").OfType()) Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItem"), (int)reward.Integer("ItemCount", 1, 100_000))); entry["Claim"] = entry.Value("Earn"); return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes, ["ClaimedXp"] = entry["Claim"]!.DeepClone() }); } if (!circuit && mode == "s") { // These are opaque selection identifiers, not item-resource paths. // Keep the game's ordering and unselected positions unchanged. // This endpoint persists and echoes them; it never loads a resource. if (body["SelectedUpgrades"] is not JArray upgrades) throw new ApiException(400, "SelectedUpgrades must be an array"); if (upgrades.Count > 100) throw new ApiException(400, "SelectedUpgrades has too many positions"); for (var index = 0; index < upgrades.Count; index++) if (upgrades[index].Type != JTokenType.String || upgrades[index].ToString().Length > 1024 || upgrades[index].ToString().Any(char.IsControl)) throw new ApiException(400, $"Invalid SelectedUpgrades position {index}"); entry["SelectedUpgrades"] = upgrades.DeepClone(); } else throw new ApiException(400, "Unknown weekly reward mode"); } if (circuit) return ApiResponse.Json(new JObject { ["NewProgress"] = entry.DeepClone() }); var response = (JObject)entry.DeepClone(); response.Remove("Category"); return ApiResponse.Json(response); } private void ValidateChoices(JObject account, string category, JArray choices) { var hard = category == "EXC_HARD"; var table = WorldData.Get(hard ? "hardModeChosenRewards" : "normalModeChosenRewards"); var offered = WorldRotations.CircuitChoices(WorldData.WeekOf(Now), GameVersion.For(account)).First(x => x.Value("Category") == category)["Choices"]!; if (choices.Count != (hard ? 2 : 1) || choices.Any(x => x.Type != JTokenType.String || table[x.ToString()] is null || !offered.Any(o => o.ToString() == x.ToString()) && !(hard && new[] { "RivenPrimary", "RivenSecondary", "RivenMelee", "Kuva" }.Contains(x.ToString()))) || choices.Select(x => x.ToString()).Distinct().Count() != choices.Count) throw new ApiException(400, "Invalid reward choices for this week"); } private static JObject Counted(string type, int count = 1) => new() { ["StoreItem"] = type, ["ItemCount"] = count }; private static JToken Pick(JToken array) => array[Random.Shared.Next(array.Count())]!.DeepClone(); private static JObject RandomDeck(string name) { var row = Pick(GameData.Table("Rewards")["/Lotus/Types/Game/MissionDecks/DuviriEndlessCircuitRewards/DuviriEndless" + name + "Rewards"]![0]!); return Counted(row.Value("type")!, row.Value("itemCount")); } private static JArray CircuitRewards(string category, JArray choices) { var hard = category == "EXC_HARD"; var thresholds = hard ? new[] { 285, 600, 945, 1335, 1785, 2310, 2925, 3645, 4485, 5460 } : new[] { 190, 400, 630, 890, 1190, 1540, 1950, 2430, 2990, 3640 }; var normal = WorldData.Get("normalModeChosenRewards")[choices[0].ToString()] as JArray; JObject[] rewards = hard ? [RandomDeck("SteelPathSilver"), RandomDeck("SteelPathArcane"), RandomDeck("SteelPathSilver"), RandomDeck("SteelPathSilver"), Counted(WorldData.Get("hardModeChosenRewards")[choices[0].ToString()]!.ToString()), RandomDeck("SteelPathGold"), RandomDeck("SteelPathGold"), RandomDeck("SteelPathArcane"), RandomDeck("SteelPathSteelEssence"), Counted(WorldData.Get("hardModeChosenRewards")[choices[1].ToString()]!.ToString())] : [RandomDeck("NormalSilver"), Counted(normal![0].ToString()), RandomDeck("NormalSilver"), RandomDeck("NormalMOD"), Counted(normal[1].ToString()), RandomDeck("NormalGold"), Counted(normal[2].ToString()), Counted(normal[3].ToString()), RandomDeck("NormalArcane"), Counted(normal[4].ToString())]; return new JArray(thresholds.Select((xp, i) => new JObject { ["RequiredTotalXp"] = xp, ["Rewards"] = new JArray(rewards[i]) })); } private static JArray DescentRewards(string category) { var normal = category == "DM_COH_NORMAL"; var rewards = new JArray(); foreach (var floor in new[] { 2, 4, 6, 9, 11, 13, 16, 18, 20, 21 }) { var reward = floor == 21 ? Pick(WorldData.Get("finalRewards")[category]!) : floor is 6 or 13 or 20 ? Counted(Pick(WorldData.Get("arcaneRewards")[category]!).ToString(), floor == 20 ? 3 : 1) : floor == 18 && !normal ? Counted("/Lotus/StoreItems/Types/Items/MiscItems/SteelEssence", 25) : !normal && floor is 4 or 11 ? Pick(WorldData.Get("spSilverRewards")) : Pick(WorldData.Get("bronzeRewards")[category]!); rewards.Add(new JObject { ["FloorCheckpoint"] = floor, ["Rewards"] = new JArray(reward) }); } return rewards; } public static void ResetVault(JObject inv, long now) { if (Wire.DateMs(inv["EntratiVaultCountResetDate"]) > now) return; inv["EntratiVaultCountResetDate"] = Wire.Date(WorldData.Epoch + (WorldData.WeekOf(now) + 1) * WorldData.Week); inv["EntratiVaultCountLastPeriod"] = 0; foreach (var prefix in new[] { "EntratiLabConquest", "EchoesHexConquest" }) { inv[prefix + "Unlocked"] = 0; inv[prefix + "CacheScoreMission"] = 0; inv[prefix + "ActiveFrameVariants"] = new JArray(); } inv["EchoesHexConquestActiveStickers"] = new JArray(); } private ApiResponse Conquest(JObject inv, JObject body) { ResetVault(inv, Now); var prefix = body.Value("IsEchoesDeepArchemedea") != 0 ? "EchoesHexConquest" : "EntratiLabConquest"; if (body.Value("BuyMode") != 0 && inv.Value(prefix + "Unlocked") == 0) { if (inv.Value("EntratiVaultCountLastPeriod") > 3) throw new ApiException(409, "Not enough weekly search pulses"); inv["EntratiVaultCountLastPeriod"] = inv.Value("EntratiVaultCountLastPeriod") + 2; inv[prefix + "Unlocked"] = 1; } if (inv.Value(prefix + "Unlocked") != 0) foreach (var suffix in prefix == "EchoesHexConquest" ? new[] { "ActiveFrameVariants", "ActiveStickers" } : new[] { "ActiveFrameVariants" }) if (body[prefix + suffix] is JToken value) { if (value is not JArray list || list.Count > 100 || list.Any(x => x.Type != JTokenType.String)) throw new ApiException(400, "Invalid conquest equipment choices"); inv[prefix + suffix] = list.DeepClone(); } return ApiResponse.Json(new JObject(new[] { "EntratiVaultCountResetDate", "EntratiVaultCountLastPeriod", "EntratiLabConquestUnlocked", "EntratiLabConquestCacheScoreMission", "EchoesHexConquestUnlocked", "EchoesHexConquestCacheScoreMission" }.Select(key => new JProperty(key, inv[key]?.DeepClone())))); } }