using System.Security.Cryptography; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class MissionApi(ItemCatalog catalog, TimeProvider clock, bool syncOfficialEvents = true, Func? replay = null) { public ApiResponse Handle(JObject account, ApiRequest request, JObject? state = null) { var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var replayKey = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body.ToString(Formatting.None)))); var isFinal = body.Value("EndOfMatchUpload"); var checkpoint = isFinal || body["RewardInfo"] is not null || body["NemesisKillConvert"] is not null; var previous = (account["MissionReceipts"] as JArray)?.OfType().FirstOrDefault(x => x.Value("key") == replayKey); if (checkpoint && previous is not null) return replay is null ? MissionReceipts.Replay(previous) : replay(previous); var info = body["RewardInfo"] as JObject; var completedSortie = (inv["CompletedSorties"] as JArray ?? []).Any(x => x.ToString() == body.Value("SortieId")); var changes = ApplyInventory(account, body, state); var failed = body["MissionStatus"] is not null ? body.Value("MissionStatus") != "GS_SUCCESS" : body.Value("MissionFailed"); var events = new EventApi(catalog, clock, syncOfficialEvents); if (body["GoalProgress"] is JArray goals) events.Goals(state ?? new JObject(), account, goals, info?.Value("node"), body["Missions"]?.Value("Tier") == 1); if (body["InvasionProgress"] is JArray invasions) events.Invasions(account, invasions); var rewards = new JArray(); var response = new JObject { ["MissionRewards"] = rewards, ["InventoryChanges"] = changes, ["AffiliationMods"] = body["AffiliationChanges"]?.DeepClone() ?? new JArray() }; if (!failed && info is not null) { var node = GameData.Find("Regions", info.Value("node")); var rotations = Rotations(info, node, body.Value("wagerTier")); var seed = info["rewardSeed"] is JObject seedObject ? seedObject["$numberLong"]?.ToString() : info["rewardSeed"]?.ToString(); var rng = new SeededRng(~unchecked((ulong)(long.TryParse(seed, out var clientSeed) ? clientSeed : Wire.Seed()))); var special = new MissionSpecialRewards(clock, syncOfficialEvents); var bounty = special.Bounty(account, body, info, rewards, (JArray)response["AffiliationMods"]!, response, rng, state); var duviri = WeeklyApi.Duviri(state ?? new JObject(), body, info, rewards, rng); new WeeklyApi(catalog, clock).Mission(account, body, info, rewards, response, rng); WeeklyApi.Purgatory(info, rewards, rng); MissionDrops.Stripped(inv, body, rewards, clock.GetUtcNow().ToUnixTimeMilliseconds()); if (!bounty && !duviri && string.IsNullOrEmpty(info.Value("sortieId")) && node is not null) foreach (var table in node["rewardManifests"] as JArray ?? []) Roll(table.ToString(), rotations, rewards, rng, info.Value("VaultsCracked") > 0); var completionCredits = special.Sortie(account, info, rewards, completedSortie); special.Storm(account, info, node, rewards); if (!string.IsNullOrEmpty(info.Value("alertId"))) completionCredits += MissionSpecialRewards.Alert(WorldApi.Generate(state ?? new JObject(), account.Value("BuildLabel") ?? "2026.05.13.13.07", clock.GetUtcNow().ToUnixTimeMilliseconds(), syncOfficialEvents), inv, info, body, rewards); if (info.Value("periodicMissionTag")?.StartsWith("HardDaily", StringComparison.Ordinal) == true) MissionSpecialRewards.Reward(rewards, "/Lotus/Types/Items/MiscItems/SteelEssence", 5); JObject? goal = null; if (info.Value("goalId") is string goalId && goalId.Length > 0) goal = WorldApi.Generate(state ?? new JObject(), account.Value("BuildLabel")!, clock.GetUtcNow().ToUnixTimeMilliseconds(), syncOfficialEvents).Array("Goals").OfType().FirstOrDefault(x => Wire.Id(x["_id"]) == goalId) ?? throw new ApiException(400, "Unknown activity goal"); if (goal?.Value("Tag")?.StartsWith("MechSurvival", StringComparison.Ordinal) == true && info["GoalProgressAmount"] is not null) MissionSpecialRewards.Reward(rewards, "/Lotus/Types/Items/MiscItems/MechSurvivalEventCreds", (int)(info.Integer("GoalProgressAmount", 0, 1_000_000) / 10)); var keyMeta = GameData.Find("Keys", (goal is null ? null : EventApi.MissionKey(goal, info.Value("node"))) ?? body.Value("LevelKeyName")); if (keyMeta is not null) { if (keyMeta["missionReward"] is JObject fixedReward) completionCredits += FixedRewards(fixedReward, rewards, rotations); if (keyMeta["rewards"] is JArray keyRewards) completionCredits += KeyRewards(keyRewards, rewards); if (keyMeta["levelMission"] is JObject mission) completionCredits += CreditsForLevel(mission); } var completedNode = GameData.Find("Regions", body["Missions"]?.Value("Tag")); if (completedNode is not null) { if (rotations.Count > 0 && completedNode.Value("missionType") is not ("MT_JUNCTION" or "MT_LANDSCAPE") && body["Missions"]?.Value("Tag") is not ("SolNode761" or "SolNode762" or "SolNode763")) completionCredits += CreditsForLevel(completedNode); if (completedNode["missionReward"] is JObject reward) completionCredits += FixedRewards(reward, rewards, rotations); } if (info.Value("nightmareMode") && node is not null) { var system = node.Value("systemIndex"); var rotation = node.Value("missionType") == "MT_RESCUE" && info.Value("rewardTier") > 0 ? info.Value("rewardTier") : new[] { 6, 7, 8, 10, 11 }.Contains(system) ? 2 : new[] { 4, 9, 12, 14, 15, 16, 17, 18 }.Contains(system) ? 1 : 0; Roll("/Lotus/Types/Game/MissionDecks/NightmareModeRewards", [rotation], rewards); } var caches = info.Value("EnemyCachesFound"); if (caches > 0 && keyMeta?.Value("cacheRewardManifest") is string cacheTable) Roll(cacheTable, Enumerable.Range(0, Math.Min(caches, 3)).ToArray(), rewards, identified: true); if (caches > 0 && node?.Value("cacheRewardManifest") is string nodeCache) Roll(nodeCache, Enumerable.Range(0, Math.Min(caches, 3)).ToArray(), rewards, identified: true); var beforeRewards = inv.Value("RegularCredits"); MissionDrops.Relics(inv, GameVersion.For(account), rewards, rng); foreach (var reward in rewards.OfType()) Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItem"), (int)reward.Integer("ItemCount", 1, 100_000), premium: true)); var rngCredits = inv.Value("RegularCredits") - beforeRewards; var droppedCredits = body.Value("RegularCredits"); var today = clock.GetUtcNow().ToUnixTimeSeconds() / 86400 * 86400; var daily = account.Value("DailyFirstWinDate") != today; var bonus = completionCredits * (daily ? 2 : 1); var rawTotal = droppedCredits + bonus + rngCredits; var total = rawTotal; bool Booster(string kind) => inv.Array("Boosters").Any(x => x.Value("ItemType") == "/Lotus/Types/Boosters/" + kind && x.Value("ExpiryDate") > clock.GetUtcNow().ToUnixTimeSeconds()); if (Booster("CreditBooster")) total *= 2; if (Booster("CreditBlessing")) total = (long)Math.Round(total * 1.25, MidpointRounding.AwayFromZero); Inventory.ChangeCurrency(inv, "RegularCredits", checked(bonus + total - rawTotal)); if (daily) { account["DailyFirstWinDate"] = today; response["DailyMissionBonus"] = true; } response["MissionCredits"] = new JArray(droppedCredits, droppedCredits); response["CreditsBonus"] = new JArray(completionCredits, bonus); response["TotalCredits"] = new JArray(rawTotal, total); } else if (!failed) { MissionDrops.Stripped(inv, body, rewards, clock.GetUtcNow().ToUnixTimeMilliseconds()); MissionDrops.Relics(inv, GameVersion.For(account), rewards, new SeededRng(Wire.Seed())); foreach (var reward in rewards.OfType()) Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItem"), (int)reward.Integer("ItemCount", 1, 100_000), premium: true)); } new NemesisApi(catalog, clock).Mission(account, body, response, failed); if (body["duviriCaveOffers"] is not null && body.Value("MissionStatus") != "GS_QUIT") { inv.Obj("DuviriInfo")["Seed"] = Wire.Seed(); inv.Obj("DuviriInfo")["NumCompletions"] = checked(inv.Obj("DuviriInfo").Value("NumCompletions") + 1); } if (!failed) ApplyConservation(inv, body, (JArray)response["AffiliationMods"]!); if (!failed && body["VoidTearParticipantsCurrWave"] is JObject relicWave) new RelicApi(catalog, clock).CompleteMission(account, relicWave, rewards); if (!failed && inv.Value("pendingPremiumCredits") > 0) { InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Ordis", ["msg"] = "/Lotus/Language/Inbox/FoundItemsBody", ["sub"] = "/Lotus/Language/Inbox/FoundItemsTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Ordis.png", ["PremiumCredits"] = inv["pendingPremiumCredits"]!.DeepClone(), ["highPriority"] = true }, clock.GetUtcNow()); inv.Remove("pendingPremiumCredits"); } if (isFinal || body.Value("RJ")) inv["RewardSeed"] = Wire.Seed(); if (failed) response = new JObject { ["InventoryJson"] = Inventory.ExportForGame(account, state?["worldState"] as JObject).ToString(Formatting.None), ["MissionRewards"] = new JArray() }; else if (!new[] { "BMI", "TNT", "SSC", "RJ", "SS", "CMI", "EJC" }.Any(x => body.Value(x))) { if (info is null) response = new JObject(); response["InventoryJson"] = Inventory.ExportForGame(account, state?["worldState"] as JObject).ToString(Formatting.None); } var result = ApiResponse.Json(response); if (checkpoint) { account.Array("MissionReceipts").Add(MissionReceipts.Capture(replayKey, result)); while (account.Array("MissionReceipts").Count > 64) account.Array("MissionReceipts").RemoveAt(0); } return result; } private JObject ApplyInventory(JObject account, JObject body, JObject? state) { var inv = account.Obj("Inventory"); var delta = new JObject(); var acquire = new ItemAcquisition(catalog, clock, account); foreach (var update in (body["Upgrades"] as JArray ?? []).OfType()) { var type = update.RequiredString("ItemType"); var id = Wire.Id(update["ItemId"]); var fingerprintText = update.Value("UpgradeFingerprint") ?? "{}"; var fingerprint = fingerprintText.StartsWith('{') ? JObject.Parse(fingerprintText) : new JObject { ["lvl"] = int.TryParse(fingerprintText.Split('|')[0].Split('=').Last(), out var oldLevel) ? oldLevel : 0 }; if (id is "" or "000000000000000000000000") { if (fingerprint.Value("lvl") > 0 && type.StartsWith("/Lotus/Upgrades/Mods/Fusers/", StringComparison.Ordinal)) inv.Array("Upgrades").Add(new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None) }); else Inventory.AddCount(inv, "RawUpgrades", type, Math.Abs(update.Value("ItemCount") ?? 1)); } else { var owned = RivenApi.Owned(inv, update["ItemId"]); if (owned.Value("ItemType") != type) throw new ApiException(400, "Mismatched mission mod"); var current = JObject.Parse(owned.Value("UpgradeFingerprint") ?? "{}"); if (current["challenge"] is JObject challenge && fingerprint["challenge"] is JObject progress) { var count = progress.Value("Progress"); if (!double.IsFinite(count) || count < 0 || count > challenge.Value("Required")) throw new ApiException(400, "Invalid Riven challenge progress"); challenge["Progress"] = count; owned["UpgradeFingerprint"] = current.ToString(Formatting.None); } } } foreach (var key in Inventory.EquipmentKeys) if (body[key] is JArray gear) InventoryProgress.Equipment(inv, key, gear); if (body["RegularCredits"] is not null) Inventory.ChangeCurrency(inv, "RegularCredits", body.Integer("RegularCredits", -999_999_999)); if (body["QuestKeys"] is JArray quests) Inventory.Combine(delta, new QuestApi(catalog, clock).Update(account, quests)); if (body["Missions"] is JObject mission) InventoryProgress.Mission(inv, mission); if (body["AffiliationChanges"] is JArray affiliations) InventoryProgress.Affiliations(inv, affiliations); foreach (var category in Inventory.CountedKeys.Append("BonusMiscItems")) foreach (var item in (body[category] as JArray ?? []).OfType()) { var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", -999_999_999); var target = category == "BonusMiscItems" ? "MiscItems" : category; if (target == "Consumables" && count < 0 && inv.Value("dontSubtractConsumables")) continue; if (target == "MiscItems" && GameData.Find("Recipes", type) is not null) target = "Recipes"; if (target == "MiscItems") InventoryProgress.Misc(inv, type, count); else Inventory.AddCount(inv, target, type, count); } foreach (var fusion in (body["FusionBundles"] as JArray ?? []).OfType()) Inventory.Combine(delta, acquire.Add(inv, fusion.RequiredString("ItemType"), (int)fusion.Integer("ItemCount", 1, 100_000))); foreach (var type in body["CollectedQuestKeys"] as JArray ?? []) Inventory.Combine(delta, acquire.Add(inv, type.ToString())); foreach (var key in new[] { "EmailItems", "WeaponSkins" }) foreach (var item in (body[key] as JArray ?? []).OfType()) Inventory.Combine(delta, acquire.Add(inv, item.RequiredString("ItemType"))); foreach (var booster in (body["Boosters"] as JArray ?? []).OfType()) InventoryProgress.Booster(inv, booster.RequiredString("ItemType"), booster.Integer("ExpiryDate"), clock.GetUtcNow()); if (body["FocusXpIncreases"] is JArray focus) InventoryProgress.Focus(inv, focus); if (body["PlayerSkillGains"] is JObject skills) foreach (var key in new[] { "LPP_SPACE", "LPP_DRIFTER" }) if (skills[key] is not null) inv.Obj("PlayerSkills")[key] = checked(inv.Obj("PlayerSkills").Value(key) + skills.Integer(key)); if (body["LastRegionPlayed"] is JToken region) inv["LastRegionPlayed"] = region.DeepClone(); foreach (var (key, id) in new[] { ("EvolutionProgress", "ItemType"), ("CustomMarkers", "tag"), ("DiscoveredMarkers", "tag") }) foreach (var update in (body[key] as JArray ?? []).OfType()) Inventory.Upsert(inv.Array(key == "CollectibleScans" ? "CollectibleSeries" : key), id, update); foreach (var scan in (body["LoreFragmentScans"] as JArray ?? []).OfType()) { var entry = inv.Array("LoreFragmentScans").OfType().FirstOrDefault(x => x.Value("ItemType") == scan.Value("ItemType")); if (entry is null) inv.Array("LoreFragmentScans").Add(scan.DeepClone()); else entry["Progress"] = checked(entry.Value("Progress") + scan.Integer("Progress")); } foreach (var scan in (body["LibraryScans"] as JArray ?? []).OfType()) if (inv["LibraryActiveDailyTaskInfo"] is JObject task && (task["EnemyTypes"] as JArray ?? []).Any(x => x.ToString() == scan.Value("EnemyType"))) task["Scans"] = checked(task.Value("Scans") + scan.Integer("Count")); MissionState.Apply(account, body, delta, catalog, clock); if (body["KeyToRemove"] is JToken keyToRemove && inv.Value("dontSubtractKeys") != true && (body.Value("EndOfMatchUpload") ?? true) && (body["KeyOwner"] is null || Wire.Id(body["KeyOwner"]) == account.Value("id"))) Inventory.AddCount(inv, "LevelKeys", keyToRemove.ToString(), -1); if (body["creditsFee"] is not null && inv.Value("noNodeEntryFees") != true) Inventory.Combine(delta, Inventory.ChangeCurrency(inv, "RegularCredits", -body.Integer("creditsFee"))); if (body["Missions"] is JObject played && body.Value("EndOfMatchUpload") && GameData.Find("Regions", played.Value("Tag"))?["miscItemFee"] is JObject fee && inv.Value("noNodeEntryFees") != true) InventoryProgress.Misc(inv, fee.RequiredString("ItemType"), -fee.Integer("ItemCount")); var challengeResult = new ChallengeApi(catalog, clock).Apply(account, body, state); Inventory.Combine(delta, (JObject)challengeResult["InventoryChanges"]!); foreach (var (key, value) in new[] { ("CompletedSorties", body.Value("SortieId")), ("CompletedSyndicates", body.Value("SyndicateId")) }) if (!string.IsNullOrEmpty(value)) inv.Array(key).UniqueAdd(value); foreach (var property in body.Properties().Where(x => x.Name.StartsWith("DailyAffiliation", StringComparison.Ordinal))) inv[property.Name] = checked(inv.Value(property.Name) - property.Value.Value()); return delta; } private static void ApplyConservation(JObject inv, JObject body, JArray affiliations) { foreach (var animal in (body["CapturedAnimals"] as JArray ?? []).OfType()) { var meta = GameData.Find("Animals", animal.RequiredString("AnimalType"))?["conservation"] as JObject ?? throw new ApiException(400, "Unknown conservation animal"); var count = animal.Integer("Count", 1, 1000); var tags = animal["NumTags"] is null ? 0 : animal.Integer("NumTags", 0, 100); var extra = animal["NumExtraRewards"] is null ? 0 : animal.Integer("NumExtraRewards", 0, 100); if (tags > 0) InventoryProgress.Misc(inv, meta.RequiredString("itemReward"), checked(tags * count)); if (extra > 0 && meta.Value("woundedAnimalReward") is string item) InventoryProgress.Misc(inv, item, checked(extra * count)); if (meta.Value("standingReward") > 0) Standing.Add(inv, body["Missions"]?.Value("Tag") == "SolNode129" ? "SolarisSyndicate" : "CetusSyndicate", new[] { 2, 1.5, 1 }[(int)animal.Integer("CaptureRating", 0, 2)] * meta.Value("standingReward") * count, affiliations); } } public static IReadOnlyList Rotations(JObject info, JObject? node, int? tierOverride = null) { var vaults = info.Value("VaultsCracked"); if (vaults > 0) return Enumerable.Range(0, Math.Min(vaults, 3)).Select(x => Math.Min(x, 2)).ToArray(); var mission = node?.Value("missionType"); if (mission == "MT_ARTIFACT") return (info["rewardTierOverrides"] as JArray ?? []).Select(x => x.Value()).ToArray(); if (mission == "MT_RESCUE" && info["rewardTier"] is not null) return [info.Value("rewardTier")]; if (node?.Value("missionName") is "/Lotus/Language/Missions/MissionName_Railjack" or "/Lotus/Language/Missions/MissionName_RailjackVolatile" or "/Lotus/Language/Missions/MissionName_RailjackExterminate" or "/Lotus/Language/Missions/MissionName_RailjackAssassinate" or "/Lotus/Language/Missions/MissionName_Assassination" or "/Lotus/Language/Missions/MissionName_Exterminate") return [0]; var count = (info["rewardQualifications"] as JArray)?.Count ?? 0; if (count == 0 && mission is not ("MT_ENDLESS_EXTERMINATION" or "MT_RAILJACK")) return [0]; if (count > 1000) throw new ApiException(400, "Too many mission rotations"); int[] pattern = tierOverride is int tier ? [tier] : [0, 0, 1, 2]; return Enumerable.Range(0, count).Select(i => pattern[i % pattern.Length]).ToArray(); } private static long CreditsForLevel(JObject node) => node.Value("minEnemyLevel") is > 0 and var level ? 1000 + (level - 1) * 100L : 0; public static void Roll(string table, IReadOnlyList rotations, JArray rewards, SeededRng? rng = null, bool identified = false) { if (GameData.Table("Rewards")[table] is not JArray deck) throw new ApiException(400, "Unknown mission reward table"); foreach (var tier in rotations) { if (tier < 0 || tier >= deck.Count || deck[tier] is not JArray pool) throw new ApiException(400, "Invalid reward rotation"); var item = rng is null ? SeededRng.RewardAt(pool, Random.Shared.NextDouble()) : rng.Reward(pool); rng?.Float(); if (item is null) continue; var drop = new JObject { ["StoreItem"] = item["type"]!.DeepClone(), ["ItemCount"] = item["itemCount"]!.DeepClone() }; if (identified) drop["FromEnemyCache"] = true; rewards.Add(drop); } } public static long FixedRewards(JObject data, JArray rewards, IReadOnlyList? rotations = null) { foreach (var item in data["items"] as JArray ?? []) rewards.Add(new JObject { ["StoreItem"] = item.DeepClone(), ["ItemCount"] = 1 }); foreach (var item in data["countedItems"] as JArray ?? []) rewards.Add(new JObject { ["StoreItem"] = GameData.StoreType(item.Value("ItemType")!), ["ItemCount"] = item["ItemCount"]!.DeepClone() }); foreach (var item in data["countedStoreItems"] as JArray ?? []) rewards.Add(item.DeepClone()); if (data.Value("droptable") is string table) Roll(table, rotations ?? [0], rewards); return data.Value("credits"); } private static long KeyRewards(JArray data, JArray rewards) { var credits = 0L; foreach (var item in data) if (item.Value("rewardType") == "RT_CREDITS") credits += item.Value("amount"); else rewards.Add(new JObject { ["StoreItem"] = item["itemType"]!.DeepClone(), ["ItemCount"] = item.Value("rewardType") == "RT_RESOURCE" ? item.Value("amount") : 1 }); return credits; } }