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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed partial class AccountEditor
{
    private static readonly Lazy<JObject> Choices = new(() => (JObject)Assets.Json("editor/choices.json"));
    private static readonly Lazy<JObject> Templates = new(() => (JObject)Assets.Json("editor/import-samples.json"));
    private static readonly IReadOnlyDictionary<string, string> TemplateLabels = new Dictionary<string, string>
    {
        ["maxFocus3"] = "Focus 3 全满(U31.5 及以后)", ["maxFocus2"] = "Focus 2 全满(U22–U31.4)", ["maxFocus1"] = "Focus 1 全满(U18–U21)",
        ["accolades"] = "账号荣誉徽章", ["maxStratos"] = "战术警报徽记", ["resetSortieCompletion"] = "重置突击完成记录", ["clearWishlist"] = "清空愿望单",
        ["clearLocPins"] = "清空地图标记", ["eidolonLocPins"] = "夜灵地图标记"
    };

    private static JArray TemplateActions() => new(Templates.Value.Properties().Select(p =>
    {
        var result = Action("template." + p.Name, TemplateLabels.GetValueOrDefault(p.Name, p.Name));
        result["description"] = "将替换以下存档字段:" + string.Join("、", ((JObject)p.Value).Properties().Select(x => x.Name));
        result["preview"] = p.Value.DeepClone();
        return result;
    }));

    private bool ApplyExtended(JObject state, JObject account, JObject body, string action, JObject values)
    {
        var inv = account.Obj("Inventory");
        if (action is "riven.create" or "riven.save")
        {
            var type = RivenCalculator.Prefix + RivenCalculator.Family(values.RequiredString("type"));
            var fingerprint = RivenCalculator.Decode(values["fingerprint"]);
            RivenCalculator.ValidateForSave(type, fingerprint);
            if (action == "riven.save")
            {
                var owned = RivenApi.Owned(inv, body["item"]);
                if (owned.Value<string>("ItemType") != type) throw new ApiException(400, "不可将已持有紫卡改为其他类型。");
                owned["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None);
                owned.Remove("PendingRerollFingerprint");
            }
            else inv.Array("Upgrades").Add(new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None) });
            return true;
        }
        if (action.StartsWith("template.", StringComparison.Ordinal))
        {
            var key = action[9..];
            var template = Templates.Value[key] as JObject ?? throw new ApiException(400, "未知存档模板。");
            // Old Focus trees are distinct protocols, not interchangeable account options.
            if (key.StartsWith("maxFocus", StringComparison.Ordinal))
            {
                var build = GameVersion.For(account);
                var version = build >= GameVersion.Of("31.5.0") ? 3 : build >= GameVersion.Of("22.0.0") ? 2 : 1;
                if (key != "maxFocus" + version) throw new ApiException(409, "所选专精模板与账号最后登录的游戏版本不符。");
            }
            Inventory.Import(account, (JObject)template.DeepClone());
            return true;
        }
        if (action == "unlock.plexus")
        {
            var harness = inv.Array("CrewShipHarnesses").OfType<JObject>().FirstOrDefault();
            if (harness is null)
            {
                new ItemAcquisition(catalog, clock, account).Add(inv, "/Lotus/Types/Game/CrewShip/RailJack/DefaultHarness", premium: true);
                harness = inv.Array("CrewShipHarnesses").OfType<JObject>().First();
            }
            SetExperience(account, "CrewShipHarnesses", harness, Math.Max(900000, harness.Value<long>("XP")));
            return true;
        }
        if (action == "inbox.read")
        {
            foreach (var message in account.Array("Inbox").OfType<JObject>()) message["r"] = true;
            return true;
        }
        return false;
    }

    private static string? EvolutionType(string type)
    {
        var parent = GameData.Find("Weapons", type)?.Value<string>("parentName");
        return WorldData.Get("evolutionWeapons").Any(x => x.ToString() == type) ? type :
            parent is not null && WorldData.Get("evolutionWeapons").Any(x => x.ToString() == parent) ? parent : null;
    }
    private static int EvolutionMax(string type) => WorldData.Get("permanentEvolutionWeapons").Any(x => x.ToString() == type) ? 5 : 4;

    private static JObject KnownChoice(string key, string label, string group, string? current = null)
    {
        var entries = ((JObject)Choices.Value[group]!).Properties().Select(x => (x.Name, x.Value.ToString())).ToArray();
        return Choice(key, label, current ?? entries[0].Name, entries);
    }
    private JObject AbilityChoice(string? current)
    {
        var entries = GameData.Table("Abilities").Properties().Select(x => (x.Name, catalog.Name((JObject)x.Value, x.Name)))
            .Concat(GameData.Table("Warframes").Properties().SelectMany(x => (x.Value["abilities"] as JArray ?? []).OfType<JObject>()).Select(x => (x.RequiredString("uniqueName"), catalog.Name(x, x.RequiredString("uniqueName")))))
            .DistinctBy(x => x.Item1).OrderBy(x => x.Item2).Prepend(("", "移除此配置的移植技能")).ToArray();
        var field = Choice("ability", "技能", current ?? "", entries);
        var icons = GameData.Table("Abilities").Properties().Where(x => x.Value["icon"] is not null)
            .ToDictionary(x => x.Name, x => x.Value["icon"]!.ToString(), StringComparer.Ordinal);
        foreach (var ability in GameData.Table("Warframes").Properties().SelectMany(x => x.Value["abilities"] as JArray ?? []))
            if (ability.Value<string>("uniqueName") is { } type && ability.Value<string>("icon") is { } icon) icons[type] = icon;
        foreach (var option in field.Array("options")) if (icons.TryGetValue(option.Value<string>("value") ?? "", out var icon)) option["icon"] = icon;
        return field;
    }

    private JArray BatchActions(string category, JObject inv)
    {
        var actions = new JArray();
        AddAcquisitionActions(actions, inv, category);
        if (LevelCategories.Contains(category)) actions.Add(Action("batch.max", "当前分类全部满级"));
        if (category == "QuestKeys") { actions.Add(Action("batch.quests.complete", "完成全部已持有任务")); actions.Add(Action("batch.quests.reset", "重置全部已持有任务")); }
        if (category == "EvolutionProgress") { actions.Add(Action("batch.evolution.max", "全部灵化进度满级")); actions.Add(Action("batch.evolution.missing", "补齐缺失的灵化进度")); }
        if (category is "Upgrades" or "RawUpgrades")
        {
            actions.Add(Action("batch.mods.max", "当前分类全部 MOD 满级"));
            foreach (var unranked in new[] { true, false })
            {
                var count = ModRemoval(inv, unranked).Count();
                if (count == 0) continue;
                var action = Action(unranked ? "batch.mods.removeUnranked" : "batch.mods.removeRanked", unranked ? "清除未升级 MOD" : "清除已升级 MOD");
                action["description"] = $"将移除 {count:N0} 条 MOD 记录。" + (unranked ? "保留未升级的安魂 MOD,并移除已使用的安魂 MOD。" : "保留已使用的安魂 MOD,并移除未升级的安魂 MOD。") + "此规则与原版相同。";
                actions.Add(action);
            }
        }
        actions.Add(Action("batch.remove", "清空当前分类"));
        foreach (var action in actions.OfType<JObject>().Where(x => x["description"] is null))
            action["description"] = $"此分类有 {inv.Array(category).Count:N0} 条记录;操作包含搜索结果之外的物品。";
        return actions;
    }

    private void ApplyBatch(JObject account, string category, string action)
    {
        var inv = account.Obj("Inventory");
        if (!BatchActions(category, inv).Any(x => x.Value<string>("key") == action)) throw new ApiException(400, "该分类当前不支持此批量操作,请刷新列表。");
        if (action is "batch.acquire.missing" or "batch.mods.missing") { AcquireMissing(account, category); return; }
        if (action is "batch.mods.removeUnranked" or "batch.mods.removeRanked")
        {
            foreach (var entry in ModRemoval(inv, action == "batch.mods.removeUnranked").ToArray()) RemoveItem(account, entry.Category, entry.Item, checked((int)(entry.Item.Value<long?>("ItemCount") ?? 1)));
            return;
        }
        if (action == "batch.evolution.missing")
        {
            foreach (var type in WorldData.Get("evolutionWeapons").Values<string>().OfType<string>())
                if (!inv.Array(category).Any(x => x.Value<string>("ItemType") == type)) inv.Array(category).Add(new JObject { ["ItemType"] = type, ["Rank"] = 1, ["Progress"] = 0 });
            return;
        }
        if (action.StartsWith("batch.quests.", StringComparison.Ordinal))
        {
            new QuestApi(catalog, clock).Manage(account, action.EndsWith("complete", StringComparison.Ordinal) ? "completeAll" : "resetAll", null); return;
        }
        foreach (var item in inv.Array(category).Select(AsItem).ToArray())
        {
            // A preceding paired-weapon removal may have removed this row too.
            if (item.Parent is null && Inventory.EquipmentKeys.Contains(category)) continue;
            switch (action)
            {
                case "batch.max": MaxExperience(account, category, item); break;
                case "batch.evolution.max": item["Rank"] = EvolutionMax(item.RequiredString("ItemType")); item["Progress"] = 0; break;
                case "batch.mods.max":
                    var limit = ModMetadata(item.RequiredString("ItemType"))?.Value<int>("fusionLimit") ?? 0;
                    if (limit > 0) SetModRank(inv, category, item, limit); break;
                case "batch.remove": RemoveItem(account, category, item, checked((int)(item.Value<long?>("ItemCount") ?? 1))); break;
            }
        }
    }

    private static IEnumerable<(string Category, JObject Item)> ModRemoval(JObject inv, bool unranked)
    {
        foreach (var category in new[] { "RawUpgrades", "Upgrades" })
            foreach (var item in inv.Array(category).OfType<JObject>())
            {
                var parazon = ModMetadata(item.RequiredString("ItemType"))?.Value<string>("type") == "PARAZON";
                if (((category == "RawUpgrades") ^ parazon) == unranked) yield return (category, item);
            }
    }

    private static void SetExperience(JObject account, string category, JObject item, long target)
    {
        var current = item.Value<long>("XP");
        if (target < current) item["XP"] = target; // Never erase earned mastery when lowering an equipment rank.
        else if (target > current) InventoryProgress.Equipment(account.Obj("Inventory"), category, new JArray(new JObject { ["ItemId"] = item["ItemId"]!.DeepClone(), ["XP"] = target - current }));
    }

    private void MaxExperience(JObject account, string category, JObject item)
    {
        JObject meta;
        try { meta = catalog.Get(item.RequiredString("ItemType")).Meta; } catch (ApiException) { meta = new JObject(); }
        var level = meta.Value<int?>("maxLevelCap") ?? 30;
        var suitLike = new[] { "Suits", "SpaceSuits", "Hoverboards", "MechSuits", "Sentinels", "MoaPets", "KubrowPets", "CrewShipHarnesses" }.Contains(category);
        var target = (long)level * level * (suitLike ? 1000 : 500);
        if (level > 30) item["Polarized"] = Math.Max(item.Value<int>("Polarized"), (level - 30) / 2);
        SetExperience(account, category, item, Math.Max(target, item.Value<long>("XP")));
        if (item["AltWeaponModeId"] is JToken pair)
        {
            var otherCategory = category == "Melee" ? "LongGuns" : "Melee";
            var other = Inventory.Equipment(account.Obj("Inventory"), otherCategory, Wire.Id(pair));
            SetExperience(account, otherCategory, other, Math.Max(target, other.Value<long>("XP")));
        }
        foreach (var type in meta["exalted"] as JArray ?? [])
        {
            var special = account.Obj("Inventory").Array("SpecialItems").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type.ToString());
            if (special is null) continue;
            var cap = type.ToString().Contains("/Khora/Kavat/", StringComparison.Ordinal) ? 1600000 : 800000;
            SetExperience(account, "SpecialItems", special, Math.Max(cap, special.Value<long>("XP")));
        }
    }

    private static void SetModRank(JObject inv, string category, JObject item, int rank)
    {
        var meta = ModApi.Metadata(item.RequiredString("ItemType"));
        if (rank < 0 || rank > meta.Value<int>("fusionLimit")) throw new ApiException(400, "MOD 等级超出上限。");
        if (category == "RawUpgrades")
        {
            if (rank == 0) return;
            var type = item.RequiredString("ItemType");
            Inventory.AddCount(inv, "RawUpgrades", type, -1);
            item = new JObject { ["ItemType"] = type, ["ItemId"] = Wire.Oid(Wire.NewId()) }; inv.Array("Upgrades").Add(item);
        }
        var fingerprint = JObject.Parse(item.Value<string>("UpgradeFingerprint") ?? "{}");
        fingerprint["lvl"] = rank; item["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None);
    }

    private static void RemoveItem(JObject account, string category, JObject item, int count)
    {
        var inv = account.Obj("Inventory"); var id = Wire.Id(item["ItemId"]);
        if (Inventory.CountedKeys.Contains(category))
        {
            var type = item.RequiredString("ItemType"); Inventory.AddCount(inv, category, type, -count);
            if (!inv.Array(category).Any(x => x.Value<string>("ItemType") == type && x.Value<long>("ItemCount") > 0)) InventoryReferences.Removed(account, category, item);
            return;
        }
        if (item.Parent is null) { inv.Array(category).First(x => x.Type == JTokenType.String && x.ToString() == item.RequiredString("ItemType")).Remove(); return; }
        Inventory.RequireNotInResearch(inv, id);
        if (category == "QuestKeys" && inv.Value<string>("ActiveQuest") == item.Value<string>("ItemType")) inv["ActiveQuest"] = "";
        if (Inventory.EquipmentKeys.Contains(category))
        {
            if (item["DeployTime"] is not null) throw new ApiException(409, "请先收回部署中的采集器。");
            if (item["AltWeaponModeId"] is JToken other)
            {
                var paired = Inventory.Equipment(inv, category == "Melee" ? "LongGuns" : "Melee", Wire.Id(other));
                Inventory.RequireNotInResearch(inv, Wire.Id(paired["ItemId"]));
                InventoryReferences.Removed(account, category == "Melee" ? "LongGuns" : "Melee", paired);
                paired.Remove();
            }
            Inventory.FreeSlot(inv, category);
            foreach (var pending in inv.Array("PendingRecipes").Where(x => Wire.Id(x["KubrowPet"]) == id).ToArray()) pending.Remove();
        }
        InventoryReferences.Removed(account, category, item); item.Remove();
    }
}