using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class RivenApi { public static readonly HashSet Controllers = ["activateRandomModController", "rerollRandomModController", "completeRandomModChallengeController"]; private static readonly int[] Costs = [900, 1000, 1200, 1400, 1700, 2000, 2350, 2750, 3150]; private static T Pick(IEnumerable source) { var pool = source.ToArray(); return pool.Length > 0 ? pool[Random.Shared.Next(pool.Length)] : throw new ApiException(400, "Empty Riven metadata pool"); } public static JObject Metadata(string type) => GameData.Find("Upgrades", type) is JObject meta && meta["availableChallenges"] is JArray ? meta : throw new ApiException(400, "Not a randomized mod"); public static JObject Veiled(string type, bool sentinel) { var meta = Metadata(type); var challenge = Pick(((JArray)meta["availableChallenges"]!).OfType()); var output = new JObject { ["Type"] = challenge["fullName"]!.DeepClone(), ["Progress"] = 0, ["Required"] = Random.Shared.Next(challenge["countRange"]![0]!.Value(), challenge["countRange"]![1]!.Value() + 1) }; if (Random.Shared.NextDouble() < challenge.Value("complicationChance")) { var pool = new JArray((challenge["complications"] as JArray ?? []).OfType().Select(x => new JObject { ["type"] = x["fullName"]!.DeepClone(), ["multiplier"] = x["countMultiplier"]!.DeepClone(), ["probability"] = x.Value("weight") })); if (SeededRng.RewardAt(pool, Random.Shared.NextDouble()) is JObject complication) { output["Complication"] = complication["type"]!.DeepClone(); output["Required"] = output.Value("Required") * complication.Value("multiplier"); } } var result = new JObject { ["challenge"] = output }; if (sentinel) result["IsSentinel"] = true; return result; } public static JObject Unveiled(string type, bool sentinel) { var meta = Metadata(type); var weapons = (meta["compatibleItems"] as JArray ?? []).Where(x => ((GameData.Find("Weapons", x.ToString())?["compatibilityTags"] as JArray)?.Any(t => t.ToString() == "SENTINEL_WEAPON") ?? false) == sentinel); var result = new JObject { ["compat"] = Pick(weapons).DeepClone(), ["lim"] = 0, ["lvl"] = 0, ["lvlReq"] = Random.Shared.Next(8, 17), ["pol"] = Pick(new[] { "AP_ATTACK", "AP_DEFENSE", "AP_TACTIC" }) }; if (sentinel) result["IsSentinel"] = true; Randomize(type, result); return result; } public static void Randomize(string type, JObject fingerprint) { var entries = Metadata(type)["upgradeEntries"] as JArray ?? throw new ApiException(400, "Missing Riven stat metadata"); var options = entries.Where(x => x.Value("canBeBuff")).ToList(); var buffs = new JArray(); var curses = new JArray(); var count = Random.Shared.Next(2, 4); for (var i = 0; i < count; i++) { var entry = Pick(options); options.Remove(entry); buffs.Add(new JObject { ["Tag"] = entry["tag"]!.DeepClone(), ["Value"] = Random.Shared.Next(0x40000000) }); } if (Random.Shared.NextDouble() < .5) { var entry = Pick(entries.Where(x => x.Value("canBeCurse") && !buffs.Any(b => b.Value("Tag") == x.Value("tag")))); curses.Add(new JObject { ["Tag"] = entry["tag"]!.DeepClone(), ["Value"] = Random.Shared.Next(0x40000000) }); } fingerprint["buffs"] = buffs; fingerprint["curses"] = curses; } public static JObject Create(JObject inv, string raw, bool unveiled = false) { if (WorldData.Get("rivenRawToRealWeighted")[raw] is not JArray choices) throw new ApiException(400, "Unknown raw Riven type"); var type = Pick(choices).ToString(); var sentinel = raw.EndsWith("RawSentinelWeaponRandomMod", StringComparison.Ordinal); var fingerprint = unveiled ? Unveiled(type, sentinel) : Veiled(type, sentinel); var mod = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None) }; inv.Array("Upgrades").Add(mod); return mod; } public static JObject Owned(JObject inv, JToken? id) => inv.Array("Upgrades").OfType().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(id)) ?? throw new ApiException(404, "Riven mod is not owned"); private static JObject Client(JObject mod, long build) { var result = (JObject)mod.DeepClone(); result["ItemId"] = GameVersion.Oid(Wire.Id(mod["ItemId"]), build); result["UpgradeFingerprint"] = JObject.Parse(mod.RequiredString("UpgradeFingerprint")); return result; } public ApiResponse Handle(string controller, JObject account, ApiRequest request) { var inv = account.Obj("Inventory"); var body = request.ObjectBody(); var build = GameVersion.For(account); if (controller == "activateRandomModController") { var raw = body.RequiredString("ItemType"); Inventory.AddCount(inv, "RawUpgrades", raw, -1); return ApiResponse.Json(new JObject { ["NewMod"] = Client(Create(inv, raw, inv.Value("instantFinishRivenChallenge")), build) }); } if (controller == "completeRandomModChallengeController") { var mod = Owned(inv, body["ItemId"]); Metadata(mod.RequiredString("ItemType")); var fp = JObject.Parse(mod.RequiredString("UpgradeFingerprint")); if (fp["challenge"] is not JObject challenge || challenge.Value("Progress") >= challenge.Value("Required")) throw new ApiException(409, "Riven challenge is already complete"); JObject changes; if (request.Q("p") == "1") changes = Inventory.ChangeCurrency(inv, "PremiumCredits", -20); else { const string cipher = "/Lotus/Types/Items/MiscItems/RivenIdentifier"; Inventory.AddCount(inv, "MiscItems", cipher, -1); changes = new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = cipher, ["ItemCount"] = -1 }) }; } challenge["Progress"] = challenge["Required"]!.DeepClone(); mod["UpgradeFingerprint"] = fp.ToString(Formatting.None); return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes, ["Fingerprint"] = mod["UpgradeFingerprint"]!.DeepClone() }); } if (body["ItemIds"] is JArray ids) { if (ids.Count == 0 || ids.Count > 100 || ids.Select(Wire.Id).Distinct().Count() != ids.Count) throw new ApiException(400, "Invalid Riven selection"); var changes = new JArray(); var cost = 0; foreach (var id in ids) { var mod = Owned(inv, id); var type = mod.RequiredString("ItemType"); Metadata(type); var fp = JObject.Parse(mod.RequiredString("UpgradeFingerprint")); if (fp["challenge"] is JObject challenge) { if (challenge.Value("Progress") < challenge.Value("Required") && !inv.Value("instantFinishRivenChallenge")) throw new ApiException(409, "Riven challenge is incomplete"); mod["UpgradeFingerprint"] = Unveiled(type, fp.Value("IsSentinel")).ToString(Formatting.None); } else { if (mod["PendingRerollFingerprint"] is not null) throw new ApiException(409, "Choose the pending Riven roll first"); var rerolls = fp.Value("rerolls"); if (rerolls < 0) throw new ApiException(400, "Invalid Riven roll count"); var price = inv.Value("dontSubtractKuvaForRivens") ? 0 : rerolls < Costs.Length ? Costs[rerolls] : 3500; Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Items/MiscItems/Kuva", -price); cost += price; fp["rerolls"] = checked(rerolls + 1); mod["UpgradeFingerprint"] = fp.ToString(Formatting.None); Randomize(type, fp); mod["PendingRerollFingerprint"] = fp.ToString(Formatting.None); } var change = new JObject { ["ItemId"] = GameVersion.Oid(Wire.Id(id), build), ["UpgradeFingerprint"] = mod["UpgradeFingerprint"]!.DeepClone() }; if (mod["PendingRerollFingerprint"] is JToken pending) change["PendingRerollFingerprint"] = pending.DeepClone(); changes.Add(change); } return ApiResponse.Json(new JObject { ["changes"] = changes, ["cost"] = cost }); } var target = Owned(inv, body["ItemId"]); Metadata(target.RequiredString("ItemType")); if (body.Value("CommitReroll") && target["PendingRerollFingerprint"] is JToken candidate) target["UpgradeFingerprint"] = candidate.DeepClone(); target.Remove("PendingRerollFingerprint"); return ApiResponse.Text(target.RequiredString("UpgradeFingerprint")); } public static ApiResponse Transmute(JObject inv, JObject body, long build) { var mods = (body["Consumed"] as JArray ?? []).OfType().ToArray(); if (mods.Length != 4 || mods.Select(x => Wire.Id(x["ItemId"])).Distinct().Count() != 4) throw new ApiException(400, "Riven transmutation requires four different owned mods"); foreach (var requested in mods) { var owned = Owned(inv, requested["ItemId"]); if (owned.Value("ItemType") != requested.Value("ItemType")) throw new ApiException(400, "Mismatched Riven mod"); Metadata(owned.RequiredString("ItemType")); owned.Remove(); } Inventory.ChangeCurrency(inv, "RegularCredits", -body.Integer("Cost")); if (body["FusionPointCost"] is not null) Inventory.ChangeCurrency(inv, "FusionPoints", -body.Integer("FusionPointCost")); Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Gameplay/Eidolon/Resources/SentientSecretItem", -1); var pack = GameData.Find("BoosterPacks", "/Lotus/Types/BoosterPacks/CalendarRivenPack")!; var raw = BoosterPacks.Draw((JArray)pack["components"]!, (JObject)pack["rarityWeightsPerRoll"]![0]!).RequiredString("Item"); return ApiResponse.Json(new JObject { ["NewMods"] = new JArray(Client(Create(inv, raw), build)) }); } }