using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class RailjackApi { public static readonly HashSet Controllers = ["crewMembersController", "crewShipIdentifySalvageController", "crewShipFusionController"]; public ApiResponse Handle(string controller, JObject account, ApiRequest request) { var inv = account.Obj("Inventory"); var body = request.ObjectBody(); if (controller == "crewMembersController") return Crew(inv, body); if (controller == "crewShipFusionController") return Fuse(inv, body); var type = body.RequiredString("ItemType"); var custom = GameData.Find("Customs", type); var weapon = GameData.Find("RailjackWeapons", type); if (custom?.Value("productCategory") != "CrewShipWeaponSkins" && weapon is null) throw new ApiException(400, "Unknown salvage"); Inventory.AddCount(inv, "CrewShipRawSalvage", type, -1); var category = weapon is null ? "CrewShipSalvagedWeaponSkins" : "CrewShipSalvagedWeapons"; var changes = Inventory.AddItem(inv, category, type, 1); var item = Inventory.Equipment(inv, category, Wire.Id(changes[category]![0]!["ItemId"])); var fingerprint = new JObject { ["compat"] = type, ["buffs"] = new JArray() }; JArray modifiers; if (custom is not null) { if (custom["subroutines"] is JArray routines && routines.Count > 0) fingerprint["SubroutineIndex"] = Random.Shared.Next(routines.Count); modifiers = (JArray?)custom["randomisedUpgrades"] ?? []; } else { var upgrade = weapon!["defaultUpgrades"]?.FirstOrDefault()?.Value("ItemType"); if (upgrade is not null) item["UpgradeType"] = upgrade; modifiers = (JArray?)GameData.Find("Upgrades", upgrade)?["upgradeEntries"] ?? []; } foreach (var entry in modifiers) ((JArray)fingerprint["buffs"]!).Add(new JObject { ["Tag"] = entry["tag"]!.DeepClone(), ["Value"] = Random.Shared.Next(0x40000000) }); item["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None); changes[category] = new JArray(item.DeepClone()); changes["CrewShipRawSalvage"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = -1 }); return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes }); } private static ApiResponse Crew(JObject inv, JObject body) { var upload = body["crewMember"] as JObject ?? throw new ApiException(400, "Missing crew member"); var id = Wire.Id(upload["ItemId"]); JObject crew; if (id == new string('0', 24)) crew = inv.Array("NemesisHistory").OfType().FirstOrDefault(x => x["fp"]?.ToString() == upload["NemesisFingerprint"]?.ToString() && !x.Value("k")) ?? throw new ApiException(404, "Converted nemesis is not owned"); else crew = Inventory.Equipment(inv, "CrewMembers", id); if (upload.Value("SecondInCommand")) foreach (var member in inv.Array("CrewMembers").Concat(inv.Array("NemesisHistory")).OfType()) member["SecondInCommand"] = false; if (id != new string('0', 24)) { if (upload["WeaponId"] is not null && Wire.Id(upload["WeaponId"]) != new string('0', 24) && !new[] { "LongGuns", "Pistols" }.Any(category => inv.Array(category).Any(x => Wire.Id(x["ItemId"]) == Wire.Id(upload["WeaponId"])))) throw new ApiException(404, "Crew weapon is not owned"); if (upload["SkillEfficiency"] is JObject skills && (skills.Properties().Any(x => x.Value.Value("Assigned") is < 0 or > 5) || skills.Properties().Sum(x => x.Value.Value("Assigned")) > Math.Min(3, inv.Obj("PlayerSkills").Value("LPS_COMMAND")))) throw new ApiException(400, "Invalid assigned crew skill points"); foreach (var field in new[] { "AssignedRole", "SkillEfficiency", "WeaponConfigIdx", "WeaponId", "Configs" }) if (upload[field] is JToken value) crew[field] = value.DeepClone(); } crew["SecondInCommand"] = upload.Value("SecondInCommand"); return ApiResponse.Json(new JObject { ["crewMemberId"] = id, ["NemesisFingerprint"] = upload["NemesisFingerprint"]?.DeepClone() }); } private static ApiResponse Fuse(JObject inv, JObject body) { var aId = Wire.Id(body["PartA"]); var bId = Wire.Id(body["PartB"]); if (aId == bId) throw new ApiException(400, "Fusion needs two different parts"); Inventory.RequireNotInResearch(inv, aId); Inventory.RequireNotInResearch(inv, bId); var isWeapon = inv.Array("CrewShipWeapons").Any(x => Wire.Id(x["ItemId"]) == aId); var category = isWeapon ? "CrewShipWeapons" : "CrewShipWeaponSkins"; var salvageCategory = isWeapon ? "CrewShipSalvagedWeapons" : "CrewShipSalvagedWeaponSkins"; var recipeType = body.Value("SourceRecipe"); var useSalvage = !string.IsNullOrEmpty(recipeType); var a = Inventory.Equipment(inv, category, aId); var b = Inventory.Equipment(inv, useSalvage ? salvageCategory : category, bId); var aType = a.RequiredString("ItemType"); var bType = b.RequiredString("ItemType"); var tierA = aType[^1] - 'A'; var tierB = bType[^1] - 'A'; if (tierA is < 0 or > 2 || tierB is < 0 or > 2 || a["UpgradeFingerprint"] is null) throw new ApiException(400, "Parts cannot be fused"); var metaA = GameData.Find(isWeapon ? "RailjackWeapons" : "Customs", aType) ?? throw new ApiException(400, "Unknown fusion part"); var metaB = GameData.Find(isWeapon ? "RailjackWeapons" : "Customs", bType) ?? throw new ApiException(400, "Unknown fusion part"); if (aType[..^1] != bType[..^1]) throw new ApiException(400, "Fusion parts must share their family and manufacturer"); var changes = new JObject(); if (useSalvage) { var recipe = GameData.Table("DojoRecipes")["research"]?[recipeType!] as JObject ?? throw new ApiException(400, "Unknown salvage repair recipe"); if (recipe.Value("resultType") != bType) throw new ApiException(400, "Repair recipe does not match salvage"); Inventory.Combine(changes, Inventory.ChangeCurrency(inv, "RegularCredits", -(long)Math.Floor(recipe.Value("price") * .4 + .5))); foreach (var part in (recipe["ingredients"] as JArray ?? []).OfType()) { var count = (int)Math.Floor(part.Value("ItemCount") * .4 + .5); Inventory.AddCount(inv, "MiscItems", part.RequiredString("ItemType"), -count); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = part["ItemType"]!.DeepClone(), ["ItemCount"] = -count }) }); } } var superior = tierA < tierB ? b : a; var inferior = tierA < tierB ? a : b; var fingerprint = JObject.Parse(superior.RequiredString("UpgradeFingerprint")); var other = inferior["UpgradeFingerprint"] is null ? new JObject { ["buffs"] = new JArray() } : JObject.Parse(inferior.RequiredString("UpgradeFingerprint")); var upperMeta = tierA < tierB ? metaB : metaA; var lowerMeta = tierA < tierB ? metaA : metaB; foreach (var buff in fingerprint.Array("buffs").OfType()) { var second = other.Array("buffs").FirstOrDefault(x => x.Value("Tag") == buff.Value("Tag")); if (second is null && !isWeapon) continue; var upperRange = (upperMeta["randomisedUpgrades"] as JArray)?.FirstOrDefault(x => x.Value("tag") == buff.Value("Tag"))?["range"] as JArray; var lowerRange = (lowerMeta["randomisedUpgrades"] as JArray)?.FirstOrDefault(x => x.Value("tag") == buff.Value("Tag"))?["range"] as JArray; var minA = isWeapon ? .3 : upperRange?[0]?.Value() ?? throw new ApiException(400, "Unknown component stat range"); var maxA = isWeapon ? .6 : upperRange![1].Value(); var minB = isWeapon ? .3 : lowerRange?[0]?.Value() ?? minA; var maxB = isWeapon ? .6 : lowerRange?[1]?.Value() ?? maxA; var valueA = minA + buff.Value("Value") / 0x3fffffff * (maxA - minA); var valueB = minB + (second?.Value("Value") ?? 0) / 0x3fffffff * (maxB - minB); var combined = Math.Min(maxA, Math.Max(valueA, valueB) * new[] { 1.1, 1.05, 1.02 }[Math.Abs(tierA - tierB)]); buff["Value"] = maxA == minA ? 0 : (long)(Math.Clamp((combined - minA) / (maxA - minA), 0, 1) * 0x3fffffff); } if (!isWeapon && other["SubroutineIndex"] is JToken routine && !(tierA < tierB ? !body.Value("UseSubroutineA") : body.Value("UseSubroutineA"))) fingerprint["SubroutineIndex"] = routine.DeepClone(); JObject destination; if (useSalvage) { // Preserve the installed component's identity when its upgrade comes from unrepaired salvage. destination = a; if (ReferenceEquals(superior, b)) { destination["ItemType"] = b["ItemType"]!.DeepClone(); if (b["UpgradeType"] is JToken upgrade) destination["UpgradeType"] = upgrade.DeepClone(); } b.Remove(); changes["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(bId) }); } else { destination = superior; var removed = Wire.Id(inferior["ItemId"]); inferior.Remove(); changes["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(removed) }); inv.Obj("CrewShipSalvageBin")["Slots"] = inv.Obj("CrewShipSalvageBin").Value("Slots") + 1; changes["CrewShipSalvageBin"] = new JObject { ["count"] = -1, ["platinum"] = 0, ["Slots"] = 1 }; } destination["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None); changes[category] = new JArray(destination.DeepClone()); return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes }); } }