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 ResearchApi(ItemCatalog catalog, TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["guildTechController"];
    public static JObject Recipe(string type) => GameData.Table("DojoRecipes")["research"]?[type] as JObject ?? throw new ApiException(400, "Unknown research recipe");
    public static long Scale(JObject guild, long value) => Math.Max(1, (long)(value * new[] { .01, .03, .1, .3, 1 }[Math.Clamp(guild.Value<int>("Tier") - 1, 0, 4)]));
    public static void Access(JObject account) { if (!account.Obj("Inventory").Array("LevelKeys").Any(x => x.Value<string>("ItemType") == "/Lotus/Types/Keys/DojoKey" && x.Value<int>("ItemCount") > 0)) throw new ApiException(403, "A crafted clan key is required"); }
    public ApiResponse Handle(JObject state, JObject account, ApiRequest request)
    {
        var body = request.ObjectBody(); var action = body.RequiredString("Action"); var type = body.Value<string>("RecipeType") ?? body.Value<string>("ResearchId") ?? request.Q("researchId"); var inv = account.Obj("Inventory"); var now = clock.GetUtcNow().ToUnixTimeMilliseconds();
        var personal = body.Value<string>("Mode") == "Personal" || body["CategoryItemId"] is not null || request.Q("guildId") == new string('0', 24) || action == "Contribute" && inv.Array("PersonalTechProjects").Any(x => Wire.Id(x["ItemId"]) == body.Value<string>("ResearchId"));
        if (personal) return Personal(account, body, action, type, now);
        var guild = GuildApi.Own(state, account, request.Q("guildId")); Refresh(guild); var guildApi = new GuildApi(clock);
        if (action == "Sync") return ApiResponse.Json(new JObject { ["TechProjects"] = new JArray(guild.Array("TechProjects").OfType<JObject>().Select(x => { var result = (JObject)x.DeepClone(); result.Remove("CompletionProcessed"); if (x["CompletionDate"] is not null) result["CompletionDate"] = GameVersion.Date(Wire.DateMs(x["CompletionDate"]), GameVersion.For(account)); return result; })) });
        Access(account);
        if (action == "Fabricate")
        {
            GuildApi.Require(guild, account, 4096); var recipe = GameData.Table("DojoRecipes")["fabrications"]?[type ?? ""] as JObject ?? throw new ApiException(400, "Unknown fabrication recipe"); var changes = Inventory.ChangeCurrency(inv, "RegularCredits", -recipe.Value<long>("price"));
            foreach (var part in (recipe["ingredients"] as JArray ?? []).OfType<JObject>()) { Inventory.AddCount(inv, "MiscItems", part.RequiredString("ItemType"), -part.Integer("ItemCount", 1)); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = part["ItemType"]!.DeepClone(), ["ItemCount"] = -part.Value<long>("ItemCount") }) }); }
            Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, recipe.RequiredString("resultType"))); return ApiResponse.Json(new JObject { ["inventoryChanges"] = changes });
        }
        var meta = Recipe(type ?? ""); var projects = guild.Array("TechProjects"); var project = projects.OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type);
        if (action == "Start")
        {
            GuildApi.Require(guild, account, 128); if (project is not null) return ApiResponse.Text();
            if (meta.Value<string>("resultType") is not null) throw new ApiException(400, "This research must be started as a personal project");
            var color = type!.StartsWith("/Lotus/Types/Items/Research/DojoColors/", StringComparison.Ordinal); if (color && !string.IsNullOrEmpty(guild.Value<string>("ActiveDojoColorResearch"))) throw new ApiException(409, "Another pigment research is active");
            project = new JObject { ["ItemType"] = type, ["State"] = 0, ["ReqCredits"] = guild.Value<bool>("noDojoResearchCosts") ? 0 : Scale(guild, meta.Value<long>("price")), ["ReqItems"] = new JArray((meta["ingredients"] as JArray ?? []).Select(x => new JObject { ["ItemType"] = x["ItemType"]!.DeepClone(), ["ItemCount"] = guild.Value<bool>("noDojoResearchCosts") ? 0 : Scale(guild, x.Value<long>("ItemCount")) })) }; projects.Add(project); guildApi.Log(guild, "TechChanges", 5, type);
            if (color) guild["ActiveDojoColorResearch"] = type; Fund(state, guild, project); return ApiResponse.Text();
        }
        if (project is null) throw new ApiException(404, "Research has not been started");
        if (action == "Contribute")
        {
            if (project.Value<int>("State") != 0) throw new ApiException(409, "Research is not collecting materials"); var changes = Contribute(account, guild, project, body); Fund(state, guild, project); return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes, ["Vault"] = GuildApi.Vault(guild) });
        }
        if (action.Split(',')[0] == "Buy")
        {
            GuildApi.Require(guild, account, 4096); if (project.Value<int>("State") != 1 || Wire.DateMs(project["CompletionDate"]) > now) throw new ApiException(409, "Research has not completed");
            var count = action.Contains(',', StringComparison.Ordinal) ? int.Parse(action.Split(',')[1], System.Globalization.CultureInfo.InvariantCulture) : 1; if (count is < 1 or > 100) throw new ApiException(400, "Invalid replication quantity");
            var changes = Inventory.ChangeCurrency(inv, "RegularCredits", checked(-meta.Value<long>("replicatePrice") * count)); Inventory.Combine(changes, Inventory.AddItem(inv, "Recipes", type!, count)); return ApiResponse.Json(new JObject { ["inventoryChanges"] = changes });
        }
        GuildApi.Require(guild, account, 128);
        if (!type!.StartsWith("/Lotus/Types/Items/Research/DojoColors/", StringComparison.Ordinal)) throw new ApiException(400, "Only pigment research may be paused");
        if (action == "Pause" && project.Value<int>("State") == 0) { project["State"] = -2; guild["ActiveDojoColorResearch"] = ""; RemovePigments(state, guild); return ApiResponse.Text(); }
        if (action == "Unpause" && project.Value<int>("State") == -2 && string.IsNullOrEmpty(guild.Value<string>("ActiveDojoColorResearch"))) { project["State"] = 0; guild["ActiveDojoColorResearch"] = type; return ApiResponse.Text(); }
        throw new ApiException(400, "Invalid research operation or state");
    }
    public static JObject Contribute(JObject account, JObject? guild, JObject project, JObject body)
    {
        var inv = account.Obj("Inventory"); var changes = new JObject(); var member = guild is null ? null : GuildApi.Member(guild, account.RequiredString("id"));
        foreach (var (field, vault) in new[] { ("VaultCredits", true), ("RegularCredits", false) })
        {
            var requested = body[field] is null ? 0 : body.Integer(field); var count = Math.Min(requested, project.Value<long>("ReqCredits")); if (count == 0) continue;
            if (vault) { if (guild is null) throw new ApiException(400, "Personal research cannot spend the clan vault"); GuildApi.Require(guild, account, 64); Credit(guild, "VaultRegularCredits", -count); }
            else { Inventory.Combine(changes, Inventory.ChangeCurrency(inv, "RegularCredits", -count)); if (member is not null) Credit(member, "RegularCreditsContributed", count); }
            project["ReqCredits"] = project.Value<long>("ReqCredits") - count;
        }
        foreach (var (field, vault) in new[] { ("VaultMiscItems", true), ("MiscItems", false) }) foreach (var contribution in (body[field] as JArray ?? []).OfType<JObject>())
        {
            var type = contribution.RequiredString("ItemType"); var requested = contribution.Integer("ItemCount"); var required = project.Array("ReqItems").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type) ?? throw new ApiException(400, "Item is not a research ingredient"); var count = Math.Min(requested, required.Value<long>("ItemCount")); if (count == 0) continue;
            if (vault) { if (guild is null) throw new ApiException(400, "Personal research cannot spend the clan vault"); GuildApi.Require(guild, account, 64); Inventory.AddCount(guild, "VaultMiscItems", type, -count); }
            else { Inventory.AddCount(inv, "MiscItems", type, -count); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = -count }) }); if (member is not null) Inventory.AddCount(member, "MiscItemsContributed", type, count); }
            required["ItemCount"] = required.Value<long>("ItemCount") - count;
        }
        return changes;
    }
    public static void Credit(JObject obj, string field, long delta) { var next = checked(obj.Value<long>(field) + delta); if (next < 0 || next > 999_999_999) throw new ApiException(400, "Insufficient vault balance or overflow"); obj[field] = next; }
    public void Fund(JObject state, JObject guild, JObject project)
    {
        if (project.Value<int>("State") != 0 || project.Value<long>("ReqCredits") > 0 || project.Array("ReqItems").Any(x => x.Value<long>("ItemCount") > 0)) return;
        var type = project.RequiredString("ItemType"); var meta = Recipe(type); project["State"] = 1; project["CompletionDate"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds() + (guild.Value<bool>("noDojoResearchTime") ? 0 : meta.Value<long>("time") * 1000));
        guild["XP"] = checked(guild.Value<long>("XP") + meta.Value<int>("guildXpValue")); new GuildApi(clock).Log(guild, "TechChanges", 3, type);
        if (guild.Value<string>("ActiveDojoColorResearch") == type) { guild["ActiveDojoColorResearch"] = ""; RemovePigments(state, guild); } Refresh(guild);
    }
    private static void RemovePigments(JObject state, JObject guild)
    {
        foreach (var member in guild.Array("Members").Where(x => x.Value<int>("status") == 0)) foreach (var pigment in GuildApi.Account(state, member.Value<string>("accountId")!).Obj("Inventory").Array("MiscItems").Where(x => x.Value<string>("ItemType")?.StartsWith("/Lotus/Types/Items/Research/DojoColors/", StringComparison.Ordinal) == true).ToArray()) pigment.Remove();
    }
    public void Refresh(JObject guild)
    {
        foreach (var project in guild.Array("TechProjects").OfType<JObject>().Where(x => x.Value<int>("State") == 1 && !x.Value<bool>("CompletionProcessed") && Wire.DateMs(x["CompletionDate"]) <= clock.GetUtcNow().ToUnixTimeMilliseconds()))
        {
            var type = project.RequiredString("ItemType"); project["CompletionProcessed"] = true; new GuildApi(clock).Log(guild, "TechChanges", 4, type);
            if (type.StartsWith("/Lotus/Levels/ClanDojo/ComponentPropRecipes/NpcPlaceables/", StringComparison.Ordinal)) Inventory.AddCount(guild, "VaultDecoRecipes", type, 1); else if (type == "/Lotus/Types/Game/SolarRails/BasicSolarRailBlueprint") Inventory.AddCount(guild, "VaultRecipes", type, 1);
        }
    }
    public void ChangeTier(JObject state, JObject guild, int tier)
    {
        if (tier is < 1 or > 5) throw new ApiException(400, "Invalid clan tier"); var oldTier = guild.Value<int>("Tier"); if (tier == oldTier) return; var old = (JObject)guild.DeepClone(); guild["Tier"] = tier;
        foreach (var project in guild.Array("TechProjects").OfType<JObject>().Where(x => x.Value<int>("State") != 1))
        {
            var meta = Recipe(project.RequiredString("ItemType")); var remaining = Scale(guild, meta.Value<long>("price")) - (Scale(old, meta.Value<long>("price")) - project.Value<long>("ReqCredits")); if (remaining < 0) Credit(guild, "VaultRegularCredits", -remaining); project["ReqCredits"] = Math.Max(0, remaining);
            foreach (var item in project.Array("ReqItems").OfType<JObject>()) { var part = (meta["ingredients"] as JArray ?? []).First(x => x.Value<string>("ItemType") == item.Value<string>("ItemType")); var count = Scale(guild, part.Value<long>("ItemCount")) - (Scale(old, part.Value<long>("ItemCount")) - item.Value<long>("ItemCount")); if (count < 0) Inventory.AddCount(guild, "VaultMiscItems", item.RequiredString("ItemType"), -count); item["ItemCount"] = Math.Max(0, count); } Fund(state, guild, project);
        }
    }
    private ApiResponse Personal(JObject account, JObject body, string action, string? type, long now)
    {
        var inv = account.Obj("Inventory"); var projects = inv.Array("PersonalTechProjects"); var itemId = body.Value<string>("CategoryItemId"); var project = projects.OfType<JObject>().FirstOrDefault(x => itemId is not null ? Wire.Id(x["CategoryItemId"]) == itemId : Wire.Id(x["ItemId"]) == body.Value<string>("ResearchId")); var changes = new JObject();
        if (action == "Start")
        {
            var meta = Recipe(type ?? ""); if (project is not null || projects.Any(x => x.Value<string>("ItemType") == type && itemId is null)) throw new ApiException(409, "Personal research already exists");
            var category = body.Value<string>("TechProductCategory"); if (category is not null) { var salvage = Inventory.Equipment(inv, SalvageCategory(category), itemId); if (meta.Value<string>("resultType") != salvage.Value<string>("ItemType")) throw new ApiException(400, "Repair recipe does not match the salvaged part"); }
            if (meta.Value<string>("resultType") is null) throw new ApiException(400, "Not a personal research recipe"); project = new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["State"] = 0, ["ReqCredits"] = meta.Value<long>("price"), ["ReqItems"] = meta["ingredients"]!.DeepClone() }; if (category is not null) { project["ProductCategory"] = category; project["CategoryItemId"] = Wire.Oid(itemId!); } projects.Add(project);
            return ApiResponse.Json(new JObject { ["isPersonal"] = true, ["action"] = "Start", ["personalTech"] = project.DeepClone() });
        }
        if (action == "InstantFinish")
        {
            const string repair = "/Lotus/Types/Items/MiscItems/InstantSalvageRepairItem"; Inventory.AddCount(inv, "MiscItems", repair, -1); changes["MiscItems"] = new JArray(new JObject { ["ItemType"] = repair, ["ItemCount"] = -1 }); Inventory.Combine(changes, Finish(inv, body.RequiredString("TechProductCategory"), itemId ?? "")); project?.Remove(); return ApiResponse.Json(new JObject { ["inventoryChanges"] = changes });
        }
        if (project is null) throw new ApiException(404, "Personal research not found"); var recipe = Recipe(project.RequiredString("ItemType"));
        if (action == "Contribute")
        {
            if (project.Value<int>("State") != 0) throw new ApiException(409, "Research is no longer collecting materials"); changes = Contribute(account, null, project, body); project["HasContributions"] = true;
            if (project.Value<long>("ReqCredits") == 0 && !project.Array("ReqItems").Any(x => x.Value<long>("ItemCount") > 0)) { project["State"] = 1; project["CompletionDate"] = Wire.Date(now + recipe.Value<long>("time") * 1000); }
            return ApiResponse.Json(new JObject { ["InventoryChanges"] = changes, ["PersonalResearch"] = project["ItemId"]!.DeepClone(), ["PersonalResearchDate"] = project["CompletionDate"]?.DeepClone() });
        }
        if (action == "Cancel")
        {
            Inventory.Combine(changes, Inventory.ChangeCurrency(inv, "RegularCredits", recipe.Value<long>("price") - project.Value<long>("ReqCredits")));
            foreach (var part in (recipe["ingredients"] as JArray ?? []).OfType<JObject>()) { var count = part.Value<long>("ItemCount") - (project.Array("ReqItems").FirstOrDefault(x => x.Value<string>("ItemType") == part.Value<string>("ItemType"))?.Value<long>("ItemCount") ?? 0); 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 result = new JObject { ["action"] = "Cancel", ["isPersonal"] = true, ["inventoryChanges"] = changes, ["personalTech"] = new JObject { ["ItemId"] = project["ItemId"]!.DeepClone() } }; project.Remove(); return ApiResponse.Json(result);
        }
        if (action == "Rush" || action.Split(',')[0] == "Buy")
        {
            if (project.Value<int>("State") != 1) throw new ApiException(409, "Research has not been fully funded"); if (Wire.DateMs(project["CompletionDate"]) > now) { if (action != "Rush") throw new ApiException(409, "Research is not complete"); Inventory.Combine(changes, Inventory.ChangeCurrency(inv, "PremiumCredits", -20)); }
            Inventory.Combine(changes, project.Value<string>("ProductCategory") is string category ? Finish(inv, category, Wire.Id(project["CategoryItemId"])) : new ItemAcquisition(catalog, clock, account).Add(inv, recipe.RequiredString("resultType"))); project.Remove(); return ApiResponse.Json(new JObject { ["inventoryChanges"] = changes });
        }
        throw new ApiException(400, "Unknown personal research operation");
    }
    private static string SalvageCategory(string category) => category switch { "CrewShipWeapons" => "CrewShipSalvagedWeapons", "CrewShipWeaponSkins" => "CrewShipSalvagedWeaponSkins", _ => throw new ApiException(400, "Invalid personal tech product category") };
    private static JObject Finish(JObject inv, string category, string id)
    {
        var salvage = Inventory.Equipment(inv, SalvageCategory(category), id); var changes = Inventory.OccupySlots(inv, category, 1, false); var copy = (JObject)salvage.DeepClone(); copy["ItemId"] = Wire.Oid(Wire.NewId()); salvage.Remove(); inv.Array(category).Add(copy); changes[category] = new JArray(copy.DeepClone()); changes["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(id) }); return changes;
    }
}