using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public static class Inventory { public static void Combine(JObject target, JObject delta) { foreach (var p in delta.Properties()) { if (target[p.Name] is null) target[p.Name] = p.Value.DeepClone(); else if (p.Value.Type == JTokenType.Integer) target[p.Name] = checked(target.Value(p.Name) + p.Value.Value()); else if (p.Value is JObject nested) Combine(target.Obj(p.Name), nested); else if (p.Value is JArray array) { foreach (var item in array) { var existing = item is JObject countItem && countItem["ItemCount"] is not null ? target.Array(p.Name).OfType().FirstOrDefault(x => x.Value("ItemType") == countItem.Value("ItemType") && JToken.DeepEquals(x["Sockets"], countItem["Sockets"])) : null; if (existing is null) target.Array(p.Name).Add(item.DeepClone()); else existing["ItemCount"] = checked(existing.Value("ItemCount") + item.Value("ItemCount")); } } else throw new ApiException(400, $"Cannot combine inventory delta {p.Name}"); } } public static string? SlotFor(string category) => category switch { "Suits" => "SuitBin", "LongGuns" or "Pistols" or "Melee" => "WeaponBin", "Sentinels" or "SentinelWeapons" or "KubrowPets" or "MoaPets" => "SentinelBin", "SpaceSuits" or "Hoverboards" => "SpaceSuitBin", "SpaceGuns" or "SpaceMelee" => "SpaceWeaponBin", "OperatorAmps" or "Antiques" => "OperatorAmpBin", "MechSuits" => "MechBin", "CrewMembers" => "CrewMemberBin", "CrewShipWeapons" or "CrewShipWeaponSkins" => "CrewShipSalvageBin", _ => null }; public static JObject OccupySlots(JObject inv, string category, int count, bool premium) { if (SlotFor(category) is not string bin) return new(); var slots = inv.Obj(bin); if (!premium && slots.Value("Slots") < count) throw new ApiException(409, "No free inventory slots"); if (premium) slots["Extra"] = slots.Value("Extra") + count; else slots["Slots"] = slots.Value("Slots") - count; return new JObject { [bin] = new JObject { ["Slots"] = premium ? 0 : -count, ["Extra"] = premium ? count : 0 } }; } public static void FreeSlot(JObject inv, string category) { if (SlotFor(category) is string bin) inv.Obj(bin)["Slots"] = checked(inv.Obj(bin).Value("Slots") + 1); } public static void RequireNotInResearch(JObject inv, string id) { if (inv.Array("PersonalTechProjects").Any(x => Wire.Id(x["CategoryItemId"]) == id)) throw new ApiException(409, "Cancel or finish this item's research project first"); } public static readonly string[] EquipmentKeys = ["Suits", "LongGuns", "Pistols", "Melee", "Sentinels", "SentinelWeapons", "SpaceSuits", "SpaceGuns", "SpaceMelee", "Hoverboards", "OperatorAmps", "MechSuits", "KubrowPets", "MoaPets", "SpecialItems", "DataKnives", "Scoops", "Horses", "Motorcycles", "OperatorSuits", "DrifterWeapons", "DrifterMelee", "Antiques", "Drones", "Ships", "CrewShips", "CrewShipHarnesses", "CrewMembers", "CrewShipWeapons", "CrewShipWeaponSkins", "CrewShipSalvagedWeapons", "CrewShipSalvagedWeaponSkins"]; public static readonly string[] LoadoutKeys = ["NORMAL", "SENTINEL", "ARCHWING", "NORMAL_PVP", "LUNARO", "OPERATOR", "GEAR", "KDRIVE", "DATAKNIFE", "MECH", "OPERATOR_ADULT", "DRIFTER"]; public static readonly string[] CountedKeys = ["MiscItems", "RawUpgrades", "Recipes", "Consumables", "LevelKeys", "ShipDecorations", "CrewShipRawSalvage", "CrewShipAmmo", "VoidProjections"]; public static readonly string[] CurrencyKeys = ["RegularCredits", "PremiumCredits", "FusionPoints", "CrewShipFusionPoints", "PrimeTokens"]; public static JObject New() { var inv = (JObject)Assets.Json("inventory-defaults.json"); foreach (var key in EquipmentKeys.Concat(CountedKeys)) inv.Array(key); inv["TrainingDate"] = Wire.Date(0); inv["RewardSeed"] = Wire.Seed(); inv["ActiveQuest"] = ""; inv["ShipDecorations"] = new JArray(); inv["Ships"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = "/Lotus/Types/Items/Ships/DefaultShip", ["ShipExterior"] = new JObject() }); return inv; } public static JObject Export(JObject account) { var result = (JObject)account.Obj("Inventory").DeepClone(); foreach (var pending in (result["PendingRecipes"] as JArray ?? []).OfType()) foreach (var field in new[] { "OwnedRecipeType", "PaidCredits", "ConsumedCounted", "ConsumedEquipment", "CystSuit", "CystDate", "DeferredPetDefaults", "PetPrintDetails", "SuitToUnbrand" }) pending.Remove(field); result["LoadOutPresets"] = account.Obj("Loadouts").DeepClone(); foreach (var p in account.Obj("PersonalRooms").Properties()) result[p.Name] = p.Value.DeepClone(); return result; } public static JObject ExportForGame(JObject account, JObject? world = null, bool masteryPatched = false) { var result = Export(account); var build = GameVersion.For(account); InfestationKing.Project(result); FetchOverdrive.Project(result); AccountRules.Project(result, build, world, masteryPatched); if (result["Nemesis"] is JObject nemesis) result["Nemesis"] = NemesisData.ForGame(nemesis); if (result["NemesisHistory"] is JArray history) for (var i = 0; i < history.Count; i++) if (history[i] is JObject past) history[i] = NemesisData.ForGame(past); // Administrative backups retain server fields. Only the game wire format // is projected here, so importing/exporting a save never loses progress. foreach (var room in account.Obj("PersonalRooms").Properties()) result.Remove(room.Name); if (build < GameVersion.Of("22.13.4")) result["Ship"] = account.Obj("PersonalRooms")["Ship"]?.DeepClone(); foreach (var ship in result.Array("Ships").OfType()) if (ship.Value("ItemType") == "/Lotus/Types/Items/Ships/Liset") ship["ItemType"] = "/Lotus/Types/Items/Ships/DefaultShip"; if (result["DrifterWeapons"] is JArray drifter) foreach (var item in drifter) result.Array("DrifterGuns").Add(item.DeepClone()); result.Remove("DrifterWeapons"); if (result["VoidProjections"] is JArray relics) foreach (var relic in relics.OfType()) AddCount(result, "MiscItems", relic.RequiredString("ItemType"), relic.Value("ItemCount")); result.Remove("VoidProjections"); foreach (var treasure in result.Array("HybridFusionTreasures").OfType()) { var type = treasure.RequiredString("ItemType"); var sockets = treasure.Value("Sockets"); var existing = result.Array("FusionTreasures").OfType().FirstOrDefault(x => x.Value("ItemType") == type && x.Value("Sockets") == sockets); if (existing is null) result.Array("FusionTreasures").Add(new JObject { ["ItemType"] = type, ["Sockets"] = sockets, ["ItemCount"] = 1 }); else existing["ItemCount"] = checked(existing.Value("ItemCount") + 1); } result.Remove("HybridFusionTreasures"); if (build >= GameVersion.August2026) { result.Remove("ChallengeProgress"); result.Remove("PetBin"); result.Remove("MadeStoryModeDecision"); result.Remove("Mailbox"); result.Obj("LoadOutPresets").Remove("GEAR"); } return result; } public static void Import(JObject account, JObject upload) { var data = (JObject)upload.DeepClone(); foreach (var key in new[] { "id", "_id", "accountOwnerId", "password", "credential", "Nonce", "GuildId" }) data.Remove(key); if (data["LoadOutPresets"] is JObject loadouts) { account["Loadouts"] = loadouts.DeepClone(); data.Remove("LoadOutPresets"); } foreach (var key in new[] { "Ship", "Apartment", "TailorShop" }) if (data[key] is JObject room) { account.Obj("PersonalRooms")[key] = room.DeepClone(); data.Remove(key); } foreach (var key in CurrencyKeys.Append("PremiumCreditsFree")) if (data.ContainsKey(key)) data.Integer(key); foreach (var key in EquipmentKeys.Concat(CountedKeys)) if (data.ContainsKey(key) && data[key] is not JArray) throw new ApiException(400, $"{key} must be an array"); foreach (var suit in (data["Suits"] as JArray ?? []).OfType()) foreach (var config in (suit["Configs"] as JArray ?? []).OfType()) if (config.ContainsKey(ExperimentalAbilities.BanksField)) ExperimentalAbilities.SetBanks(config, config[ExperimentalAbilities.BanksField] as JObject ?? throw new ApiException(400, "技能组格式无效。")); else if (config.ContainsKey(ExperimentalAbilities.Field)) ExperimentalAbilities.Set(config, config[ExperimentalAbilities.Field] as JObject ?? throw new ApiException(400, "多技能配置格式无效。")); account.Obj("Inventory").Merge(data, new() { MergeArrayHandling = Newtonsoft.Json.Linq.MergeArrayHandling.Replace }); ShipFeatureProgress.RestoreCompletedQuests(account); } public static JObject ChangeCurrency(JObject inv, string key, long delta, bool applyRules = true) { if (!CurrencyKeys.Contains(key)) throw new ApiException(400, "Unknown currency"); if (applyRules && delta < 0 && AccountRules.InfiniteCurrency(inv, key)) return new JObject { [key] = 0 }; var balance = checked(inv.Value(key) + delta); if (balance is < 0 or > 999_999_999) throw new ApiException(400, "Insufficient currency or balance overflow"); inv[key] = balance; var changes = new JObject { [key] = delta }; if (key == "PremiumCredits" && delta < 0) { var freeUsed = Math.Min(inv.Value("PremiumCreditsFree"), -delta); inv["PremiumCreditsFree"] = inv.Value("PremiumCreditsFree") - freeUsed; changes["PremiumCreditsFree"] = -freeUsed; } return changes; } public static JObject AddItem(JObject inv, string category, string type, int count) { if (type == InfestationKing.Type && category is "RawUpgrades" or "Upgrades") return InfestationKing.Add(inv, count); if (type == XFEWarframe.Mods.PetFetchMod.Type && category is "RawUpgrades" or "Upgrades") return FetchOverdrive.Add(inv, count); if (!type.StartsWith("/Lotus/", StringComparison.Ordinal) || type.Length > 512 || count is < 1 or > 100_000) throw new ApiException(400, "Invalid item or count"); if (EquipmentKeys.Contains(category)) { if (count > 100) throw new ApiException(400, "At most 100 equipment items per request"); var added = new JArray(); for (var i = 0; i < count; i++) { var item = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["XP"] = 0, ["Features"] = 0, ["UpgradeVer"] = 101, ["Configs"] = new JArray(), ["IsNew"] = true }; inv.Array(category).Add(item); added.Add(item.DeepClone()); } return new JObject { [category] = added }; } if (!CountedKeys.Contains(category)) throw new ApiException(400, "Unknown item category"); AddCount(inv, category, type, count); return new JObject { [category] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = count }) }; } public static void AddCount(JObject inv, string category, string type, long delta) { var items = inv.Array(category); var item = items.OfType().FirstOrDefault(x => x.Value("ItemType") == type); var total = checked((item?.Value("ItemCount") ?? 0) + delta); if (total < 0 || total > 999_999_999) throw new ApiException(400, "Insufficient items or item count overflow"); if (item is null && total > 0) items.Add(new JObject { ["ItemType"] = type, ["ItemCount"] = total }); else if (item is not null) { if (total == 0) item.Remove(); else item["ItemCount"] = total; } } public static JObject Equipment(JObject inv, string? category, string? id) { if (category is null || !EquipmentKeys.Contains(category)) throw new ApiException(400, "Unknown equipment category"); return inv.Array(category).OfType().FirstOrDefault(x => Wire.Id(x["ItemId"]) == id) ?? throw new ApiException(404, "Equipment not found"); } public static JObject StartingGear(JObject inv, JObject body) { if (inv.Value("ReceivedStartingGear") == true) throw new ApiException(409, "Account already received starting gear"); var defaults = new Dictionary { ["LongGuns"] = "/Lotus/Weapons/Tenno/Rifle/Rifle", ["Pistols"] = "/Lotus/Weapons/Tenno/Pistol/Pistol", ["Suits"] = "/Lotus/Powersuits/Excalibur/Excalibur", ["Melee"] = "/Lotus/Weapons/Tenno/Melee/LongSword/LongSword", ["DataKnives"] = "/Lotus/Weapons/Tenno/HackingDevices/TnHackingDevice/TnHackingDeviceWeapon", ["Scoops"] = "/Lotus/Weapons/Tenno/Speedball/SpeedballWeaponTest" }; var changes = new JObject(); foreach (var (category, type) in defaults) changes.Merge(AddItem(inv, category, body[category]?[0]?.Value("ItemType") ?? type, 1)); inv["ReceivedStartingGear"] = true; inv["ActiveQuest"] = "/Lotus/Types/Keys/VorsPrize/VorsPrizeQuestKeyChain"; inv.Array("QuestKeys").Add(new JObject { ["ItemType"] = inv["ActiveQuest"], ["Progress"] = new JArray() }); // Preserve balances granted before the first game login. var credits = Math.Min(3000, 999_999_999 - inv.Value("RegularCredits")); var platinum = Math.Min(50, 999_999_999 - inv.Value("PremiumCredits")); inv["RegularCredits"] = inv.Value("RegularCredits") + credits; inv["PremiumCredits"] = inv.Value("PremiumCredits") + platinum; inv["PremiumCreditsFree"] = inv.Value("PremiumCreditsFree") + platinum; changes["RegularCredits"] = credits; changes["PremiumCredits"] = platinum; changes["PremiumCreditsFree"] = platinum; inv.Obj("SuitBin")["Slots"] = inv.Obj("SuitBin").Value("Slots") - 1; inv.Obj("WeaponBin")["Slots"] = inv.Obj("WeaponBin").Value("Slots") - 3; changes["SuitBin"] = new JObject { ["count"] = 1, ["platinum"] = 0, ["Slots"] = -1 }; changes["WeaponBin"] = new JObject { ["count"] = 3, ["platinum"] = 0, ["Slots"] = -3 }; return changes; } public static void Upsert(JArray array, string key, JObject upload) { var id = upload[key] ?? throw new ApiException(400, $"Missing {key}"); var existing = array.OfType().FirstOrDefault(x => JToken.DeepEquals(x[key], id)); if (existing is null) array.Add(upload.DeepClone()); else existing.Merge(upload, new() { MergeArrayHandling = Newtonsoft.Json.Linq.MergeArrayHandling.Replace }); } }