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 FocusApi
{
    public const string TrainingAmpType = "/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/OperatorTrainingAmpWeapon";
    public static readonly HashSet<string> Controllers = ["focusController"];
    private static readonly string[] Polarities = ["AP_ATTACK", "AP_DEFENSE", "AP_TACTIC", "AP_POWER", "AP_WARD"];
    private static string Polarity(string type)
    {
        var parts = type.Split('/'); var polarity = parts.Length > 4 ? "AP_" + parts[4].ToUpperInvariant() : "";
        return type.StartsWith("/Lotus/Upgrades/Focus/", StringComparison.Ordinal) && Polarities.Contains(polarity) ? polarity : throw new ApiException(400, "Invalid focus school");
    }
    private static JObject Owned(JObject inv, string type) => inv.Array("FocusUpgrades").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type) ?? throw new ApiException(404, "Focus upgrade is not unlocked");
    private static void Spend(JObject inv, string polarity, long amount, JObject costs)
    {
        if (amount < 0 || amount > inv.Obj("FocusXP").Value<long>(polarity)) throw new ApiException(400, "Insufficient focus points");
        inv.Obj("FocusXP")[polarity] = inv.Obj("FocusXP").Value<long>(polarity) - amount; costs[polarity] = costs.Value<long>(polarity) + amount;
    }
    public ApiResponse Handle(JObject account, ApiRequest request)
    {
        var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var build = GameVersion.For(account); var version = build >= GameVersion.Of("31.5.0") ? 3 : build >= GameVersion.Of("22.0.0") ? 2 : 1;
        if (build >= GameVersion.Of("41.0.0")) TauronFocus.EnsureOwned(inv);
        var operations = (JObject)WorldData.Get("Focus" + version + "Operation"); var op = operations.Properties().FirstOrDefault(x => x.Value.ToString() == request.Q("op"))?.Name ?? request.Q("op");
        var costs = new JObject(); var result = new JObject { ["FocusPointCosts"] = costs };
        if (op == "InstallLens")
        {
            var type = body.RequiredString("LensType"); if (!type.StartsWith("/Lotus/Types/Items/MiscItems/FocusLens", StringComparison.Ordinal) || GameData.Find("Resources", type) is null) throw new ApiException(400, "Unknown focus lens");
            var category = body.RequiredString("Category"); var gear = Inventory.Equipment(inv, category, body.RequiredString("WeaponId")); Inventory.AddCount(inv, "MiscItems", type, -1); gear["FocusLens"] = type;
            result = new JObject { ["weaponId"] = body["WeaponId"]!.DeepClone(), ["lensType"] = type };
            if (gear["AltWeaponModeId"] is JToken other) { Inventory.Equipment(inv, category == "Melee" ? "LongGuns" : "Melee", Wire.Id(other))["FocusLens"] = type; result["altWeaponModeId"] = Wire.Id(other); } return ApiResponse.Json(result);
        }
        if (op == "ConvertShard")
        {
            var polarity = body.RequiredString("Polarity"); if (!Polarities.Contains(polarity)) throw new ApiException(400, "Invalid focus polarity");
            var shards = body["Shards"] as JArray ?? new JArray(new JObject { ["ItemType"] = body.RequiredString("ShardType"), ["ItemCount"] = body.Integer("NumShards", 1, 100000) }); var gain = 0L;
            foreach (var shard in shards.OfType<JObject>()) { var type = shard.RequiredString("ItemType"); var count = shard.Integer("ItemCount", 1, 100000); var value = WorldData.Get("shardValues")[type]?.Value<long>() ?? throw new ApiException(400, "Not a focus shard"); gain = checked(gain + count * value); Inventory.AddCount(inv, "MiscItems", type, -count); }
            inv.Obj("FocusXP")[polarity] = checked(inv.Obj("FocusXP").Value<long>(polarity) + gain); return ApiResponse.Json(new JObject { ["FocusPointGains"] = new JObject { [polarity] = gain }, ["MiscItemCosts"] = shards.DeepClone() });
        }
        if (op == "SentTrainingAmplifier")
        {
            var type = body.RequiredString("StartingWeaponType"); if (type != TrainingAmpType) throw new ApiException(400, "Invalid training amplifier");
            var existing = inv.Array("OperatorAmps").FirstOrDefault(x => x.Value<string>("ItemType") == type); if (existing is not null) return ApiResponse.Json(existing);
            Inventory.OccupySlots(inv, "OperatorAmps", 1, false); var changes = Inventory.AddItem(inv, "OperatorAmps", type, 1); var gear = Inventory.Equipment(inv, "OperatorAmps", Wire.Id(changes["OperatorAmps"]![0]!["ItemId"]));
            gear["ModularParts"] = new JArray(new[] { "Grip", "Chassis", "Barrel" }.Select(x => "/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTraining" + x)); return ApiResponse.Json(gear);
        }
        if (op is "UnlockWay" or "ActivateWay")
        {
            if (op == "ActivateWay" && body["FocusType"]?.Type == JTokenType.Null) { inv["FocusAbility"] = ""; return ApiResponse.Json(new JObject()); }
            var type = body.RequiredString("FocusType"); var polarity = Polarity(type); JObject upgrade;
            if (op == "UnlockWay")
            {
                if (inv.Array("FocusUpgrades").Any(x => x.Value<string>("ItemType") == type)) throw new ApiException(409, "Focus school already unlocked");
                Spend(inv, polarity, string.IsNullOrEmpty(inv.Value<string>("FocusAbility")) ? 0 : 50000, costs);
                upgrade = new JObject { ["ItemType"] = type, ["IsActive"] = true, ["TotalCapacity"] = 5 }; inv.Array("FocusUpgrades").Add(upgrade);
                if (string.IsNullOrEmpty(inv.Value<string>("FocusAbility"))) inv["FocusAbility"] = type;
            }
            else { Owned(inv, type); inv["FocusAbility"] = type; upgrade = new JObject { ["ItemType"] = type }; result.Remove("FocusPointCosts"); }
            result["FocusUpgrade"] = upgrade.DeepClone(); return ApiResponse.Json(result);
        }
        if (op == "UnlockUpgrade")
        {
            var types = body["FocusTypes"] as JArray ?? new JArray(body.RequiredString("FocusType")); if (types.Count == 0) throw new ApiException(400, "Empty focus selection");
            foreach (var item in types)
            {
                var type = item.ToString(); if (inv.Array("FocusUpgrades").Any(x => x.Value<string>("ItemType") == type)) throw new ApiException(409, "Focus upgrade already unlocked");
                var cost = GameData.Find("FocusUpgrades", type)?.Value<long?>("baseFocusPointCost") ?? WorldData.Get("focusUnlockCostSupplementals")[type]?.Value<long>() ?? throw new ApiException(400, "Unknown focus upgrade"); Spend(inv, Polarity(type), cost, costs);
                var upgrade = new JObject { ["ItemType"] = type, ["Level"] = 0 }; if (body["ActivateUpgrade"] is JToken active) upgrade["IsActive"] = active.DeepClone(); inv.Array("FocusUpgrades").Add(upgrade);
                if (body["FocusTypes"] is null) result["FocusUpgrade"] = upgrade.DeepClone();
            }
            if (body["FocusTypes"] is not null) result["FocusTypes"] = types.DeepClone(); return ApiResponse.Json(result);
        }
        if (op == "LevelUpUpgrade")
        {
            var infos = body["FocusInfos"] as JArray ?? new JArray(new JObject { ["ItemType"] = body.RequiredString("FocusType"), ["Level"] = body.Integer("NewLvl", 1, 20), ["FocusXpCost"] = body.Integer("XPCost") });
            foreach (var info in infos.OfType<JObject>())
            {
                var type = info.RequiredString("ItemType"); var owned = Owned(inv, type); var level = info.Integer("Level", 1, GameData.Find("FocusUpgrades", type)?.Value<int?>("fusionLimit") ?? 3);
                if (level <= owned.Value<int>("Level")) throw new ApiException(409, "Focus level must increase"); Spend(inv, Polarity(type), info.Integer("FocusXpCost"), costs); owned["Level"] = level;
            }
            if (body["FocusInfos"] is not null) result["FocusInfos"] = infos.DeepClone(); else result["FocusUpgrade"] = new JObject { ["ItemType"] = body["FocusType"]!.DeepClone(), ["Level"] = body["NewLvl"]!.DeepClone() }; return ApiResponse.Json(result);
        }
        if (op == "UnbindUpgrade")
        {
            var types = body["FocusTypes"] as JArray ?? throw new ApiException(400, "Missing focus nodes"); if (types.Count == 0) throw new ApiException(400, "Empty focus selection");
            foreach (var item in types) { var type = item.ToString(); var owned = Owned(inv, type); if (owned.Value<bool>("IsUniversal") || owned.Value<int>("Level") < (GameData.Find("FocusUpgrades", type)?.Value<int>("fusionLimit") ?? 3)) throw new ApiException(409, "Focus node must be fully ranked and still bound"); Spend(inv, Polarity(type), 750000, costs); owned["IsUniversal"] = true; }
            const string shard = "/Lotus/Types/Gameplay/Eidolon/Resources/SentientShards/SentientShardBrilliantItem"; Inventory.AddCount(inv, "MiscItems", shard, -types.Count);
            result["FocusTypes"] = types.DeepClone(); result["MiscItemCosts"] = new JArray(new JObject { ["ItemType"] = shard, ["ItemCount"] = types.Count }); return ApiResponse.Json(result);
        }
        if (op == "IncreasePool" && version < 3)
        {
            var type = body.RequiredString("FocusType"); var capacity = (int)body.Integer("CurrentTotalCapacity", 5, 177);
            if (version == 1) { var owned = Owned(inv, type); if (capacity <= owned.Value<int>("TotalCapacity")) throw new ApiException(400, "Pool capacity must increase"); Spend(inv, Polarity(type), body.Integer("XPCost"), costs); owned["TotalCapacity"] = capacity; result["FocusUpgrade"] = new JObject { ["ItemType"] = type, ["TotalCapacity"] = capacity }; }
            else
            {
                var target = (int)body.Integer("NewTotalCapacity", capacity + 1, 177); if (capacity != (inv.Value<int?>("FocusCapacity") ?? 5)) throw new ApiException(409, "Focus pool changed");
                var cost = Enumerable.Range(capacity - 5, target - capacity).Sum(i => WorldData.Get("increasePoolCost")[i]!.Value<long>()); Spend(inv, Polarity(type), cost, costs); inv["FocusCapacity"] = target; result["TotalCapacity"] = target;
            }
            return ApiResponse.Json(result);
        }
        if (op == "UpdateUpgrade" && version < 3)
        {
            if (body["FocusInfos"] is JArray infos) { foreach (var item in infos.OfType<JObject>()) Owned(inv, item.RequiredString("ItemType"))["IsActive"] = item["IsActive"]?.DeepClone() ?? false; return ApiResponse.Json(new JObject { ["FocusInfos"] = infos.DeepClone() }); }
            foreach (var type in body["FocusTypes"] as JArray ?? []) Owned(inv, type.ToString())["IsActive"] = body.Value<bool>("ActivateUpgrade"); return ApiResponse.Json(body);
        }
        if (op is "UpgradeCooldown" or "UpdateCooldownReduction" && version == 1)
        {
            var type = body.RequiredString("FocusType"); var owned = Owned(inv, type); var delta = new JObject { ["ItemType"] = type };
            if (op == "UpgradeCooldown") { var tier = body.Integer("NewTier", owned.Value<int>("CooldownTier") + 1, 20); Spend(inv, Polarity(type), body.Integer("XPCost"), costs); owned["CooldownTier"] = tier; delta["CooldownTier"] = tier; }
            else { owned["IsCooldownReductionActive"] = body.Value<bool>("ActivateCooldown"); delta["IsCooldownReductionActive"] = owned["IsCooldownReductionActive"]!.DeepClone(); result.Remove("FocusPointCosts"); }
            result["FocusUpgrade"] = delta; return ApiResponse.Json(result);
        }
        throw new ApiException(400, "Unknown focus operation for client version");
    }
}