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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class EventApi(ItemCatalog catalog, TimeProvider clock, bool syncOfficialEvents = true)
{
    private long Now => clock.GetUtcNow().ToUnixTimeMilliseconds();
    public ApiResponse Handle(JObject state, JObject account, ApiRequest request)
    {
        if (request.ObjectBody()["Progress"] is not JArray progress) throw new ApiException(400, "Missing goal progress"); Goals(state, account, progress); return ApiResponse.Text();
    }
    public static string? MissionKey(JObject goal, string? node)
    {
        if (goal.Value<string>("Node") == node) return goal.Value<string>("MissionKeyName");
        var nodes = goal["ConcurrentNodes"] as JArray; var index = nodes?.Select(x => x.ToString()).ToList().IndexOf(node ?? "") ?? -1;
        return index >= 0 ? (goal["ConcurrentMissionKeyNames"] as JArray)?.ElementAtOrDefault(index)?.ToString() : null;
    }
    public void Goals(JObject state, JObject account, JArray progress, string? node = null, bool steel = false)
    {
        if (progress.Count == 0) return; var inv = account.Obj("Inventory"); var world = WorldApi.Generate(state, account.Value<string>("BuildLabel")!, Now, syncOfficialEvents);
        foreach (var upload in progress.OfType<JObject>())
        {
            var id = Wire.Id(upload["_id"]); var goal = world.Array("Goals").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["_id"]) == id) ?? throw new ApiException(400, "Unknown activity goal");
            var count = upload.Integer("Count"); var best = upload.Integer("Best"); var tag = goal.RequiredString("Tag");
            if (tag == "ShadowgrapherEvent" && node == goal.Value<string>("Node")) { count += steel ? 4 : 3; best += steel ? 4 : 3; }
            if (goal.Value<bool>("Personal"))
            {
                var entries = inv.Array("PersonalGoalProgress"); var entry = entries.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["goalId"]) == id);
                if (entry is null) { entry = new JObject { ["goalId"] = Wire.Oid(id), ["Tag"] = tag, ["Count"] = 0, ["Best"] = 0 }; entries.Add(entry); }
                var before = entry.Value<long>(goal.Value<bool>("Best") ? "Best" : "Count"); var total = goal.Value<bool>("Best") ? Math.Max(best, before) : checked(before + count);
                var thresholds = new List<(long Threshold, JObject Reward, int Index)>(); var goals = goal["InterimGoals"] as JArray ?? []; var rewards = goal["InterimRewards"] as JArray ?? [];
                for (var i = 0; i < Math.Min(goals.Count, rewards.Count); i++) if (rewards[i] is JObject reward) thresholds.Add((goals[i].Value<long>(), reward, i));
                if (goal["Reward"] is JObject final) thresholds.Add((goal.Value<long>("Goal"), final, goals.Count));
                if (goal["BonusReward"] is JObject bonus) thresholds.Add((goal.Value<long>("BonusGoal"), bonus, goals.Count + 1));
                var key = MissionKey(goal, node); var keyMessage = key is null ? null : WorldData.Get("goalMessagesByKey")[key] as JObject; var tagMessages = WorldData.Get("goalMessagesByTag")[tag] as JArray;
                foreach (var threshold in thresholds.Where(x => before < x.Threshold && x.Threshold <= total))
                {
                    var claimId = id + ":" + threshold.Index; if (account.Array("GoalRewardClaims").Any(x => x.ToString() == claimId)) continue;
                    var info = keyMessage ?? tagMessages?.ElementAtOrDefault(threshold.Index) as JObject;
                    var mail = info is null ? new JObject { ["sndr"] = "/Lotus/Language/Bosses/Ordis", ["sub"] = tag, ["msg"] = tag } : (JObject)info.DeepClone();
                    mail["highPriority"] = true; if (threshold.Reward["items"] is JArray items) mail["att"] = new JArray(items.Select(x => GameData.ItemType(x.ToString())));
                    if (threshold.Reward["countedItems"] is JArray counted) mail["countedAtt"] = counted.DeepClone(); if (threshold.Reward["credits"] is not null) mail["RegularCredits"] = threshold.Reward["credits"]!.DeepClone();
                    if (info?["arg"] is JArray args) mail["arg"] = new JArray(args.Select(x => new JObject { ["Key"] = x.ToString(), ["Tag"] = x.ToString() == "PLAYER_NAME" ? account.RequiredString("DisplayName") : (threshold.Reward.Value<long>("credits")).ToString(CultureInfo.InvariantCulture) }));
                    if (info?.Value<string>("minBuildLabel") is string build) { mail["minBuildVersion"] = GameVersion.Parse(build); mail.Remove("minBuildLabel"); }
                    InboxApi.Create(account, mail, clock.GetUtcNow()); account.Array("GoalRewardClaims").Add(claimId);
                }
                entry["Best"] = Math.Max(entry.Value<long>("Best"), best); entry["Count"] = checked(entry.Value<long>("Count") + count);
            }
            var clanGoal = goal["ClanGoal"];
            var hasClanGoal = clanGoal is JArray tiers ? tiers.Any(x => x.Type == JTokenType.Integer && x.Value<long>() > 0) : clanGoal?.Type == JTokenType.Integer && clanGoal.Value<long>() > 0;
            if (hasClanGoal && GuildApi.Find(state, Wire.Id(inv["GuildId"])) is JObject guild) GuildGoal(guild, goal, count);
        }
    }
    public static void GuildGoal(JObject guild, JObject goal, long count)
    {
        var id = Wire.Id(goal["_id"]); var tag = goal.RequiredString("Tag"); var progress = guild.Array("GoalProgress"); var entry = progress.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["goalId"]) == id);
        if (entry is null) { entry = new JObject { ["goalId"] = Wire.Oid(id), ["Tag"] = tag, ["Count"] = 0 }; progress.Add(entry); }
        var previous = entry.Value<long>("Count"); var total = checked(previous + count); var meta = WorldData.Get("goalGuildRewardByTag")[tag];
        if (meta is not null)
        {
            var thresholds = (JArray)meta["guildGoals"]![guild.Value<int>("Tier") - 1]!;
            for (var i = 0; i < thresholds.Count; i++) if (previous < thresholds[i].Value<long>() && total >= thresholds[i].Value<long>()) Inventory.AddCount(guild, "VaultDecoRecipes", meta["rewards"]![i]!.ToString(), 1);
        }
        entry["Count"] = total;
    }
    public void Invasions(JObject account, JArray progress)
    {
        var inv = account.Obj("Inventory");
        foreach (var upload in progress.OfType<JObject>())
        {
            var id = Wire.Id(upload["_id"]); var invasion = Invasion(id, GameVersion.For(account));
            if (account.Array("PaidInvasions").Any(x => x.ToString() == id)) throw new ApiException(409, "Invasion was already settled");
            var multiplier = inv.Value<bool>("finishInvasionsInOneMission") ? 3 : 1; var attacker = upload.Integer("AttackerScore", 0, 1) * multiplier; var defender = upload.Integer("DefenderScore", 0, 1) * multiplier;
            if (attacker + defender == 0 || attacker != 0 && defender != 0 || invasion.Value<string>("Faction") == "FC_INFESTATION" && attacker != 0) throw new ApiException(400, "Invalid invasion allegiance");
            var entries = inv.Array("QualifyingInvasions"); var entry = entries.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["invasionId"]) == id);
            if (entry is null) { entry = new JObject { ["invasionId"] = Wire.Oid(id) }; entries.Add(entry); }
            entry["Delta"] = checked(entry.Value<long>("Delta") + upload.Integer("Delta", -1, 1) * multiplier); entry["AttackerScore"] = checked(entry.Value<long>("AttackerScore") + attacker); entry["DefenderScore"] = checked(entry.Value<long>("DefenderScore") + defender);
            if (invasion.Value<string>("Faction") == "FC_INFESTATION" || inv.Value<bool>("noDeathMarks")) continue;
            var faction = invasion.Value<string>(attacker > 0 ? "Faction" : "DefenderFaction"); var info = WorldData.Get(faction != "FC_GRINEER" ? "grineerDeathSquadInfo" : "corpusDeathSquadInfo"); var flag = info.Value<string>("booleanKey")!; var points = info.Value<string>("numberKey")!;
            if (inv.Value<bool>(flag)) continue; inv[points] = checked(inv.Value<long>(points) + attacker + defender);
            if (inv.Value<long>(points) < 5) continue; inv[points] = 0; var repeat = inv[flag] is not null; inv[flag] = true;
            InboxApi.Create(account, new JObject { ["sndr"] = info["inboxSender"]!.DeepClone(), ["sub"] = info["inboxTitle"]!.DeepClone(), ["msg"] = info[repeat ? "inboxMessageRepeat" : "inboxMessage"]!.DeepClone(), ["icon"] = info["inboxIcon"]!.DeepClone(), ["highPriority"] = true }, clock.GetUtcNow());
        }
    }
    private JObject Invasion(string id, long build)
    {
        if (id.Length != 24 || id.Substring(8, 8) != "fd148cb8" || !uint.TryParse(id[..8], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var timestamp) || !int.TryParse(id[16..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var index)) throw new ApiException(400, "Invalid invasion identifier");
        var start = timestamp * 1000L; if (start < WorldData.Epoch || start > Now || (start - WorldData.Epoch) % WorldData.Day != 0) throw new ApiException(400, "Unknown invasion"); return WorldRotations.Invasion((int)((start - WorldData.Epoch) / WorldData.Day), index, Now, build);
    }
    public void Refresh(JObject account)
    {
        var inv = account.Obj("Inventory");
        foreach (var progress in inv.Array("QualifyingInvasions").OfType<JObject>().ToArray())
        {
            var id = Wire.Id(progress["invasionId"]); var invasion = Invasion(id, GameVersion.For(account)); if (!invasion.Value<bool>("Completed")) continue;
            var attacker = progress.Value<int>("AttackerScore") >= 3; var qualified = attacker || progress.Value<int>("DefenderScore") >= 3;
            if (qualified && !account.Array("PaidInvasions").Any(x => x.ToString() == id) && invasion[attacker ? "AttackerReward" : "DefenderReward"]?["countedItems"] is JArray reward)
            {
                var faction = invasion.Value<string>(attacker ? "Faction" : "DefenderFaction"); var grineer = faction == "FC_GRINEER";
                foreach (var item in reward.OfType<JObject>()) new ItemAcquisition(catalog, clock, account).Add(inv, item.RequiredString("ItemType"), (int)item.Integer("ItemCount", 1, 100_000));
                InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Menu/" + (grineer ? "Grineer" : "Corpus") + "InvasionLeader", ["sub"] = $"/Lotus/Language/G1Quests/{faction}_InvasionThankyouMessageSubject", ["msg"] = $"/Lotus/Language/G1Quests/{faction}_InvasionThankyouMessageBody", ["countedAtt"] = reward.DeepClone(), ["attVisualOnly"] = true, ["icon"] = "/Lotus/Interface/Icons/Npcs/" + (grineer ? "EliteRifleLancerAvatar.png" : "CrewmanNormal.png"), ["endDate"] = Wire.Date(Now + WorldData.Day) }, clock.GetUtcNow());
            }
            account.Array("PaidInvasions").UniqueAdd(id); progress.Remove();
        }
    }
}