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 string[] LevelCategories = ["Suits", "SpaceSuits", "Sentinels", "LongGuns", "Pistols", "Melee", "SpaceGuns", "SpaceMelee", "SentinelWeapons", "Hoverboards", "OperatorAmps", "MechSuits", "MoaPets", "KubrowPets", "SpecialItems"];
    private static readonly (string, string)[] Elements = [("InnateElectricityDamage", "电击"), ("InnateFreezeDamage", "冰冻"), ("InnateHeatDamage", "火焰"), ("InnateImpactDamage", "冲击"), ("InnateMagDamage", "磁力"), ("InnateRadDamage", "辐射"), ("InnateToxinDamage", "毒素")];
    private static readonly IReadOnlyDictionary<string, string> PartLabels = new Dictionary<string, string>
    {
        ["LWPT_HILT"] = "握柄", ["LWPT_BLADE"] = "打击部", ["LWPT_HILT_WEIGHT"] = "连接部",
        ["LWPT_GUN_PRIMARY_HANDLE"] = "主武器握柄", ["LWPT_GUN_SECONDARY_HANDLE"] = "副武器握柄", ["LWPT_GUN_BARREL"] = "枪膛", ["LWPT_GUN_CLIP"] = "装填器",
        ["LWPT_AMP_BRACE"] = "曲柄", ["LWPT_AMP_CORE"] = "支架", ["LWPT_AMP_OCULUS"] = "棱镜",
        ["LWPT_HB_DECK"] = "板面", ["LWPT_HB_ENGINE"] = "反应堆", ["LWPT_HB_FRONT"] = "板头", ["LWPT_HB_JET"] = "喷射器",
        ["LWPT_MOA_LEG"] = "支架", ["LWPT_MOA_HEAD"] = "模型", ["LWPT_MOA_ENGINE"] = "核心", ["LWPT_MOA_PAYLOAD"] = "陀螺仪",
        ["LWPT_ZANUKA_BODY"] = "骨架", ["LWPT_ZANUKA_HEAD"] = "模型", ["LWPT_ZANUKA_LEG"] = "稳定器", ["LWPT_ZANUKA_TAIL"] = "感知器",
        ["LWPT_CATBROW_MUTAGEN"] = "突变剂", ["LWPT_CATBROW_ANTIGEN"] = "抗原", ["LWPT_KUBROW_MUTAGEN"] = "突变剂", ["LWPT_KUBROW_ANTIGEN"] = "抗原"
    };
    private JObject[] PartFields(string type, JArray? current = null) => ModularApi.RequiredParts(type).Where(x => x != "ANIMAL").Select(part =>
    {
        var choices = GameData.Table("Weapons").Properties().Where(x => x.Value.Value<string>("partType") == part).Select(x => (x.Name, catalog.Name((JObject)x.Value, x.Name))).OrderBy(x => x.Item2).ToArray();
        var selected = current?.Values<string>().FirstOrDefault(x => x is not null && GameData.Find("Weapons", x)?.Value<string>("partType") == part);
        return Choice(part, PartLabels.GetValueOrDefault(part, part), selected ?? choices.First().Name, choices);
    }).ToArray();
    private JArray CreationActions(string category, JObject inventory)
    {
        var actions = new JArray();
        if (category == "QuestKeys")
        {
            var missing = MissingItems(inventory, category).Select(x => (x.Type, x.Name)).ToArray();
            if (missing.Length > 0)
            {
                var action = Action("create.quest", "添加缺失任务", Choice("type", "系列任务", missing[0].Type, missing));
                action["description"] = "仅添加尚未持有的任务,不会完成任务或改动已有任务进度。";
                actions.Add(action);
            }
            return actions;
        }
        var seen = new HashSet<string>();
        foreach (var type in ((JObject)WorldData.Get("modularWeaponTypes")).Properties().Where(x => x.Value.ToString() == category).Select(x => x.Name))
        {
            var family = category == "KubrowPets" ? type : string.Join(',', ModularApi.RequiredParts(type));
            if (!seen.Add(family)) continue;
            var label = category is "Melee" or "LongGuns" or "Pistols" or "OperatorAmps" or "Hoverboards" ? Labels[category] : type.Contains("Zanuka", StringComparison.Ordinal) ? "猎犬" : Name(new JObject { ["ItemType"] = type });
            var action = Action("create.modular." + actions.Count, "组装 · " + label, PartFields(type)); action["weaponType"] = type; actions.Add(action);
        }
        if (category == "EvolutionProgress")
        {
            var types = WorldData.Get("evolutionWeapons").Values<string>().OfType<string>().Select(x => (x, Name(new JObject { ["ItemType"] = x }))).ToArray();
            actions.Add(Action("create.evolution", "添加灵化进度", Choice("type", "武器", types[0].x, types), Number("rank", "等级(永久灵化 0–5,适配器 1–4)", 1, 0, 5)));
        }
        if (category == "Upgrades") foreach (var mod in LegacyMods.All.Properties())
        {
            var fields = LegacyFields((JObject)mod.Value, new JObject(), null, true);
            var action = Action("create.legacy." + actions.Count, "创建旧版 MOD · " + catalog.Name((JObject)mod.Value, mod.Name), fields); action["modType"] = mod.Name; actions.Add(action);
        }
        if (category == "Boosters")
        {
            var types = catalog.Entries.Where(x => x.Category == "Boosters").Select(x => (x.Type, catalog.Name(x.Meta, x.Type))).ToArray();
            if (types.Length > 0) actions.Add(Action("create.booster", "添加加成", Choice("type", "加成类型", types[0].Type, types), Date("expiry", "到期时间", clock.GetUtcNow().AddDays(3).ToUnixTimeMilliseconds())));
        }
        return actions;
    }
    private static void ValidateFields(JObject descriptor, JObject values)
    {
        var fields = (JArray)descriptor["fields"]!;
        if (values.Properties().Any(x => !fields.Any(f => f.Value<string>("key") == x.Name))) throw new ApiException(400, "包含未知编辑字段。");
        foreach (var f in fields.OfType<JObject>()) Validate(f, values[f.RequiredString("key")] ?? throw new ApiException(400, "缺少 " + f.RequiredString("label")));
    }
    private static JArray Parts(string type, JObject values)
    {
        var parts = new JArray(ModularApi.RequiredParts(type).Select(x => x == "ANIMAL" ? ModularApi.Animal(type) : values.RequiredString(x)));
        return parts;
    }
    private static string ResolveModularType(string type, JArray parts)
    {
        var category = ModularApi.Category(type);
        foreach (var part in parts) if (WorldData.Get("modularPartTypeMapping")[part.ToString()]?.Value<string>(category) is string mapped) type = mapped;
        return type;
    }
    private void CreateItem(JObject account, string category, string action, JObject values)
    {
        var descriptor = CreationActions(category, account.Obj("Inventory")).OfType<JObject>().FirstOrDefault(x => x.Value<string>("key") == action) ?? throw new ApiException(400, "该分类不支持此创建操作。");
        ValidateFields(descriptor, values); var inv = account.Obj("Inventory");
        if (action == "create.quest")
        {
            new ItemAcquisition(catalog, clock, account).Add(inv, values.RequiredString("type"), premium: true);
        }
        else if (action.StartsWith("create.modular.", StringComparison.Ordinal))
        {
            var type = descriptor.RequiredString("weaponType"); var parts = Parts(type, values); type = ResolveModularType(type, parts);
            new ModularApi(catalog, clock).Create(account, type, parts, premium: true);
        }
        else if (action.StartsWith("create.legacy.", StringComparison.Ordinal))
        {
            var item = new JObject { ["ItemType"] = descriptor["modType"]!.DeepClone(), ["ItemId"] = Wire.Oid(Wire.NewId()) };
            ApplyLegacy(item, "legacy.meta", values); ApplyLegacy(item, "legacy.add", values); inv.Array("Upgrades").Add(item);
        }
        else if (action == "create.evolution")
        {
            var type = values.RequiredString("type"); var rank = values.Integer("rank", EvolutionMax(type) == 5 ? 0 : 1, EvolutionMax(type));
            if (inv.Array(category).Any(x => x.Value<string>("ItemType") == type)) throw new ApiException(409, "该武器已有灵化进度,请选择它后编辑。");
            inv.Array(category).Add(new JObject { ["ItemType"] = type, ["Rank"] = rank, ["Progress"] = 0 });
        }
        else if (action == "create.booster")
        {
            var expiry = values.Value<long>("expiry") / 1000;
            if (expiry <= clock.GetUtcNow().ToUnixTimeSeconds()) throw new ApiException(400, "加成到期时间必须在未来。");
            var type = values.RequiredString("type"); var booster = inv.Array(category).OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type);
            if (booster is null) inv.Array(category).Add(new JObject { ["ItemType"] = type, ["ExpiryDate"] = expiry }); else booster["ExpiryDate"] = expiry;
        }
    }
    private void AddEquipmentActions(JArray actions, string category, JObject item)
    {
        var type = item.RequiredString("ItemType");
        if (WorldData.Get("modularWeaponTypes")[type] is not null && item["ModularParts"] is JArray parts) actions.Add(Action("parts", "修改模块化部件", PartFields(type, parts)));
        if (category is "LongGuns" or "Pistols" or "Melee" or "SpaceGuns" or "SpaceMelee")
        {
            JObject fp;
            try { fp = JObject.Parse(item.Value<string>("UpgradeFingerprint") ?? "{}"); } catch (JsonException) { fp = new(); }
            var buff = (fp["buffs"] as JArray)?.FirstOrDefault(); var raw = buff?.Value<long>("Value") ?? 0;
            var percentage = 25 + 35 * raw / (double)RivenCalculator.Scale;
            var value = new JObject { ["key"] = "percentage", ["label"] = "元素伤害加成(%)", ["type"] = "number", ["min"] = 25, ["max"] = 60, ["step"] = .1, ["value"] = percentage };
            actions.Add(Action("valence", "玄骸 / 信条元素加成", Choice("element", "元素(选移除可清除覆盖)", buff?.Value<string>("Tag") ?? "InnateHeatDamage", [("", "移除元素覆盖"), .. Elements]), value));
        }
    }
    private static void ChangeParts(string category, JObject item, JObject values)
    {
        var type = item.RequiredString("ItemType"); var parts = Parts(type, values); type = ResolveModularType(type, parts);
        ModularApi.ValidateParts(type, parts);
        if (ModularApi.Category(type) != category) throw new ApiException(400, "部件不能改变装备分类。");
        item["ItemType"] = type;
        item["ModularParts"] = category == "KubrowPets" ? new JArray(parts.Skip(1).Select(x => x.DeepClone())) : parts;
    }
    private static void SetValence(JObject item, JObject values)
    {
        if (values.Value<string>("element") == "") { item.Remove("UpgradeFingerprint"); item.Remove("UpgradeType"); return; }
        var fp = JObject.Parse(item.Value<string>("UpgradeFingerprint") ?? "{}");
        fp["buffs"] = new JArray(new JObject { ["Tag"] = values["element"]!.DeepClone(), ["Value"] = (long)Math.Truncate((values.Value<double>("percentage") - 25) * RivenCalculator.Scale / 35) });
        item["UpgradeType"] = "/Lotus/Weapons/Grineer/KuvaLich/Upgrades/InnateDamageRandomMod";
        item["UpgradeFingerprint"] = fp.ToString(Formatting.None);
    }
}