XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

public sealed class DojoApi(ItemCatalog catalog, TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["createGuildDojoController", "getGuildDojoController", "startDojoRecipeController", "contributeToDojoComponentController", "dojoComponentRushGetController", "dojoComponentRushPostController", "abortDojoComponentGetController", "abortDojoComponentPostController", "queueDojoComponentDestructionController", "abortDojoComponentDestructionController", "changeDojoRootController", "changeDojoSpawnRoomController", "setDojoComponentMessageController", "setDojoComponentSettingsController", "setDojoComponentColorsController", "placeDecoInComponentController", "destroyDojoDecoController", "reduceGuildTierController", "startGuildRecipeController"];
    public static JObject Component(JObject guild, string? id) => guild.Array("DojoComponents").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["id"]) == id) ?? throw new ApiException(404, "Dojo room not found");
    private static JObject Deco(JObject room, string id) => room.Array("Decos").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["id"]) == id) ?? throw new ApiException(404, "Dojo decoration not found");
    public static JObject? Metadata(string category, string type) => (GameData.Table("DojoRecipes")[category] as JObject)?.Properties().Select(x => x.Value).OfType<JObject>().FirstOrDefault(x => x.Value<string>("resultType") == type);
    public static int Tier(string? prefab) => prefab?.Split('/').Last() switch { "ClanDojoBarracksShadow.level" => 2, "ClanDojoBarracksStorm.level" => 3, "ClanDojoBarracksMountain.level" => 4, "ClanDojoBarracksMoon.level" => 5, _ => 0 };
    public static void Decorator(JObject guild, JObject account, JObject room)
    {
        if (GuildApi.Allowed(guild, account, 1024)) return; var settings = room.Value<string>("Settings"); if (settings is not null && JObject.Parse(settings)["decorators"] is JArray people && people.Any(x => x.ToString() == account.Value<string>("id"))) return; throw new ApiException(403, "Room decoration permission is required");
    }
    public ApiResponse Handle(string controller, JObject state, JObject account, ApiRequest request)
    {
        var body = request.ObjectBody(); var build = GameVersion.For(account);
        if (controller == "getGuildDojoController") { var target = GuildApi.Find(state, request.Q("guildId") ?? Wire.Id(account.Obj("Inventory")["GuildId"])) ?? throw new ApiException(404, "Dojo not found"); return ApiResponse.Json(Client(state, target, build, body.Value<string>("ComponentId") ?? request.Q("componentId"))); }
        var guild = GuildApi.Own(state, account, request.Q("guildId")); Refresh(state, guild); var changes = new JObject(); var now = clock.GetUtcNow().ToUnixTimeMilliseconds();
        if (controller == "createGuildDojoController")
        {
            GuildApi.Require(guild, account, 16); if (guild.Array("DojoComponents").Count == 0)
            {
                var prefab = body["SpawnComponent"]?.Value<string>("pf"); if (prefab is not ("/Lotus/Levels/ClanDojo/DojoHall.level" or "/Lotus/Levels/ClanDojo/ClanHallA.level")) throw new ApiException(400, "Invalid dojo spawn hall");
                guild.Array("DojoComponents").Add(new JObject { ["id"] = Wire.Oid(Wire.NewId()), ["pf"] = "/Lotus/Levels/ClanDojo/DojoHall.level", ["ppf"] = "", ["CompletionTime"] = Wire.Date(now - 2000), ["DecoCapacity"] = 600, ["Decos"] = new JArray() });
            }
            return ApiResponse.Json(Client(state, guild, build));
        }
        ResearchApi.Access(account);
        if (controller == "startDojoRecipeController")
        {
            GuildApi.Require(guild, account, 16); var placed = body["PlacedComponent"] as JObject ?? throw new ApiException(400, "Missing dojo room placement"); var prefab = placed.RequiredString("pf"); var meta = Metadata("rooms", prefab) ?? throw new ApiException(400, "Unknown dojo room"); var parent = Component(guild, Wire.Id(placed["pi"]));
            if (parent["CompletionTime"] is null || Wire.DateMs(parent["CompletionTime"]) > now || parent["DestructionTime"] is not null) throw new ApiException(409, "Parent room is not available for construction");
            if (Tier(prefab) > 0 && Wire.DateMs(guild["GuildTierIncMoratorium"]) > now) throw new ApiException(409, "Clan tier increase is on cooldown");
            var capacity = guild.Value<int>("DojoCapacity") + meta.Value<int>("capacity"); var energy = guild.Value<int>("DojoEnergy") + meta.Value<int>("energy"); if (capacity < 0 || energy < 0) throw new ApiException(409, "Insufficient dojo capacity or energy");
            if (guild.Array("DojoComponents").Any(x => Wire.Id(x["pi"]) == Wire.Id(parent["id"]) && x.Value<string>("pp") == placed.Value<string>("pp"))) throw new ApiException(409, "Parent room connector is occupied");
            var room = new JObject { ["id"] = Wire.Oid(Wire.NewId()), ["pf"] = prefab, ["ppf"] = parent["pf"]!.DeepClone(), ["pi"] = parent["id"]!.DeepClone(), ["op"] = placed.RequiredString("op"), ["pp"] = placed.RequiredString("pp"), ["DecoCapacity"] = meta.Value<int?>("decoCapacity") ?? 600, ["Decos"] = new JArray(), ["RegularCredits"] = 0, ["MiscItems"] = new JArray() };
            guild.Array("DojoComponents").Add(room); guild["DojoCapacity"] = capacity; guild["DojoEnergy"] = energy; new GuildApi(clock).Log(guild, "RoomChanges", 2, prefab);
            if (guild.Value<bool>("noDojoRoomBuildStage")) { room["CompletionTime"] = Wire.Date(now); GrantXp(guild, meta); } return ApiResponse.Json(Client(state, guild, build));
        }
        if (controller == "changeDojoRootController")
        {
            GuildApi.Require(guild, account, 16); Reparent(guild, request.Q("newRoot") ?? body.Value<string>("newRoot") ?? ""); return ApiResponse.Json(Client(state, guild, build));
        }
        if (controller == "changeDojoSpawnRoomController") { GuildApi.Require(guild, account, 16); if (guild.Array("DojoComponents").Count != 1) throw new ApiException(409, "Changing the spawn hall requires a single-room dojo"); guild["DojoComponents"]![0]!["pf"] = "/Lotus/Levels/ClanDojo/DojoHall.level"; return ApiResponse.Json(Client(state, guild, build)); }
        if (controller == "reduceGuildTierController")
        {
            GuildApi.Require(guild, account, 1); if (!int.TryParse(request.Q("newTier"), out var tier) || tier < 1 || tier >= guild.Value<int>("Tier")) throw new ApiException(400, "Invalid reduced clan tier");
            if (guild.Array("Members").Count(x => x.Value<int>("status") == 0) > new[] { 10, 30, 100, 300, 1000 }[tier - 1]) throw new ApiException(409, "Member count exceeds the new clan tier capacity");
            new ResearchApi(catalog, clock).ChangeTier(state, guild, tier); guild["GuildTierIncMoratorium"] = Wire.Date(clock.GetUtcNow().AddDays(60).ToUnixTimeMilliseconds()); return ApiResponse.Json(new { NewTier = tier });
        }
        var componentId = body.Value<string>("ComponentId") ?? body.Value<string>("componentId") ?? body.Value<string>("ParentRoom") ?? request.Q("componentId"); var roomTarget = Component(guild, componentId); var decoId = body.Value<string>("DecoId") ?? body.Value<string>("decoId") ?? request.Q("decoId");
        if (controller == "startGuildRecipeController")
        {
            GuildApi.Require(guild, account, 256); if (body.Value<bool>("Alliance")) return ApiResponse.Json(new { DojoRequestStatus = -1 }); if (guild.Array("VaultPendingRecipes").Any(x => Wire.Id(x["ParentRoom"]) == componentId)) throw new ApiException(409, "Room is already crafting");
            var type = body.RequiredString("Recipe"); if (!guild.Array("VaultRecipes").Any(x => x.Value<string>("ItemType") == type && x.Value<int>("ItemCount") > 0)) throw new ApiException(400, "Clan does not own this blueprint"); var recipe = GameData.Find("Recipes", type) ?? throw new ApiException(400, "Unknown clan recipe");
            guild.Array("VaultPendingRecipes").Add(new JObject { ["ParentRoom"] = roomTarget["id"]!.DeepClone(), ["ParentGuildId"] = Wire.Oid(guild.RequiredString("id")), ["Type"] = recipe["resultType"]!.DeepClone(), ["RecipeType"] = type }); return ApiResponse.Json(Client(state, guild, build));
        }
        if (controller == "contributeToDojoComponentController" || controller.StartsWith("dojoComponentRush", StringComparison.Ordinal))
        {
            JObject contributionTarget; JObject meta; var unscaled = body["ResultType"] is not null;
            if (unscaled) { contributionTarget = guild.Array("VaultPendingRecipes").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ParentRoom"]) == componentId && x.Value<string>("Type") == body.Value<string>("ResultType")) ?? throw new ApiException(404, "Clan crafting project not found"); var recipe = GameData.Find("Recipes", contributionTarget.RequiredString("RecipeType"))!; meta = new JObject { ["price"] = recipe.Value<long>("buildPrice"), ["time"] = recipe.Value<long>("buildTime"), ["skipTimePrice"] = recipe.Value<long>("skipBuildTimePrice"), ["ingredients"] = recipe["ingredients"]!.DeepClone(), ["resultType"] = recipe["resultType"]!.DeepClone() }; }
            else { contributionTarget = decoId is null ? roomTarget : Deco(roomTarget, decoId); meta = Metadata(decoId is null ? "rooms" : "decos", contributionTarget.RequiredString(decoId is null ? "pf" : "Type")) ?? throw new ApiException(400, "This object has no construction recipe"); }
            changes = controller == "contributeToDojoComponentController" ? Contribute(guild, account, contributionTarget, meta, body, unscaled) : Rush(guild, account, contributionTarget, meta, body, request);
        }
        else if (controller.StartsWith("abortDojoComponent", StringComparison.Ordinal))
        {
            if (controller == "abortDojoComponentDestructionController") { GuildApi.Require(guild, account, 16); roomTarget.Remove("DestructionTime"); }
            else if (body.Value<string>("ResultType") is string resultType) { GuildApi.Require(guild, account, 256); var pending = guild.Array("VaultPendingRecipes").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ParentRoom"]) == componentId && x.Value<string>("Type") == resultType) ?? throw new ApiException(404, "Clan crafting project not found"); Refund(guild, pending); pending.Remove(); }
            else if (decoId is not null) { Decorator(guild, account, roomTarget); RemoveDeco(guild, roomTarget, Deco(roomTarget, decoId)); }
            else { GuildApi.Require(guild, account, 16); if (roomTarget["CompletionTime"] is not null && Wire.DateMs(roomTarget["CompletionTime"]) <= now) throw new ApiException(409, "Completed rooms must be queued for destruction"); CanRemove(guild, roomTarget); RemoveRoom(guild, roomTarget); return ApiResponse.Json(Client(state, guild, build)); }
        }
        else if (controller == "queueDojoComponentDestructionController") { GuildApi.Require(guild, account, 16); CanRemove(guild, roomTarget); if (roomTarget["DestructionTime"] is not null) throw new ApiException(409, "Room destruction is already queued"); if (roomTarget["CompletionTime"] is null || Wire.DateMs(roomTarget["CompletionTime"]) > now) throw new ApiException(409, "Room is not completed"); roomTarget["DestructionTime"] = Wire.Date(now + (guild.Value<bool>("fastDojoRoomDestruction") ? 5000 : 7200000)); }
        else
        {
            Decorator(guild, account, roomTarget);
            if (controller == "setDojoComponentMessageController") { var field = body["Name"] is null ? "Message" : "Name"; if (body[field]?.Type != JTokenType.String || body[field]!.ToString().Length > 8000) throw new ApiException(400, "Invalid room message"); roomTarget[field] = body[field]!.DeepClone(); }
            else if (controller == "setDojoComponentSettingsController") { var settings = body.RequiredString("Settings", 32000); JObject.Parse(settings); roomTarget["Settings"] = settings; }
            else if (controller == "setDojoComponentColorsController") { var colors = body["Colours"] as JArray ?? throw new ApiException(400, "Missing room colors"); if (colors.Count > 32 || colors.Any(x => x.Type != JTokenType.Integer)) throw new ApiException(400, "Invalid room colors"); roomTarget[request.Q("lights") is null ? "PendingColors" : "PendingLights"] = colors.DeepClone(); }
            else if (controller == "placeDecoInComponentController") Place(guild, roomTarget, body);
            else if (controller == "destroyDojoDecoController") { if (body.Value<string>("Act") == "cObst") foreach (var deco in roomTarget.Array("Decos").OfType<JObject>().ToArray()) RemoveDeco(guild, roomTarget, deco); else RemoveDeco(guild, roomTarget, Deco(roomTarget, decoId ?? "")); }
            else throw new ApiException(400, "Unknown dojo operation");
        }
        var response = Client(state, guild, build, componentId); if (changes.Count > 0) response["InventoryChanges"] = changes; return ApiResponse.Json(response);
    }
    public static void GrantXp(JObject guild, JObject meta)
    {
        var type = meta.Value<string>("resultType"); if (meta.Value<int>("guildXpValue") > 0 && type is not null && !guild.Array("ClaimedXP").Any(x => x.ToString() == type)) { guild.Array("ClaimedXP").Add(type); guild["XP"] = checked(guild.Value<long>("XP") + meta.Value<int>("guildXpValue")); }
    }
    private JObject Contribute(JObject guild, JObject account, JObject target, JObject meta, JObject body, bool unscaled)
    {
        if (target["CompletionTime"] is not null) throw new ApiException(409, "Construction is already funded"); long Cost(long value) => unscaled || value == 0 ? value : ResearchApi.Scale(guild, value);
        var remaining = new JObject { ["ReqCredits"] = Math.Max(0, Cost(meta.Value<long>("price")) - target.Value<long>("RegularCredits")), ["ReqItems"] = new JArray((meta["ingredients"] as JArray ?? []).Select(x => new JObject { ["ItemType"] = x["ItemType"]!.DeepClone(), ["ItemCount"] = Math.Max(0, Cost(x.Value<long>("ItemCount")) - (target.Array("MiscItems").FirstOrDefault(item => item.Value<string>("ItemType") == x.Value<string>("ItemType"))?.Value<long>("ItemCount") ?? 0)) })) };
        var normalized = (JObject)body.DeepClone(); normalized["MiscItems"] = (body["IngredientContributions"] ?? body["MiscItems"])?.DeepClone() ?? new JArray(); normalized["VaultMiscItems"] = (body["VaultIngredientContributions"] ?? body["VaultMiscItems"])?.DeepClone() ?? new JArray(); var changes = ResearchApi.Contribute(account, guild, remaining, normalized);
        target["RegularCredits"] = Cost(meta.Value<long>("price")) - remaining.Value<long>("ReqCredits"); target["MiscItems"] = new JArray((meta["ingredients"] as JArray ?? []).Select(x => new JObject { ["ItemType"] = x["ItemType"]!.DeepClone(), ["ItemCount"] = Cost(x.Value<long>("ItemCount")) - remaining.Array("ReqItems").First(y => y.Value<string>("ItemType") == x.Value<string>("ItemType")).Value<long>("ItemCount") }));
        if (remaining.Value<long>("ReqCredits") == 0 && remaining.Array("ReqItems").All(x => x.Value<long>("ItemCount") == 0)) { target["CompletionTime"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds() + meta.Value<long>("time") * 1000); GrantXp(guild, meta); }
        return changes;
    }
    private JObject Rush(JObject guild, JObject account, JObject target, JObject meta, JObject body, ApiRequest request)
    {
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); if (target["CompletionTime"] is null || Wire.DateMs(target["CompletionTime"]) <= now) throw new ApiException(409, "Object is not under construction");
        long Amount(string upper, string lower, string query) => body[upper] is not null ? body.Integer(upper) : body[lower] is not null ? body.Integer(lower) : request.Q(query) is string value && long.TryParse(value, out var count) && count is >= 0 and <= 999999999 ? count : 0;
        var personal = Amount("Amount", "amount", "contributionAmount"); var vault = Amount("VaultAmount", "vaultAmount", "vaultContributionAmount"); var fullCost = ResearchApi.Scale(guild, meta.Value<long>("skipTimePrice")); var millisPerPlatinum = meta.Value<double>("time") * 1000 / fullCost; var maximum = (long)Math.Ceiling((Wire.DateMs(target["CompletionTime"]) - now) / millisPerPlatinum);
        if (!double.IsFinite(millisPerPlatinum) || millisPerPlatinum <= 0 || personal + vault <= 0 || personal + vault > maximum) throw new ApiException(400, "Invalid rush contribution");
        if (vault > 0) { GuildApi.Require(guild, account, 64); ResearchApi.Credit(guild, "VaultPremiumCredits", -vault); }
        var changes = Inventory.ChangeCurrency(account.Obj("Inventory"), "PremiumCredits", -personal); ResearchApi.Credit(GuildApi.Member(guild, account.RequiredString("id")), "PremiumCreditsContributed", personal); target["CompletionTime"] = Wire.Date(Math.Max(now, Wire.DateMs(target["CompletionTime"]) - (long)(millisPerPlatinum * (personal + vault)))); target["RushPlatinum"] = target.Value<long>("RushPlatinum") + personal + vault; return changes;
    }
    private void Place(JObject guild, JObject room, JObject body)
    {
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); if (room["CompletionTime"] is null || Wire.DateMs(room["CompletionTime"]) > now || room["DestructionTime"] is not null) throw new ApiException(409, "Room is not ready for decoration"); var moving = body.Value<string>("MoveId"); JObject deco;
        if (moving is not null) deco = Deco(room, moving);
        else
        {
            var type = body.RequiredString("Type"); var meta = Metadata("decos", type); var entry = GameData.Table("Resources").Properties().FirstOrDefault(x => x.Value.Value<string>("deco") == type && x.Value["dojoCapacityCost"] is not null); if (meta is null && entry is null) throw new ApiException(400, "Unknown dojo decoration"); var cost = meta?.Value<int>("capacityCost") ?? entry!.Value.Value<int>("dojoCapacityCost");
            if (room.Value<int>("DecoCapacity") < cost) throw new ApiException(409, "Insufficient room decoration capacity");
            deco = new JObject { ["id"] = Wire.Oid(Wire.NewId()), ["Type"] = type }; room["DecoCapacity"] = room.Value<int>("DecoCapacity") - cost;
            if (meta is null) { if (body["Sockets"] is not null) { var sockets = (int)body.Integer("Sockets", 0, 65535); VaultApi.Treasure(guild, "VaultFusionTreasures", entry!.Name, sockets, -1); deco["Sockets"] = sockets; } else Inventory.AddCount(guild, "VaultShipDecorations", entry!.Name, -1); }
            if (type != "/Lotus/Objects/Tenno/Props/TnoPaintBotDojoDeco")
            {
                if (meta is null || guild.Value<bool>("noDojoDecoBuildStage") || meta.Value<long>("price") == 0 && (meta["ingredients"] as JArray ?? []).Count == 0) { deco["CompletionTime"] = Wire.Date(now); if (meta is not null) GrantXp(guild, meta); }
                else if (guild.Value<bool>("AutoContributeFromVault") || type.StartsWith("/Lotus/Objects/Tenno/Dojo/NpcPlaceables/", StringComparison.Ordinal)) AutoFund(guild, deco, meta);
            }
            if (body["Name"] is JToken name) deco["Name"] = name.DeepClone(); room.Array("Decos").Add(deco);
        }
        foreach (var field in new[] { "Pos", "Rot" }) { if (body[field] is not JArray vector || vector.Count != 3 || vector.Any(x => x.Type is not (JTokenType.Integer or JTokenType.Float) || !double.IsFinite(x.Value<double>()))) throw new ApiException(400, "Invalid decoration transform"); deco[field] = vector.DeepClone(); }
        if (body["Scale"] is JToken scale) { var value = scale.Value<double>(); if (!double.IsFinite(value) || value <= 0 || value > 100) throw new ApiException(400, "Invalid decoration scale"); deco["Scale"] = value; }
    }
    private void AutoFund(JObject guild, JObject target, JObject meta)
    {
        var credits = meta.Value<long>("price") == 0 ? 0 : ResearchApi.Scale(guild, meta.Value<long>("price")); var parts = new JArray((meta["ingredients"] as JArray ?? []).Select(x => new JObject { ["ItemType"] = x["ItemType"]!.DeepClone(), ["ItemCount"] = ResearchApi.Scale(guild, x.Value<long>("ItemCount")) }));
        if (guild.Value<long>("VaultRegularCredits") < credits || parts.Any(x => (guild.Array("VaultMiscItems").FirstOrDefault(y => y.Value<string>("ItemType") == x.Value<string>("ItemType"))?.Value<long>("ItemCount") ?? 0) < x.Value<long>("ItemCount"))) return;
        ResearchApi.Credit(guild, "VaultRegularCredits", -credits); foreach (var part in parts) Inventory.AddCount(guild, "VaultMiscItems", part.Value<string>("ItemType")!, -part.Value<long>("ItemCount")); target["RegularCredits"] = credits; target["MiscItems"] = parts; target["CompletionTime"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds() + meta.Value<long>("time") * 1000); GrantXp(guild, meta);
    }
    private static void CanRemove(JObject guild, JObject room)
    {
        if (room["pi"] is null || guild.Array("DojoComponents").Any(x => Wire.Id(x["pi"]) == Wire.Id(room["id"]))) throw new ApiException(409, "Reparent connected rooms before destroying this room"); var meta = Metadata("rooms", room.RequiredString("pf"));
        if (meta is not null && (guild.Value<int>("DojoCapacity") - meta.Value<int>("capacity") < 0 || guild.Value<int>("DojoEnergy") - meta.Value<int>("energy") < 0)) throw new ApiException(409, "Other rooms depend on this room's capacity or energy");
    }
    private static void Refund(JObject guild, JObject target)
    {
        ResearchApi.Credit(guild, "VaultRegularCredits", target.Value<long>("RegularCredits")); ResearchApi.Credit(guild, "VaultPremiumCredits", target.Value<long>("RushPlatinum")); foreach (var item in target.Array("MiscItems")) Inventory.AddCount(guild, "VaultMiscItems", item.Value<string>("ItemType")!, item.Value<long>("ItemCount"));
    }
    private static void RemoveDeco(JObject guild, JObject room, JObject deco)
    {
        var type = deco.RequiredString("Type"); var meta = Metadata("decos", type); var entry = GameData.Table("Resources").Properties().FirstOrDefault(x => x.Value.Value<string>("deco") == type); room["DecoCapacity"] = room.Value<int>("DecoCapacity") + (meta?.Value<int>("capacityCost") ?? entry?.Value.Value<int>("dojoCapacityCost") ?? 0);
        if (meta is null && entry is not null) { if (deco["Sockets"] is not null) VaultApi.Treasure(guild, "VaultFusionTreasures", entry.Name, deco.Value<int>("Sockets"), 1); else Inventory.AddCount(guild, "VaultShipDecorations", entry.Name, 1); }
        Refund(guild, deco); deco.Remove();
    }
    private static void RemoveRoom(JObject guild, JObject room)
    {
        var meta = Metadata("rooms", room.RequiredString("pf")); if (meta is not null) { guild["DojoCapacity"] = guild.Value<int>("DojoCapacity") - meta.Value<int>("capacity"); guild["DojoEnergy"] = guild.Value<int>("DojoEnergy") - meta.Value<int>("energy"); }
        foreach (var deco in room.Array("Decos").OfType<JObject>().ToArray()) RemoveDeco(guild, room, deco); foreach (var pending in guild.Array("VaultPendingRecipes").OfType<JObject>().Where(x => Wire.Id(x["ParentRoom"]) == Wire.Id(room["id"])).ToArray()) { Refund(guild, pending); pending.Remove(); } Refund(guild, room); room.Remove();
    }
    private static void Reparent(JObject guild, string newRoot)
    {
        var root = Component(guild, newRoot); var chain = new List<JObject> { root }; var seen = new HashSet<string> { newRoot }; var cursor = root;
        while (cursor["pi"] is not null) { var id = Wire.Id(cursor["pi"]); if (!seen.Add(id)) throw new ApiException(409, "Dojo room graph contains a cycle"); cursor = Component(guild, id); chain.Add(cursor); }
        for (var i = chain.Count - 1; i > 0; i--) { var parent = chain[i]; var child = chain[i - 1]; parent["pi"] = child["id"]!.DeepClone(); parent["ppf"] = child["pf"]!.DeepClone(); parent["op"] = child["pp"]?.DeepClone(); parent["pp"] = child["op"]?.DeepClone(); }
        root.Remove("pi"); root.Remove("op"); root.Remove("pp"); root["ppf"] = ""; var queue = new Queue<JObject>(); queue.Enqueue(root); seen.Clear();
        while (queue.TryDequeue(out var room)) { var id = Wire.Id(room["id"]); if (!seen.Add(id)) throw new ApiException(409, "Dojo room graph contains a cycle"); room["SortId"] = Wire.Oid(Wire.NewId()); foreach (var child in guild.Array("DojoComponents").OfType<JObject>().Where(x => Wire.Id(x["pi"]) == id)) queue.Enqueue(child); }
    }
    public void Refresh(JObject state, JObject guild)
    {
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); foreach (var room in guild.Array("DojoComponents").OfType<JObject>().ToArray())
        {
            if (room["DestructionTime"] is not null && Wire.DateMs(room["DestructionTime"]) <= now) { CanRemove(guild, room); RemoveRoom(guild, room); continue; }
            if (room["CompletionTime"] is not null && Wire.DateMs(room["CompletionTime"]) <= now && !room.Value<bool>("CompletionProcessed")) { room["CompletionProcessed"] = true; var tier = Tier(room.Value<string>("pf")); if (tier > guild.Value<int>("Tier")) new ResearchApi(catalog, clock).ChangeTier(state, guild, tier); new GuildApi(clock).Log(guild, "RoomChanges", 1, room["pf"]!); }
            foreach (var paint in room.Array("Decos").OfType<JObject>().Where(x => x.Value<string>("Type") == "/Lotus/Objects/Tenno/Props/TnoPaintBotDojoDeco" && x["CompletionTime"] is not null && Wire.DateMs(x["CompletionTime"]) <= now).ToArray()) { foreach (var key in new[] { "Colors", "Lights" }) if (room["Pending" + key] is JToken value) { room[key] = value.DeepClone(); room.Remove("Pending" + key); } paint.Remove(); }
        }
        foreach (var pending in guild.Array("VaultPendingRecipes").OfType<JObject>().Where(x => x["CompletionTime"] is not null && Wire.DateMs(x["CompletionTime"]) <= now).ToArray()) { Inventory.AddCount(guild, "VaultInventoryItems", pending.RequiredString("Type"), 1); pending.Remove(); }
    }
    public JObject Client(JObject state, JObject guild, long build, string? componentId = null)
    {
        Refresh(state, guild); var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); var result = new JObject { ["_id"] = GameVersion.Oid(guild.RequiredString("id"), build), ["Name"] = guild["Name"]!.DeepClone(), ["Tier"] = guild.Value<int>("Tier"), ["TradeTax"] = guild.Value<int>("TradeTax"), ["NumContributors"] = guild.Array("CeremonyContributors").Count, ["FixedContributions"] = true, ["DojoRevision"] = 1, ["RevisionTime"] = (now + 500) / 1000, ["Energy"] = guild.Value<int>("DojoEnergy"), ["Capacity"] = guild.Value<int>("DojoCapacity"), ["DojoRequestStatus"] = 0, ["Vault"] = GuildApi.Vault(guild), ["DojoComponents"] = new JArray() };
        foreach (var room in guild.Array("DojoComponents").OfType<JObject>().Where(x => componentId is null || Wire.Id(x["id"]) == componentId))
        {
            var copy = (JObject)room.DeepClone(); copy.Remove("CompletionProcessed"); copy.Remove("RushPlatinum"); copy["id"] = GameVersion.Oid(Wire.Id(room["id"]), build); copy["SortId"] = GameVersion.Oid(Wire.Id(room["SortId"] ?? room["id"]), build); if (room["pi"] is not null) copy["pi"] = GameVersion.Oid(Wire.Id(room["pi"]), build);
            if (copy.Value<string>("pf") == "/Lotus/Levels/ClanDojo/DojoHall.level" && build <= GameVersion.Of("9.1.0")) copy["pf"] = "/Lotus/Levels/ClanDojo/ClanHallA.level";
            if (room["CompletionTime"] is not null) { copy.Remove("RegularCredits"); copy.Remove("MiscItems"); copy["TimeRemaining"] = 1 + (Wire.DateMs(room["CompletionTime"]) - now) / 1000; } if (room["DestructionTime"] is not null) copy["DestructionTimeRemaining"] = 1 + (Wire.DateMs(room["DestructionTime"]) - now) / 1000;
            foreach (var deco in copy.Array("Decos").OfType<JObject>()) { deco["id"] = GameVersion.Oid(Wire.Id(deco["id"]), build); deco.Remove("RushPlatinum"); if (deco["CompletionTime"] is not null) { deco.Remove("RegularCredits"); deco.Remove("MiscItems"); deco["TimeRemaining"] = (Wire.DateMs(deco["CompletionTime"]) - now) / 1000; } }
            ((JArray)result["DojoComponents"]!).Add(copy);
        }
        if (guild["CeremonyResetDate"] is JToken date) result["CeremonyResetDate"] = date.DeepClone(); return result;
    }
}