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 GuildApi(TimeProvider clock)
{
    private static readonly Lazy<ItemCatalog> Catalog = new(() => new());
    public static readonly HashSet<string> Controllers = ["createGuildGetController", "createGuildPostController", "getGuildController", "addToGuildGetController", "addToGuildPostController", "confirmGuildInvitationGetController", "confirmGuildInvitationPostController", "declineGuildInviteController", "removeFromGuildGetController", "removeFromGuildPostController", "changeGuildRankController", "customizeGuildRanksController", "setGuildMotdController", "getGuildContributionsController", "getGuildLogController", "getGuildEventScoreController", "contributeGuildClassController"];
    public static IEnumerable<JObject> All(JObject state) => state.Obj("guilds").Properties().Select(x => x.Value).OfType<JObject>();
    public static JObject? Find(JObject state, string? id) => id is null ? null : state.Obj("guilds")[id] as JObject;
    public static JObject Own(JObject state, JObject account, string? id = null)
    {
        var ownId = Wire.Id(account.Obj("Inventory")["GuildId"]); if (id is not null && id != ownId) throw new ApiException(403, "Account is not a member of the requested guild");
        var guild = Find(state, ownId) ?? throw new ApiException(404, "Account has no guild"); Member(guild, account.RequiredString("id")); return guild;
    }
    public static JObject Member(JObject guild, string id) => guild.Array("Members").OfType<JObject>().FirstOrDefault(x => x.Value<string>("accountId") == id && x.Value<int>("status") == 0) ?? throw new ApiException(403, "Active guild membership is required");
    public static bool Allowed(JObject guild, JObject account, int permission)
    {
        var member = Member(guild, account.RequiredString("id")); var rank = member.Value<int>("rank"); return rank >= 0 && rank < guild.Array("Ranks").Count && (guild["Ranks"]![rank]!.Value<int>("Permissions") & permission) == permission;
    }
    public static void Require(JObject guild, JObject account, int permission) { if (!Allowed(guild, account, permission)) throw new ApiException(403, "Insufficient guild permissions"); }
    public static JObject Account(JObject state, string id) => state.Obj("accounts")[id] as JObject ?? throw new ApiException(404, "Player not found");
    public static JObject Target(JObject state, string? id, string? name) => id is not null ? Account(state, id) : Accounts.All(state).FirstOrDefault(x => x.Value<string>("DisplayName") == name?.TrimEnd('\ue000', '\ue001', '\ue002', '\ue003', '\ue004', '\ue005')) ?? throw new ApiException(404, "Player not found");
    public static int Capacity(JObject guild) => new[] { 10, 30, 100, 300, 1000 }[Math.Clamp(guild.Value<int>("Tier") - 1, 0, 4)];
    public void Log(JObject guild, string field, int kind, JToken details) => guild.Array(field).Add(new JObject { ["dateTime"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds()), ["entryType"] = kind, ["details"] = details.DeepClone() });
    public static string Name(string value)
    {
        value = value.Trim(); if (value.Length is < 1 or > 64 || value.Any(char.IsControl) || value.Contains('#', StringComparison.Ordinal)) throw new ApiException(400, "Invalid clan or alliance name"); return value;
    }
    public ApiResponse Handle(string controller, JObject state, JObject account, ApiRequest request)
    {
        var body = controller == "setGuildMotdController" ? new JObject() : request.ObjectBody(); var id = account.RequiredString("id"); var inv = account.Obj("Inventory");
        if (controller is "createGuildGetController" or "createGuildPostController")
        {
            if (Find(state, Wire.Id(inv["GuildId"])) is JObject existing) return ApiResponse.Json(Client(state, existing, account));
            var name = Name(request.Q("guildName") ?? body.RequiredString("guildName", 64)); var names = All(state).Select(x => x.Value<string>("Name")).ToHashSet(); var start = Random.Shared.Next(1000); string? full = null;
            for (var i = 0; i < 1000; i++) { var candidate = name + "#" + ((start + i) % 1000).ToString("000"); if (!names.Contains(candidate)) { full = candidate; break; } }
            if (full is null) throw new ApiException(409, "Clan name discriminators are exhausted");
            var guild = new JObject { ["id"] = Wire.NewId(), ["Name"] = full, ["MOTD"] = "", ["Tier"] = 1, ["Class"] = 0, ["XP"] = 0, ["TradeTax"] = 0, ["DojoCapacity"] = 100, ["DojoEnergy"] = 5, ["ActiveDojoColorResearch"] = "", ["Ranks"] = Ranks(), ["Members"] = new JArray(), ["DojoComponents"] = new JArray() }; state.Obj("guilds")[guild.RequiredString("id")] = guild;
            var changes = Join(state, guild, account, 0); var response = Client(state, guild, account); response["InventoryChanges"] = changes; return ApiResponse.Json(response);
        }
        if (controller == "getGuildController") return Find(state, Wire.Id(inv["GuildId"])) is JObject current ? ApiResponse.Json(Client(state, current, account)) : ApiResponse.Text();
        if (controller == "declineGuildInviteController")
        {
            var invited = Find(state, request.Q("clanId")); if (invited is not null) foreach (var entry in invited.Array("Members").OfType<JObject>().Where(x => x.Value<string>("accountId") == id && x.Value<int>("status") != 0).ToArray()) entry.Remove(); return ApiResponse.Text();
        }
        if (controller == "confirmGuildInvitationGetController")
        {
            var invited = Find(state, request.Q("clanId")) ?? throw new ApiException(404, "Clan invitation not found");
            if (!invited.Array("Members").Any(x => x.Value<string>("accountId") == id && x.Value<int>("status") == 2)) throw new ApiException(409, "No pending clan invitation");
            var changes = Join(state, invited, account); var response = Client(state, invited, account); response["InventoryChanges"] = changes; return ApiResponse.Json(response);
        }
        if (controller is "addToGuildPostController" && body["RequestMsg"] is not null)
        {
            if (!string.IsNullOrEmpty(Wire.Id(inv["GuildId"]))) throw new ApiException(409, "Already in a clan"); var invited = Find(state, Wire.Id(body["GuildId"])) ?? throw new ApiException(404, "Clan not found");
            if (invited.Array("Members").Any(x => x.Value<string>("accountId") == id)) throw new ApiException(409, "Clan application already exists");
            invited.Array("Members").Add(new JObject { ["accountId"] = id, ["rank"] = 7, ["status"] = 1, ["RequestMsg"] = body["RequestMsg"]!.DeepClone(), ["RequestExpiry"] = Wire.Date(clock.GetUtcNow().AddDays(14).ToUnixTimeMilliseconds()) }); return ApiResponse.Text();
        }
        var own = Own(state, account, request.Q("guildId") ?? (controller == "confirmGuildInvitationPostController" ? request.Q("clanId") : null)); Refresh(own);
        if (controller is "addToGuildGetController" or "addToGuildPostController")
        {
            Require(own, account, 2); var target = Target(state, null, request.Q("userName") ?? body.Value<string>("UserName") ?? body.Value<string>("userName")); var targetId = target.RequiredString("id");
            if (!string.IsNullOrEmpty(Wire.Id(target.Obj("Inventory")["GuildId"]))) throw new ApiException(409, "Player is already in a clan");
            if (own.Array("Members").Any(x => x.Value<string>("accountId") == targetId)) throw new ApiException(409, "Clan invitation already exists");
            var restriction = target.Obj("Inventory").Obj("Settings").Value<string>("GuildInvRestriction"); var edges = state.Array("friendships");
            if (restriction == "GIFT_MODE_NONE" || restriction == "GIFT_MODE_FRIENDS" && !(edges.Any(x => x.Value<string>("owner") == id && x.Value<string>("friend") == targetId) && edges.Any(x => x.Value<string>("owner") == targetId && x.Value<string>("friend") == id))) throw new ApiException(403, "Clan invitations are restricted");
            var member = new JObject { ["accountId"] = targetId, ["status"] = 2, ["rank"] = 7 }; own.Array("Members").Add(member);
            InboxApi.Create(target, new JObject { ["sndr"] = account["DisplayName"]!.DeepClone(), ["sub"] = "/Lotus/Language/Menu/Mailbox_ClanInvite_Title", ["msg"] = "/Lotus/Language/Menu/Mailbox_ClanInvite_Body", ["arg"] = new JArray(new JObject { ["Key"] = "clan", ["Tag"] = own["Name"]!.DeepClone() }), ["contextInfo"] = own["id"]!.DeepClone(), ["highPriority"] = true, ["acceptAction"] = "GUILD_INVITE", ["declineAction"] = "GUILD_INVITE", ["hasAccountAction"] = true }, clock.GetUtcNow());
            return ApiResponse.Json(new JObject { ["NewMember"] = MemberClient(state, member, GameVersion.For(account)) });
        }
        if (controller == "confirmGuildInvitationPostController")
        {
            Require(own, account, 2); var user = body.RequiredString("userId"); var members = new JArray();
            foreach (var member in own.Array("Members").OfType<JObject>().Where(x => x.Value<int>("status") == 1 && (user == "all" || x.Value<string>("accountId") == user)).ToArray())
            {
                var target = Account(state, member.RequiredString("accountId")); if (Find(state, Wire.Id(target.Obj("Inventory")["GuildId"])) is not null) { member.Remove(); continue; }
                Join(state, own, target); members.Add(target["id"]!.DeepClone());
            }
            return ApiResponse.Json(new JObject { ["NewMembers"] = members });
        }
        if (controller is "removeFromGuildGetController" or "removeFromGuildPostController")
        {
            var target = Target(state, body.Value<string>("userId"), request.Q("userName") ?? body.Value<string>("userName")); var targetId = target.RequiredString("id");
            var member = own.Array("Members").OfType<JObject>().FirstOrDefault(x => x.Value<string>("accountId") == targetId) ?? throw new ApiException(404, "Clan member not found");
            if (targetId != id) { Require(own, account, 4); if (member.Value<int>("status") == 0 && member.Value<int>("rank") <= Member(own, id).Value<int>("rank")) throw new ApiException(403, "Cannot remove a member of equal or higher rank"); }
            if (member.Value<int>("status") == 0) { if (member.Value<int>("rank") == 0) Delete(state, own); else { RemoveMembership(target); member.Remove(); Log(own, "RosterActivity", targetId == id ? 7 : 12, target.Value<string>("DisplayName") + (targetId == id ? "" : "," + account.Value<string>("DisplayName"))); } }
            else member.Remove(); RemoveInvites(target, own.RequiredString("id"));
            return ApiResponse.Json(new JObject { ["_id"] = targetId, ["Name"] = target["DisplayName"]!.DeepClone(), ["ItemToRemove"] = "/Lotus/Types/Keys/DojoKey", ["RecipeToRemove"] = "/Lotus/Types/Keys/DojoKeyBlueprint" });
        }
        if (controller == "changeGuildRankController")
        {
            Require(own, account, 8); var me = Member(own, id); var target = Member(own, request.Q("targetId") ?? ""); if (!int.TryParse(request.Q("rankChange"), out var rank)) throw new ApiException(400, "Invalid clan rank");
            if (GameVersion.For(account) <= GameVersion.Of("24.0.0")) rank += target.Value<int>("rank");
            if (rank < me.Value<int>("rank") || rank < 0 || rank >= own.Array("Ranks").Count || target.Value<int>("rank") < me.Value<int>("rank") || ReferenceEquals(me, target)) throw new ApiException(403, "Invalid clan rank change");
            target["rank"] = rank; if (rank == 0) me["rank"] = 1; return ApiResponse.Json(new { _id = target.Value<string>("accountId"), Rank = rank + (GameVersion.For(account) < GameVersion.Of("24.0.0") ? 1 : 0) });
        }
        if (controller == "customizeGuildRanksController")
        {
            Require(own, account, 1); var ranks = body["GuildRanks"] as JArray ?? throw new ApiException(400, "Missing clan ranks"); if (ranks.Count != 9) throw new ApiException(400, "Clan requires nine ranks");
            foreach (var rank in ranks.OfType<JObject>()) { rank.RequiredString("Name", 100); rank.Integer("Permissions", 0, 16383); } if (ranks.OfType<JObject>().Count() != 9) throw new ApiException(400, "Invalid clan rank");
            if ((ranks[0]!.Value<int>("Permissions") & 1) == 0) throw new ApiException(400, "Founding warlord must retain ruler permission"); own["Ranks"] = ranks.DeepClone(); return ApiResponse.Text();
        }
        if (controller == "setGuildMotdController")
        {
            var text = request.Body.TrimEnd('\0'); if (text.Length > 32000) throw new ApiException(400, "MOTD is too long"); var isLong = request.Q("longMOTD") is not null; JObject target = own; var alliance = request.Q("alliance") is not null;
            if (alliance) { if (Member(own, id).Value<int>("rank") > 1) throw new ApiException(403, "Warlord permission is required"); target = AllianceApi.Find(state, own.Value<string>("AllianceId")) ?? throw new ApiException(404, "Alliance not found"); } else Require(own, account, 2048);
            if (isLong || alliance) { var message = new JObject { ["message"] = text, ["authorName"] = account["DisplayName"]!.DeepClone() }; if (alliance) message["authorGuildName"] = own["Name"]!.DeepClone(); if (text.Length == 0) target.Remove(isLong ? "LongMOTD" : "MOTD"); else target[isLong ? "LongMOTD" : "MOTD"] = message; } else target["MOTD"] = text;
            return GameVersion.For(account) > GameVersion.Of("29.3.1") ? ApiResponse.Json(new { IsLongMOTD = isLong, MOTD = text }) : ApiResponse.Text(text);
        }
        if (controller == "getGuildContributionsController")
        {
            var member = Member(own, request.Q("buddyId") ?? ""); var result = new JObject { ["_id"] = Wire.Oid(member.RequiredString("accountId")), ["ConsumablesContributed"] = new JArray() }; foreach (var key in new[] { "RegularCreditsContributed", "PremiumCreditsContributed", "MiscItemsContributed", "ShipDecorationsContributed" }) if (member[key] is JToken value) result[key] = value.DeepClone(); return ApiResponse.Json(result);
        }
        if (controller == "getGuildLogController")
        {
            var result = new JObject(); foreach (var key in new[] { "RoomChanges", "TechChanges", "RosterActivity", "StandingsUpdates", "ClassChanges" }) result[key] = new JArray(own.Array(key).OfType<JObject>().Select(x => new JObject { ["dateTime"] = GameVersion.Date(Wire.DateMs(x["dateTime"]), GameVersion.For(account)), ["entryType"] = x["entryType"]!.DeepClone(), ["details"] = x["details"]!.DeepClone() })); return ApiResponse.Json(result);
        }
        if (controller == "getGuildEventScoreController")
        {
            var goal = own.Array("GoalProgress").FirstOrDefault(x => Wire.Id(x["_id"] ?? x["goalId"]) == request.Q("goalId")); return ApiResponse.Json(goal is null ? new JObject() : new JObject { ["Tier"] = own["Tier"]!.DeepClone(), ["GoalProgress"] = goal.DeepClone() });
        }
        if (controller == "contributeGuildClassController") return Ascend(own, account, body);
        throw new ApiException(400, "Unknown guild operation");
    }
    private static JArray Ranks() => new(new[] { "Creator", "Warlord", "General", "Officer", "Leader", "Sage", "Soldier", "Initiate", "Utility" }.Select((x, i) => new JObject { ["Name"] = "/Lotus/Language/Game/Rank_" + x, ["Permissions"] = new[] { 16383, 16383, 4350, 4346, 4138, 4336, 4130, 4128, 4128 }[i] }));
    public JObject Join(JObject state, JObject guild, JObject account, int rank = 7)
    {
        var id = account.RequiredString("id"); var inv = account.Obj("Inventory"); var prior = Find(state, Wire.Id(inv["GuildId"]));
        if (prior is not null) { if (ReferenceEquals(prior, guild)) throw new ApiException(409, "Already in this clan"); throw new ApiException(409, "Leave the current clan before joining another"); }
        if (guild.Array("Members").Count(x => x.Value<int>("status") == 0) >= Capacity(guild)) throw new ApiException(409, "Clan capacity has been reached");
        foreach (var other in All(state)) foreach (var pending in other.Array("Members").OfType<JObject>().Where(x => x.Value<string>("accountId") == id && x.Value<int>("status") != 0).ToArray()) pending.Remove();
        guild.Array("Members").Add(new JObject { ["accountId"] = id, ["rank"] = rank, ["status"] = 0, ["Joined"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds()) }); inv["GuildId"] = Wire.Oid(guild.RequiredString("id")); RemoveInvites(account, guild.RequiredString("id"));
        Log(guild, "RosterActivity", 6, account["DisplayName"]!); var skip = state.Obj("config").Value<bool>("skipClanKeyCrafting"); var category = skip ? "LevelKeys" : "Recipes"; var type = "/Lotus/Types/Keys/DojoKey" + (skip ? "" : "Blueprint"); return Inventory.AddItem(inv, category, type, 1);
    }
    public static void RemoveMembership(JObject account)
    {
        var inv = account.Obj("Inventory"); inv.Remove("GuildId"); foreach (var category in new[] { "Recipes", "LevelKeys", "PendingRecipes" }) foreach (var entry in inv.Array(category).Where(x => x.Value<string>("ItemType") is "/Lotus/Types/Keys/DojoKey" or "/Lotus/Types/Keys/DojoKeyBlueprint").ToArray()) entry.Remove();
    }
    private static void RemoveInvites(JObject account, string guild) { foreach (var message in account.Array("Inbox").Where(x => x.Value<string>("contextInfo") == guild && x.Value<string>("acceptAction") == "GUILD_INVITE").ToArray()) message.Remove(); }
    public static void Delete(JObject state, JObject guild)
    {
        var id = guild.RequiredString("id"); foreach (var account in Accounts.All(state)) { if (Wire.Id(account.Obj("Inventory")["GuildId"]) == id) RemoveMembership(account); RemoveInvites(account, id); }
        foreach (var alliance in state.Obj("alliances").Properties().Select(x => x.Value).OfType<JObject>().ToArray())
            foreach (var member in alliance.Array("Members").OfType<JObject>().Where(x => x.Value<string>("guildId") == id).ToArray()) { if ((member.Value<int>("Permissions") & 1) != 0) AllianceApi.Delete(state, alliance); else member.Remove(); }
        state.Obj("guildAds").Remove(id); state.Obj("guilds").Remove(id);
    }
    public void Refresh(JObject guild)
    {
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); foreach (var pending in guild.Array("Members").OfType<JObject>().Where(x => x.Value<int>("status") != 0 && x["RequestExpiry"] is not null && Wire.DateMs(x["RequestExpiry"]) <= now).ToArray()) pending.Remove();
        if (guild["CeremonyResetDate"] is not null && Wire.DateMs(guild["CeremonyResetDate"]) <= now) foreach (var field in new[] { "CeremonyResetDate", "CeremonyEndo", "CeremonyClass", "CeremonyContributors" }) guild.Remove(field);
    }
    private static JObject MemberClient(JObject state, JObject member, long build)
    {
        var account = Account(state, member.RequiredString("accountId")); var result = SocialApi.Info(account, new JObject()); result["_id"] = GameVersion.Oid(account.RequiredString("id"), build); result["Status"] = member.Value<int>("status"); result["Rank"] = member.Value<int>("rank") + (build < GameVersion.Of("24.0.0") ? 1 : 0);
        foreach (var field in new[] { "Joined", "RequestExpiry" }) if (member[field] is JToken value) result[field] = value.DeepClone(); if (member["RequestMsg"] is JToken note) result["Note"] = note.DeepClone(); return result;
    }
    public JObject Client(JObject state, JObject guild, JObject account)
    {
        Refresh(guild); new ResearchApi(Catalog.Value, clock).Refresh(guild); new DojoApi(Catalog.Value, clock).Refresh(state, guild); var build = GameVersion.For(account); var result = new JObject { ["_id"] = GameVersion.Oid(guild.RequiredString("id"), build), ["Members"] = new JArray(guild.Array("Members").OfType<JObject>().Select(x => MemberClient(state, x, build))), ["Vault"] = Vault(guild), ["IsContributor"] = guild.Array("CeremonyContributors").Any(x => x.ToString() == account.Value<string>("id")), ["NumContributors"] = guild.Array("CeremonyContributors").Count };
        foreach (var key in new[] { "Name", "MOTD", "LongMOTD", "Ranks", "Tier", "Emblem", "ActiveDojoColorResearch", "Class", "XP", "AutoContributeFromVault", "GoalProgress" }) if (guild[key] is JToken value) result[key] = value.DeepClone();
        foreach (var key in new[] { "GuildTierIncMoratorium", "CeremonyResetDate" }) if (guild[key] is JToken value) result[key] = GameVersion.Date(Wire.DateMs(value), build); if (guild.Value<string>("AllianceId") is string alliance) result["AllianceId"] = GameVersion.Oid(alliance, build); return result;
    }
    public static JObject Vault(JObject guild)
    {
        var vault = new JObject { ["DojoRefundRegularCredits"] = guild.Value<long>("VaultRegularCredits"), ["DojoRefundPremiumCredits"] = guild.Value<long>("VaultPremiumCredits"), ["DojoRefundMiscItems"] = guild.Array("VaultMiscItems").DeepClone() };
        foreach (var key in new[] { "ShipDecorations", "FusionTreasures", "DecoRecipes", "Recipes" }) vault[key] = guild.Array("Vault" + key).DeepClone();
        foreach (var key in new[] { "MaxBattlePayReserve", "MaxMissionBattlePay", "MinMissionBattlePay" }) vault[key] = guild.Value<long>(key);
        foreach (var item in guild.Array("VaultInventoryItems").OfType<JObject>()) vault.Obj("InventoryItems").Array(Catalog.Value.Get(item.RequiredString("ItemType")).Category).Add(item.DeepClone());
        foreach (var pending in guild.Array("VaultPendingRecipes").OfType<JObject>()) { var copy = (JObject)pending.DeepClone(); copy.Remove("RecipeType"); vault.Obj("PendingRecipes").Array(Catalog.Value.Get(pending.RequiredString("Type")).Category).Add(copy); }
        return vault;
    }
    private ApiResponse Ascend(JObject guild, JObject account, JObject body)
    {
        if (body.Value<string>("GuildId") != guild.Value<string>("id")) throw new ApiException(403, "Invalid ascension guild"); var contributions = guild.Array("CeremonyContributors"); var id = account.RequiredString("id"); if (contributions.Any(x => x.ToString() == id)) throw new ApiException(409, "Ascension reward already claimed");
        if (guild["CeremonyEndo"] is null)
        {
            var thresholds = new[] { 0, 11000, 34000, 69000, 114000, 168000, 231000, 302000, 381000, 468000, 563000, 665000, 774000, 891000 }; var next = thresholds.Count(x => guild.Value<int>("XP") >= x) - 1; var current = guild.Value<int>("Class");
            if (next <= current) throw new ApiException(409, "Clan has not earned a new rank"); guild["CeremonyClass"] = next; guild["CeremonyEndo"] = Enumerable.Range(current + 1, next - current).Sum(x => x * 1000); Log(guild, "ClassChanges", 13, next);
        }
        contributions.Add(id); if (guild.Value<int>("CeremonyClass") > 0 && contributions.Count >= new[] { 1, 5, 15, 30, 50 }[guild.Value<int>("Tier") - 1]) { guild["Class"] = guild["CeremonyClass"]!.DeepClone(); guild.Remove("CeremonyClass"); guild["CeremonyResetDate"] = Wire.Date(clock.GetUtcNow().AddHours(guild.Value<bool>("fastClanAscension") ? 5d / 3600 : 72).ToUnixTimeMilliseconds()); }
        Inventory.ChangeCurrency(account.Obj("Inventory"), "FusionPoints", guild.Value<int>("CeremonyEndo")); return ApiResponse.Json(new JObject { ["NumContributors"] = contributions.Count, ["FusionPointReward"] = guild["CeremonyEndo"]!.DeepClone(), ["Class"] = guild["Class"]!.DeepClone(), ["CeremonyResetDate"] = guild["CeremonyResetDate"]?.DeepClone() });
    }
}