using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class RelicApi(ItemCatalog catalog, TimeProvider clock) { public static readonly HashSet Controllers = ["projectionManagerController", "getVoidProjectionRewardsController"]; private static readonly string[] Qualities = ["VPQ_BRONZE", "VPQ_SILVER", "VPQ_GOLD", "VPQ_PLATINUM"]; private static readonly int[] Costs = [0, 25, 50, 100]; private static readonly double[][] Weights = [[.76, .22, .02], [.70, .26, .04], [.60, .34, .06], [.50, .40, .10]]; public ApiResponse Handle(string controller, JObject account, ApiRequest request) { var body = request.ObjectBody(); var inv = account.Obj("Inventory"); if (controller == "projectionManagerController") { var previous = body.RequiredString("projectionType"); var meta = Metadata(previous); var quality = (int)body.Integer("qualityTag", 0, 3); var old = Array.IndexOf(Qualities, meta.Value("quality")); if (old < 0 || quality <= old) throw new ApiException(400, "Relics can only be refined to a higher quality"); var next = GameData.Table("Relics").Properties().FirstOrDefault(x => x.Value.Value("era") == meta.Value("era") && x.Value.Value("category") == meta.Value("category") && x.Value.Value("quality") == Qualities[quality])?.Name ?? throw new ApiException(400, "Refined relic is not available"); var cost = inv.Value("dontSubtractVoidTraces") ? 0 : Costs[quality] - Costs[old]; Inventory.AddCount(inv, "MiscItems", previous, -1); Inventory.AddCount(inv, "MiscItems", next, 1); Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Items/MiscItems/VoidTearDrop", -cost); return ApiResponse.Json(new JObject { ["prevProjection"] = previous, ["upgradedProjection"] = next, ["upgradeCost"] = cost }); } var wave = body["CurrentWave"]?.Value() ?? body["VoidTearParticipantsCurrWave"]?.Value("Wave") ?? throw new ApiException(400, "Missing relic wave"); if (wave is < 1 or > 1000) throw new ApiException(400, "Invalid relic wave"); var participant = body["ParticipantInfo"] as JObject ?? (body["VoidTearParticipantsCurrWave"]?["Participants"] as JArray)?.OfType().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value("id")) ?? throw new ApiException(400, "Missing own relic participant"); if (Wire.Id(participant["AccountId"]) != account.Value("id")) throw new ApiException(403, "Relic participant does not match authenticated account"); if (participant.Value("QualifiesForReward") && !participant.Value("HaveRewardResponse") && string.IsNullOrEmpty(participant.Value("Reward"))) Roll(account, participant, wave, body.Value("VoidProjectionRemovalHash")); if (body["VoidTearParticipantsPrevWave"] is JObject previousWave) CorrectSelection(account, previousWave); return ApiResponse.Json(body["CurrentWave"] is not null ? new JObject { ["CurrentWave"] = wave, ["ParticipantInfo"] = participant.DeepClone(), ["DifficultyTier"] = body.Value("DifficultyTier") } : new JObject { ["VoidTearParticipantsCurrWave"] = body["VoidTearParticipantsCurrWave"]!.DeepClone() }); } private static JObject Metadata(string type) => GameData.Find("Relics", type) ?? throw new ApiException(400, "Unknown relic"); private static JArray Pool(string relic) => GameData.Table("Rewards")[Metadata(relic).Value("rewardManifest")!]?[0] as JArray ?? throw new ApiException(400, "Missing relic reward pool"); public JObject Roll(JObject account, JObject participant, int wave, string? hash = null) { var inv = account.Obj("Inventory"); var type = participant.RequiredString("VoidProjection"); var meta = Metadata(type); var group = hash ?? inv["RewardSeed"]?.ToString() ?? ""; var receipts = account.Array("RelicRolls"); var receipt = receipts.OfType().FirstOrDefault(x => x.Value("group") == group && x.Value("wave") == wave); JObject reward; if (receipt is not null) { if (receipt.Value("relic") != type) throw new ApiException(409, "This relic wave has already been resolved"); reward = (JObject)receipt["reward"]!.DeepClone(); } else { var quality = Array.IndexOf(Qualities, meta.Value("quality")); if (quality < 0) throw new ApiException(400, "Invalid relic quality"); var weights = Weights[quality].ToArray(); if (quality == 1 && inv.Value("exceptionalRelicsAlwaysGiveBronzeReward")) weights = [1, 0, 0]; else if (quality == 2 && inv.Value("flawlessRelicsAlwaysGiveSilverReward")) weights = [0, 1, 0]; else if (quality == 3 && inv.Value("radiantRelicsAlwaysGiveGoldReward")) weights = [0, 0, 1]; var pool = (JArray)Pool(type).DeepClone(); var rarities = new[] { "COMMON", "UNCOMMON", "RARE" }; for (var i = 0; i < rarities.Length; i++) { var entries = pool.OfType().Where(x => x.Value("rarity") == rarities[i]).ToArray(); foreach (var entry in entries) entry["probability"] = weights[i] / entries.Length; } reward = (JObject)(SeededRng.RewardAt(pool, Random.Shared.NextDouble()) ?? throw new ApiException(400, "Empty relic pool")).DeepClone(); var count = checked(reward.Value("itemCount") * Math.Clamp(inv.Value("relicRewardItemCountMultiplier") ?? 1, 1, 1000)); reward["itemCount"] = count; Inventory.AddCount(inv, "MiscItems", type, -1); new ItemAcquisition(catalog, clock, account).Add(inv, reward.Value("type")!, count); var bonusKey = reward.Value("rarity") switch { "COMMON" => "relicPlatinumBonusCommon", "UNCOMMON" => "relicPlatinumBonusUncommon", _ => "relicPlatinumBonusRare" }; var bonus = checked((inv.Value(bonusKey) ?? 0) * (inv.Value("relicRewardItemCountMultiplier") ?? 1)); if (bonus > 0) inv["pendingPremiumCredits"] = checked(inv.Value("pendingPremiumCredits") + bonus); if (wave == 1) inv["MissionRelicRewards"] = new JArray(); var missionRewards = inv.Array("MissionRelicRewards"); while (missionRewards.Count < wave) missionRewards.Add(JValue.CreateNull()); missionRewards[wave - 1] = new JObject { ["ItemType"] = reward["type"]!.DeepClone(), ["ItemCount"] = count }; receipts.Add(new JObject { ["group"] = group, ["wave"] = wave, ["relic"] = type, ["reward"] = reward.DeepClone() }); while (receipts.Count > 1000) receipts.RemoveAt(0); } participant["Reward"] = reward["type"]!.DeepClone(); participant["ChosenRewardOwner"] = participant["AccountId"]!.DeepClone(); return reward; } public void CorrectSelection(JObject account, JObject wave) { var inv = account.Obj("Inventory"); var index = (int)wave.Integer("Wave", 1, 1000) - 1; if (inv["MissionRelicRewards"] is not JArray rewards || index >= rewards.Count || rewards[index] is not JObject previous) return; var participants = wave["Participants"] as JArray ?? throw new ApiException(400, "Missing relic participants"); var self = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value("id")) ?? throw new ApiException(400, "Missing own relic selection"); if (self["ChosenRewardOwner"] is null) return; var owner = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == Wire.Id(self["ChosenRewardOwner"])) ?? throw new ApiException(400, "Selected relic participant is missing"); var selected = Pool(owner.Value("VoidProjection") ?? "").FirstOrDefault(x => x.Value("type") == owner.Value("Reward")) ?? throw new ApiException(400, "Selected reward is not in that relic"); var type = selected.Value("type")!; var count = checked(selected.Value("itemCount") * Math.Clamp(inv.Value("relicRewardItemCountMultiplier") ?? 1, 1, 1000)); if (previous.Value("ItemType") == type && previous.Value("ItemCount") == count) return; var oldType = catalog.ResolveType(previous.Value("ItemType")!); var category = catalog.Get(oldType).Category; if (!Inventory.CountedKeys.Contains(category)) throw new ApiException(400, "Relic reward cannot be exchanged after acquisition"); Inventory.AddCount(inv, category, oldType, -previous.Value("ItemCount")); new ItemAcquisition(catalog, clock, account).Add(inv, type, count); rewards[index] = new JObject { ["ItemType"] = type, ["ItemCount"] = count }; } public void CompleteMission(JObject account, JObject wave, JArray destination) { var inv = account.Obj("Inventory"); var self = (wave["Participants"] as JArray)?.OfType().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value("id")); if (self?.Value("QualifiesForReward") != true) return; if (!self.Value("HaveRewardResponse") && string.IsNullOrEmpty(self.Value("Reward"))) Roll(account, self, (int)wave.Integer("Wave", 1, 1000)); CorrectSelection(account, wave); foreach (var reward in (inv["MissionRelicRewards"] as JArray ?? []).OfType()) destination.Add(new JObject { ["StoreItem"] = reward["ItemType"]!.DeepClone(), ["ItemCount"] = reward["ItemCount"]!.DeepClone() }); inv.Remove("MissionRelicRewards"); } }