using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class SyndicateApi(ItemCatalog catalog, TimeProvider clock) { public static readonly HashSet Controllers = ["syndicateSacrificeController", "syndicateStandingBonusController", "fishmongerController", "gildWeaponController", "hubBlessingController"]; public ApiResponse Handle(string controller, JObject account, ApiRequest request) { var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var delta = new JObject(); var affiliations = new JArray(); if (controller == "hubBlessingController") return Blessing(inv, request, body); if (controller == "syndicateSacrificeController") return Sacrifice(account, body); if (controller == "gildWeaponController") { var category = request.Q("Category") ?? ""; var gear = Inventory.Equipment(inv, category, request.Q("ItemId")); if (gear["ModularParts"] is not JArray || (gear.Value("Features") & 8) != 0) throw new ApiException(409, "Equipment is not an ungilded modular item"); var recipeType = body.RequiredString("Recipe"); var recipe = GameData.Find("Recipes", recipeType) ?? throw new ApiException(400, "Unknown gilding recipe"); if (!recipeType.Contains("Gild", StringComparison.OrdinalIgnoreCase) || recipe["secretIngredients"] is not JArray ingredients) throw new ApiException(400, "Not a gilding recipe"); foreach (var item in ingredients.OfType()) Consume(inv, delta, item.RequiredString("ItemType"), item.Integer("ItemCount", 1)); if (recipe["syndicateStandingChange"] is JObject cost) Standing.Spend(inv, cost.RequiredString("tag"), -cost.Integer("value", -999_999_999, 0), affiliations); gear["Features"] = gear.Value("Features") | 8; gear["ItemName"] = body.RequiredString("ItemName", 100); gear["XP"] = 0; if (category != "OperatorAmps" && body["PolarizeSlot"] is not null) gear["Polarity"] = new JArray(new JObject { ["Slot"] = body.Integer("PolarizeSlot", 0, 63), ["Value"] = body.RequiredString("PolarizeValue", 64) }); delta[category] = new JArray(gear.DeepClone()); return ApiResponse.Json(new JObject { ["InventoryChanges"] = delta, ["AffiliationMods"] = affiliations }); } string? tag = null; double standing = 0; if (controller == "fishmongerController") { foreach (var item in (body["Fish"] as JArray ?? throw new ApiException(400, "Missing fish")).OfType()) { var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 100_000); var meta = GameData.Find("Resources", type); if (meta?["dissectionParts"] is not JArray parts) throw new ApiException(400, "Not a fish"); Consume(inv, delta, type, count); if (request.Q("dissect") == "1") foreach (var part in parts.OfType()) Inventory.Combine(delta, new ItemAcquisition(catalog, clock, account).Add(inv, part.RequiredString("ItemType"), checked((int)(count * part.Integer("ItemCount", 1))))); else { var fishTag = meta.RequiredString("syndicateTag"); if (tag is not null && tag != fishTag) throw new ApiException(400, "Fish donation must belong to one syndicate"); tag = fishTag; standing += count * meta.Integer("standingBonus", 1); } } var gain = tag is null ? 0 : Standing.Add(inv, tag, standing, affiliations); var result = new JObject { ["InventoryChanges"] = delta, ["StandingChange"] = gain }; if (tag is not null) result["SyndicateTag"] = tag; return ApiResponse.Json(result); } var operation = body["Operation"] as JObject ?? body; tag = operation.RequiredString("AffiliationTag"); var syndicate = Standing.Metadata(tag); foreach (var item in (operation["Items"] as JArray ?? []).OfType()) { var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 100_000); var medallion = (syndicate["medallions"] as JArray)?.FirstOrDefault(x => x.Value("itemType") == type) ?? throw new ApiException(400, "Item cannot be donated to this syndicate"); standing += count * medallion.Value("standing"); Consume(inv, delta, type, count); } var id = Wire.Id(operation["ModularWeaponId"]); if (id is not ("" or "000000000000000000000000")) { if (standing != 0) throw new ApiException(400, "Cannot combine medallions and modular equipment"); var category = request.Q("Category"); if (category is not ("LongGuns" or "Pistols" or "Melee" or "OperatorAmps")) throw new ApiException(400, "Invalid modular equipment category"); var gear = Inventory.Equipment(inv, category, id); if (gear["ModularParts"] is not JArray parts || parts.Count == 0) throw new ApiException(400, "Not modular equipment"); foreach (var part in parts) standing += GameData.Find("Weapons", part.ToString())?.Value("donationStandingBonus") ?? throw new ApiException(400, "Part cannot be donated"); if ((gear.Value("Features") & 8) != 0) standing *= 2; gear.Remove(); var bin = Inventory.SlotFor(category)!; inv.Obj(bin)["Slots"] = inv.Obj(bin).Value("Slots") + 1; delta[bin] = new JObject { ["count"] = -1, ["platinum"] = 0, ["Slots"] = 1 }; delta["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = operation["ModularWeaponId"]!.DeepClone() }); } var gained = Standing.Add(inv, tag, standing, affiliations, 5); return ApiResponse.Json(new JObject { ["AffiliationTag"] = tag, ["StandingChange"] = gained, ["InventoryChanges"] = delta, ["AffiliationMods"] = affiliations }); } private void Consume(JObject inv, JObject delta, string type, long count) { var category = catalog.Get(type).Category; if (!Inventory.CountedKeys.Contains(category)) throw new ApiException(400, "Sacrifice requires a counted item"); Inventory.AddCount(inv, category, type, -count); Inventory.Combine(delta, new JObject { [category] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = -count }) }); } private ApiResponse Sacrifice(JObject account, JObject body) { var inv = account.Obj("Inventory"); var tag = body.RequiredString("AffiliationTag"); var meta = Standing.Metadata(tag); var affiliation = Standing.Affiliation(inv, tag); var old = affiliation.Value("Title"); var target = (int)body.Integer("SacrificeLevel", -2, 180); var increase = target - old; if (increase < 0 || increase > 1 && !body.Value("AllowMultiple")) throw new ApiException(400, "Invalid syndicate rank increase"); if (increase == 0 && (target != 0 || affiliation.Value("Initiated"))) throw new ApiException(409, "Rank reward already claimed"); if (target != 0 && Standing.Title(meta, target) is null) throw new ApiException(400, "Unknown syndicate rank"); if (target > 0 && affiliation.Value("Standing") < Standing.Minimum(meta, target)) throw new ApiException(400, "Insufficient standing for rank"); var delta = new JObject(); var episode = false; var acquire = new ItemAcquisition(catalog, clock, account); for (var level = old + Math.Min(increase, 1); level <= target; level++) { var title = Standing.Title(meta, level); var sacrifice = (level == 0 ? meta["initiationSacrifice"] : title?["sacrifice"]) as JObject; if (sacrifice is not null) { Inventory.Combine(delta, Inventory.ChangeCurrency(inv, "RegularCredits", -sacrifice.Integer("credits"))); foreach (var item in (sacrifice["items"] as JArray ?? []).OfType()) Consume(inv, delta, item.RequiredString("ItemType"), item.Integer("ItemCount", 1)); } if (level == 0) { affiliation["Initiated"] = true; if (meta.Value("initiationReward") is string reward) Inventory.Combine(delta, acquire.Add(inv, reward, premium: true)); } if (meta["dailyChallenges"] is JArray && title is not null) { var reward = title.Value("storeItemReward") ?? title["reward"]?.Value("ItemType"); if (reward is null) continue; var granted = acquire.Add(inv, reward, title["storeItemReward"] is null ? title["reward"]!.Value("ItemCount") : 1, premium: true); if (granted.Count == 0) granted = acquire.Add(inv, meta["titles"]![0]!["reward"]!.Value("ItemType")!, 50); Inventory.Combine(delta, granted); episode = true; } else if (level > 0 && (meta["favours"] as JArray ?? []).Any(x => x.Value("rankUpReward") && x.Value("requiredLevel") == level)) affiliation.Array("FreeFavorsEarned").UniqueAdd(level); } affiliation["Title"] = target < 0 ? target + 1 : target; return ApiResponse.Json(new JObject { ["AffiliationTag"] = tag, ["InventoryChanges"] = delta, ["Level"] = target, ["LevelIncrease"] = target < 0 ? 1 : increase, ["NewEpisodeReward"] = episode }); } private ApiResponse Blessing(JObject inv, ApiRequest request, JObject body) { var now = clock.GetUtcNow(); void Set(string store, long expiry) { var type = GameData.Find("Boosters", store)?.Value("typeName") ?? throw new ApiException(400, "Unknown blessing"); if (!type.EndsWith("Blessing", StringComparison.Ordinal)) throw new ApiException(400, "Not a relay blessing"); var booster = inv.Array("Boosters").OfType().FirstOrDefault(x => x.Value("ItemType") == type); if (booster is null) { booster = new JObject { ["ItemType"] = type }; inv.Array("Boosters").Add(booster); } booster["ExpiryDate"] = expiry; } if (request.Q("mode") == "send") { if (!inv.Value("noBlessingCooldown") && Wire.DateMs(inv["BlessingCooldown"]) > now.ToUnixTimeMilliseconds()) throw new ApiException(409, "Relay blessing is on cooldown"); Set(body.RequiredString("booster"), now.ToUnixTimeSeconds() + 10800); inv["BlessingCooldown"] = Wire.Date(inv.Value("noBlessingCooldown") ? 0 : now.AddHours(23).ToUnixTimeMilliseconds()); return ApiResponse.Json(new JObject { ["BlessingCooldown"] = inv["BlessingCooldown"]!.DeepClone(), ["SendTime"] = now.ToUnixTimeSeconds().ToString(), ["Expiry"] = (now.ToUnixTimeSeconds() + 10800).ToString(), ["Token"] = Convert.ToHexStringLower(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)) }); } if (body.Value("booster") is string legacy) { Set(legacy, now.ToUnixTimeSeconds() + 10800); return ApiResponse.Json(new JObject { ["BoosterType"] = legacy, ["Sender"] = body["senderId"]?.DeepClone() }); } foreach (var blessing in (body["PendingHubBlessings"] as JArray ?? []).OfType()) { var sent = long.Parse(blessing.RequiredString("sendTime"), System.Globalization.CultureInfo.InvariantCulture); if (sent > now.ToUnixTimeSeconds() + 60) throw new ApiException(400, "Invalid blessing time"); Set(blessing.RequiredString("booster"), sent + 10800); } return ApiResponse.Text(); } }