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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class MissionApi(ItemCatalog catalog, TimeProvider clock, bool syncOfficialEvents = true, Func<JObject, ApiResponse>? replay = null)
{
    public ApiResponse Handle(JObject account, ApiRequest request, JObject? state = null)
    {
        var body = request.ObjectBody(); var inv = account.Obj("Inventory");
        var replayKey = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body.ToString(Formatting.None))));
        var isFinal = body.Value<bool>("EndOfMatchUpload");
        var checkpoint = isFinal || body["RewardInfo"] is not null || body["NemesisKillConvert"] is not null;
        var previous = (account["MissionReceipts"] as JArray)?.OfType<JObject>().FirstOrDefault(x => x.Value<string>("key") == replayKey);
        if (checkpoint && previous is not null) return replay is null ? MissionReceipts.Replay(previous) : replay(previous);
        var info = body["RewardInfo"] as JObject;
        var completedSortie = (inv["CompletedSorties"] as JArray ?? []).Any(x => x.ToString() == body.Value<string>("SortieId"));
        var changes = ApplyInventory(account, body, state);
        var failed = body["MissionStatus"] is not null ? body.Value<string>("MissionStatus") != "GS_SUCCESS" : body.Value<bool>("MissionFailed");
        var events = new EventApi(catalog, clock, syncOfficialEvents);
        if (body["GoalProgress"] is JArray goals) events.Goals(state ?? new JObject(), account, goals, info?.Value<string>("node"), body["Missions"]?.Value<int>("Tier") == 1);
        if (body["InvasionProgress"] is JArray invasions) events.Invasions(account, invasions);
        var rewards = new JArray(); var response = new JObject { ["MissionRewards"] = rewards, ["InventoryChanges"] = changes, ["AffiliationMods"] = body["AffiliationChanges"]?.DeepClone() ?? new JArray() };
        if (!failed && info is not null)
        {
            var node = GameData.Find("Regions", info.Value<string>("node"));
            var rotations = Rotations(info, node, body.Value<int?>("wagerTier"));
            var seed = info["rewardSeed"] is JObject seedObject ? seedObject["$numberLong"]?.ToString() : info["rewardSeed"]?.ToString();
            var rng = new SeededRng(~unchecked((ulong)(long.TryParse(seed, out var clientSeed) ? clientSeed : Wire.Seed())));
            var special = new MissionSpecialRewards(clock, syncOfficialEvents);
            var bounty = special.Bounty(account, body, info, rewards, (JArray)response["AffiliationMods"]!, response, rng, state);
            var duviri = WeeklyApi.Duviri(state ?? new JObject(), body, info, rewards, rng);
            new WeeklyApi(catalog, clock).Mission(account, body, info, rewards, response, rng);
            WeeklyApi.Purgatory(info, rewards, rng);
            MissionDrops.Stripped(inv, body, rewards, clock.GetUtcNow().ToUnixTimeMilliseconds());
            if (!bounty && !duviri && string.IsNullOrEmpty(info.Value<string>("sortieId")) && node is not null)
                foreach (var table in node["rewardManifests"] as JArray ?? []) Roll(table.ToString(), rotations, rewards, rng, info.Value<int>("VaultsCracked") > 0);
            var completionCredits = special.Sortie(account, info, rewards, completedSortie);
            special.Storm(account, info, node, rewards);
            if (!string.IsNullOrEmpty(info.Value<string>("alertId"))) completionCredits += MissionSpecialRewards.Alert(WorldApi.Generate(state ?? new JObject(), account.Value<string>("BuildLabel") ?? "2026.05.13.13.07", clock.GetUtcNow().ToUnixTimeMilliseconds(), syncOfficialEvents), inv, info, body, rewards);
            if (info.Value<string>("periodicMissionTag")?.StartsWith("HardDaily", StringComparison.Ordinal) == true) MissionSpecialRewards.Reward(rewards, "/Lotus/Types/Items/MiscItems/SteelEssence", 5);
            JObject? goal = null;
            if (info.Value<string>("goalId") is string goalId && goalId.Length > 0) goal = WorldApi.Generate(state ?? new JObject(), account.Value<string>("BuildLabel")!, clock.GetUtcNow().ToUnixTimeMilliseconds(), syncOfficialEvents).Array("Goals").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["_id"]) == goalId) ?? throw new ApiException(400, "Unknown activity goal");
            if (goal?.Value<string>("Tag")?.StartsWith("MechSurvival", StringComparison.Ordinal) == true && info["GoalProgressAmount"] is not null) MissionSpecialRewards.Reward(rewards, "/Lotus/Types/Items/MiscItems/MechSurvivalEventCreds", (int)(info.Integer("GoalProgressAmount", 0, 1_000_000) / 10));
            var keyMeta = GameData.Find("Keys", (goal is null ? null : EventApi.MissionKey(goal, info.Value<string>("node"))) ?? body.Value<string>("LevelKeyName"));
            if (keyMeta is not null)
            {
                if (keyMeta["missionReward"] is JObject fixedReward) completionCredits += FixedRewards(fixedReward, rewards, rotations);
                if (keyMeta["rewards"] is JArray keyRewards) completionCredits += KeyRewards(keyRewards, rewards);
                if (keyMeta["levelMission"] is JObject mission) completionCredits += CreditsForLevel(mission);
            }
            var completedNode = GameData.Find("Regions", body["Missions"]?.Value<string>("Tag"));
            if (completedNode is not null)
            {
                if (rotations.Count > 0 && completedNode.Value<string>("missionType") is not ("MT_JUNCTION" or "MT_LANDSCAPE") && body["Missions"]?.Value<string>("Tag") is not ("SolNode761" or "SolNode762" or "SolNode763")) completionCredits += CreditsForLevel(completedNode);
                if (completedNode["missionReward"] is JObject reward) completionCredits += FixedRewards(reward, rewards, rotations);
            }
            if (info.Value<bool>("nightmareMode") && node is not null)
            {
                var system = node.Value<int>("systemIndex");
                var rotation = node.Value<string>("missionType") == "MT_RESCUE" && info.Value<int>("rewardTier") > 0 ? info.Value<int>("rewardTier") : new[] { 6, 7, 8, 10, 11 }.Contains(system) ? 2 : new[] { 4, 9, 12, 14, 15, 16, 17, 18 }.Contains(system) ? 1 : 0;
                Roll("/Lotus/Types/Game/MissionDecks/NightmareModeRewards", [rotation], rewards);
            }
            var caches = info.Value<int>("EnemyCachesFound");
            if (caches > 0 && keyMeta?.Value<string>("cacheRewardManifest") is string cacheTable) Roll(cacheTable, Enumerable.Range(0, Math.Min(caches, 3)).ToArray(), rewards, identified: true);
            if (caches > 0 && node?.Value<string>("cacheRewardManifest") is string nodeCache) Roll(nodeCache, Enumerable.Range(0, Math.Min(caches, 3)).ToArray(), rewards, identified: true);
            var beforeRewards = inv.Value<long>("RegularCredits");
            MissionDrops.Relics(inv, GameVersion.For(account), rewards, rng);
            foreach (var reward in rewards.OfType<JObject>()) Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItem"), (int)reward.Integer("ItemCount", 1, 100_000), premium: true));
            var rngCredits = inv.Value<long>("RegularCredits") - beforeRewards;
            var droppedCredits = body.Value<long>("RegularCredits");
            var today = clock.GetUtcNow().ToUnixTimeSeconds() / 86400 * 86400;
            var daily = account.Value<long>("DailyFirstWinDate") != today;
            var bonus = completionCredits * (daily ? 2 : 1);
            var rawTotal = droppedCredits + bonus + rngCredits;
            var total = rawTotal;
            bool Booster(string kind) => inv.Array("Boosters").Any(x => x.Value<string>("ItemType") == "/Lotus/Types/Boosters/" + kind && x.Value<long>("ExpiryDate") > clock.GetUtcNow().ToUnixTimeSeconds());
            if (Booster("CreditBooster")) total *= 2;
            if (Booster("CreditBlessing")) total = (long)Math.Round(total * 1.25, MidpointRounding.AwayFromZero);
            Inventory.ChangeCurrency(inv, "RegularCredits", checked(bonus + total - rawTotal));
            if (daily) { account["DailyFirstWinDate"] = today; response["DailyMissionBonus"] = true; }
            response["MissionCredits"] = new JArray(droppedCredits, droppedCredits); response["CreditsBonus"] = new JArray(completionCredits, bonus); response["TotalCredits"] = new JArray(rawTotal, total);
        }
        else if (!failed)
        {
            MissionDrops.Stripped(inv, body, rewards, clock.GetUtcNow().ToUnixTimeMilliseconds());
            MissionDrops.Relics(inv, GameVersion.For(account), rewards, new SeededRng(Wire.Seed()));
            foreach (var reward in rewards.OfType<JObject>()) Inventory.Combine(changes, new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("StoreItem"), (int)reward.Integer("ItemCount", 1, 100_000), premium: true));
        }
        new NemesisApi(catalog, clock).Mission(account, body, response, failed);
        if (body["duviriCaveOffers"] is not null && body.Value<string>("MissionStatus") != "GS_QUIT") { inv.Obj("DuviriInfo")["Seed"] = Wire.Seed(); inv.Obj("DuviriInfo")["NumCompletions"] = checked(inv.Obj("DuviriInfo").Value<int>("NumCompletions") + 1); }
        if (!failed) ApplyConservation(inv, body, (JArray)response["AffiliationMods"]!);
        if (!failed && body["VoidTearParticipantsCurrWave"] is JObject relicWave) new RelicApi(catalog, clock).CompleteMission(account, relicWave, rewards);
        if (!failed && inv.Value<long>("pendingPremiumCredits") > 0)
        {
            InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Ordis", ["msg"] = "/Lotus/Language/Inbox/FoundItemsBody", ["sub"] = "/Lotus/Language/Inbox/FoundItemsTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Ordis.png", ["PremiumCredits"] = inv["pendingPremiumCredits"]!.DeepClone(), ["highPriority"] = true }, clock.GetUtcNow());
            inv.Remove("pendingPremiumCredits");
        }
        if (isFinal || body.Value<bool>("RJ")) inv["RewardSeed"] = Wire.Seed();
        if (failed) response = new JObject { ["InventoryJson"] = Inventory.ExportForGame(account, state?["worldState"] as JObject).ToString(Formatting.None), ["MissionRewards"] = new JArray() };
        else if (!new[] { "BMI", "TNT", "SSC", "RJ", "SS", "CMI", "EJC" }.Any(x => body.Value<bool>(x)))
        {
            if (info is null) response = new JObject();
            response["InventoryJson"] = Inventory.ExportForGame(account, state?["worldState"] as JObject).ToString(Formatting.None);
        }
        var result = ApiResponse.Json(response);
        if (checkpoint)
        {
            account.Array("MissionReceipts").Add(MissionReceipts.Capture(replayKey, result));
            while (account.Array("MissionReceipts").Count > 64) account.Array("MissionReceipts").RemoveAt(0);
        }
        return result;
    }
    private JObject ApplyInventory(JObject account, JObject body, JObject? state)
    {
        var inv = account.Obj("Inventory"); var delta = new JObject(); var acquire = new ItemAcquisition(catalog, clock, account);
        foreach (var update in (body["Upgrades"] as JArray ?? []).OfType<JObject>())
        {
            var type = update.RequiredString("ItemType"); var id = Wire.Id(update["ItemId"]); var fingerprintText = update.Value<string>("UpgradeFingerprint") ?? "{}";
            var fingerprint = fingerprintText.StartsWith('{') ? JObject.Parse(fingerprintText) : new JObject { ["lvl"] = int.TryParse(fingerprintText.Split('|')[0].Split('=').Last(), out var oldLevel) ? oldLevel : 0 };
            if (id is "" or "000000000000000000000000")
            {
                if (fingerprint.Value<int>("lvl") > 0 && type.StartsWith("/Lotus/Upgrades/Mods/Fusers/", StringComparison.Ordinal)) inv.Array("Upgrades").Add(new JObject { ["ItemId"] = Wire.Oid(Wire.NewId()), ["ItemType"] = type, ["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None) });
                else Inventory.AddCount(inv, "RawUpgrades", type, Math.Abs(update.Value<long?>("ItemCount") ?? 1));
            }
            else
            {
                var owned = RivenApi.Owned(inv, update["ItemId"]); if (owned.Value<string>("ItemType") != type) throw new ApiException(400, "Mismatched mission mod");
                var current = JObject.Parse(owned.Value<string>("UpgradeFingerprint") ?? "{}");
                if (current["challenge"] is JObject challenge && fingerprint["challenge"] is JObject progress)
                {
                    var count = progress.Value<double>("Progress"); if (!double.IsFinite(count) || count < 0 || count > challenge.Value<double>("Required")) throw new ApiException(400, "Invalid Riven challenge progress");
                    challenge["Progress"] = count; owned["UpgradeFingerprint"] = current.ToString(Formatting.None);
                }
            }
        }
        foreach (var key in Inventory.EquipmentKeys) if (body[key] is JArray gear) InventoryProgress.Equipment(inv, key, gear);
        if (body["RegularCredits"] is not null) Inventory.ChangeCurrency(inv, "RegularCredits", body.Integer("RegularCredits", -999_999_999));
        if (body["QuestKeys"] is JArray quests) Inventory.Combine(delta, new QuestApi(catalog, clock).Update(account, quests));
        if (body["Missions"] is JObject mission) InventoryProgress.Mission(inv, mission);
        if (body["AffiliationChanges"] is JArray affiliations) InventoryProgress.Affiliations(inv, affiliations);
        foreach (var category in Inventory.CountedKeys.Append("BonusMiscItems"))
            foreach (var item in (body[category] as JArray ?? []).OfType<JObject>())
            {
                var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", -999_999_999);
                var target = category == "BonusMiscItems" ? "MiscItems" : category;
                if (target == "Consumables" && count < 0 && inv.Value<bool>("dontSubtractConsumables")) continue;
                if (target == "MiscItems" && GameData.Find("Recipes", type) is not null) target = "Recipes";
                if (target == "MiscItems") InventoryProgress.Misc(inv, type, count); else Inventory.AddCount(inv, target, type, count);
            }
        foreach (var fusion in (body["FusionBundles"] as JArray ?? []).OfType<JObject>()) Inventory.Combine(delta, acquire.Add(inv, fusion.RequiredString("ItemType"), (int)fusion.Integer("ItemCount", 1, 100_000)));
        foreach (var type in body["CollectedQuestKeys"] as JArray ?? []) Inventory.Combine(delta, acquire.Add(inv, type.ToString()));
        foreach (var key in new[] { "EmailItems", "WeaponSkins" }) foreach (var item in (body[key] as JArray ?? []).OfType<JObject>()) Inventory.Combine(delta, acquire.Add(inv, item.RequiredString("ItemType")));
        foreach (var booster in (body["Boosters"] as JArray ?? []).OfType<JObject>()) InventoryProgress.Booster(inv, booster.RequiredString("ItemType"), booster.Integer("ExpiryDate"), clock.GetUtcNow());
        if (body["FocusXpIncreases"] is JArray focus) InventoryProgress.Focus(inv, focus);
        if (body["PlayerSkillGains"] is JObject skills) foreach (var key in new[] { "LPP_SPACE", "LPP_DRIFTER" }) if (skills[key] is not null) inv.Obj("PlayerSkills")[key] = checked(inv.Obj("PlayerSkills").Value<long>(key) + skills.Integer(key));
        if (body["LastRegionPlayed"] is JToken region) inv["LastRegionPlayed"] = region.DeepClone();
        foreach (var (key, id) in new[] { ("EvolutionProgress", "ItemType"), ("CustomMarkers", "tag"), ("DiscoveredMarkers", "tag") })
            foreach (var update in (body[key] as JArray ?? []).OfType<JObject>()) Inventory.Upsert(inv.Array(key == "CollectibleScans" ? "CollectibleSeries" : key), id, update);
        foreach (var scan in (body["LoreFragmentScans"] as JArray ?? []).OfType<JObject>())
        {
            var entry = inv.Array("LoreFragmentScans").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == scan.Value<string>("ItemType"));
            if (entry is null) inv.Array("LoreFragmentScans").Add(scan.DeepClone()); else entry["Progress"] = checked(entry.Value<long>("Progress") + scan.Integer("Progress"));
        }
        foreach (var scan in (body["LibraryScans"] as JArray ?? []).OfType<JObject>())
            if (inv["LibraryActiveDailyTaskInfo"] is JObject task && (task["EnemyTypes"] as JArray ?? []).Any(x => x.ToString() == scan.Value<string>("EnemyType"))) task["Scans"] = checked(task.Value<long>("Scans") + scan.Integer("Count"));
        MissionState.Apply(account, body, delta, catalog, clock);
        if (body["KeyToRemove"] is JToken keyToRemove && inv.Value<bool?>("dontSubtractKeys") != true && (body.Value<bool?>("EndOfMatchUpload") ?? true) && (body["KeyOwner"] is null || Wire.Id(body["KeyOwner"]) == account.Value<string>("id"))) Inventory.AddCount(inv, "LevelKeys", keyToRemove.ToString(), -1);
        if (body["creditsFee"] is not null && inv.Value<bool?>("noNodeEntryFees") != true) Inventory.Combine(delta, Inventory.ChangeCurrency(inv, "RegularCredits", -body.Integer("creditsFee")));
        if (body["Missions"] is JObject played && body.Value<bool>("EndOfMatchUpload") && GameData.Find("Regions", played.Value<string>("Tag"))?["miscItemFee"] is JObject fee && inv.Value<bool?>("noNodeEntryFees") != true) InventoryProgress.Misc(inv, fee.RequiredString("ItemType"), -fee.Integer("ItemCount"));
        var challengeResult = new ChallengeApi(catalog, clock).Apply(account, body, state); Inventory.Combine(delta, (JObject)challengeResult["InventoryChanges"]!);
        foreach (var (key, value) in new[] { ("CompletedSorties", body.Value<string>("SortieId")), ("CompletedSyndicates", body.Value<string>("SyndicateId")) }) if (!string.IsNullOrEmpty(value)) inv.Array(key).UniqueAdd(value);
        foreach (var property in body.Properties().Where(x => x.Name.StartsWith("DailyAffiliation", StringComparison.Ordinal))) inv[property.Name] = checked(inv.Value<long>(property.Name) - property.Value.Value<long>());
        return delta;
    }
    private static void ApplyConservation(JObject inv, JObject body, JArray affiliations)
    {
        foreach (var animal in (body["CapturedAnimals"] as JArray ?? []).OfType<JObject>())
        {
            var meta = GameData.Find("Animals", animal.RequiredString("AnimalType"))?["conservation"] as JObject ?? throw new ApiException(400, "Unknown conservation animal"); var count = animal.Integer("Count", 1, 1000);
            var tags = animal["NumTags"] is null ? 0 : animal.Integer("NumTags", 0, 100); var extra = animal["NumExtraRewards"] is null ? 0 : animal.Integer("NumExtraRewards", 0, 100);
            if (tags > 0) InventoryProgress.Misc(inv, meta.RequiredString("itemReward"), checked(tags * count));
            if (extra > 0 && meta.Value<string>("woundedAnimalReward") is string item) InventoryProgress.Misc(inv, item, checked(extra * count));
            if (meta.Value<int>("standingReward") > 0) Standing.Add(inv, body["Missions"]?.Value<string>("Tag") == "SolNode129" ? "SolarisSyndicate" : "CetusSyndicate", new[] { 2, 1.5, 1 }[(int)animal.Integer("CaptureRating", 0, 2)] * meta.Value<int>("standingReward") * count, affiliations);
        }
    }
    public static IReadOnlyList<int> Rotations(JObject info, JObject? node, int? tierOverride = null)
    {
        var vaults = info.Value<int>("VaultsCracked"); if (vaults > 0) return Enumerable.Range(0, Math.Min(vaults, 3)).Select(x => Math.Min(x, 2)).ToArray();
        var mission = node?.Value<string>("missionType");
        if (mission == "MT_ARTIFACT") return (info["rewardTierOverrides"] as JArray ?? []).Select(x => x.Value<int>()).ToArray();
        if (mission == "MT_RESCUE" && info["rewardTier"] is not null) return [info.Value<int>("rewardTier")];
        if (node?.Value<string>("missionName") is "/Lotus/Language/Missions/MissionName_Railjack" or "/Lotus/Language/Missions/MissionName_RailjackVolatile" or "/Lotus/Language/Missions/MissionName_RailjackExterminate" or "/Lotus/Language/Missions/MissionName_RailjackAssassinate" or "/Lotus/Language/Missions/MissionName_Assassination" or "/Lotus/Language/Missions/MissionName_Exterminate") return [0];
        var count = (info["rewardQualifications"] as JArray)?.Count ?? 0;
        if (count == 0 && mission is not ("MT_ENDLESS_EXTERMINATION" or "MT_RAILJACK")) return [0];
        if (count > 1000) throw new ApiException(400, "Too many mission rotations");
        int[] pattern = tierOverride is int tier ? [tier] : [0, 0, 1, 2];
        return Enumerable.Range(0, count).Select(i => pattern[i % pattern.Length]).ToArray();
    }
    private static long CreditsForLevel(JObject node) => node.Value<int>("minEnemyLevel") is > 0 and var level ? 1000 + (level - 1) * 100L : 0;
    public static void Roll(string table, IReadOnlyList<int> rotations, JArray rewards, SeededRng? rng = null, bool identified = false)
    {
        if (GameData.Table("Rewards")[table] is not JArray deck) throw new ApiException(400, "Unknown mission reward table");
        foreach (var tier in rotations)
        {
            if (tier < 0 || tier >= deck.Count || deck[tier] is not JArray pool) throw new ApiException(400, "Invalid reward rotation");
            var item = rng is null ? SeededRng.RewardAt(pool, Random.Shared.NextDouble()) : rng.Reward(pool); rng?.Float();
            if (item is null) continue;
            var drop = new JObject { ["StoreItem"] = item["type"]!.DeepClone(), ["ItemCount"] = item["itemCount"]!.DeepClone() };
            if (identified) drop["FromEnemyCache"] = true; rewards.Add(drop);
        }
    }
    public static long FixedRewards(JObject data, JArray rewards, IReadOnlyList<int>? rotations = null)
    {
        foreach (var item in data["items"] as JArray ?? []) rewards.Add(new JObject { ["StoreItem"] = item.DeepClone(), ["ItemCount"] = 1 });
        foreach (var item in data["countedItems"] as JArray ?? []) rewards.Add(new JObject { ["StoreItem"] = GameData.StoreType(item.Value<string>("ItemType")!), ["ItemCount"] = item["ItemCount"]!.DeepClone() });
        foreach (var item in data["countedStoreItems"] as JArray ?? []) rewards.Add(item.DeepClone());
        if (data.Value<string>("droptable") is string table) Roll(table, rotations ?? [0], rewards);
        return data.Value<long>("credits");
    }
    private static long KeyRewards(JArray data, JArray rewards)
    {
        var credits = 0L;
        foreach (var item in data)
            if (item.Value<string>("rewardType") == "RT_CREDITS") credits += item.Value<long>("amount");
            else rewards.Add(new JObject { ["StoreItem"] = item["itemType"]!.DeepClone(), ["ItemCount"] = item.Value<string>("rewardType") == "RT_RESOURCE" ? item.Value<int>("amount") : 1 });
        return credits;
    }
}