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("Node") == node) return goal.Value("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("BuildLabel")!, Now, syncOfficialEvents); foreach (var upload in progress.OfType()) { var id = Wire.Id(upload["_id"]); var goal = world.Array("Goals").OfType().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("Node")) { count += steel ? 4 : 3; best += steel ? 4 : 3; } if (goal.Value("Personal")) { var entries = inv.Array("PersonalGoalProgress"); var entry = entries.OfType().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(goal.Value("Best") ? "Best" : "Count"); var total = goal.Value("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(), reward, i)); if (goal["Reward"] is JObject final) thresholds.Add((goal.Value("Goal"), final, goals.Count)); if (goal["BonusReward"] is JObject bonus) thresholds.Add((goal.Value("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("credits")).ToString(CultureInfo.InvariantCulture) })); if (info?.Value("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("Best"), best); entry["Count"] = checked(entry.Value("Count") + count); } var clanGoal = goal["ClanGoal"]; var hasClanGoal = clanGoal is JArray tiers ? tiers.Any(x => x.Type == JTokenType.Integer && x.Value() > 0) : clanGoal?.Type == JTokenType.Integer && clanGoal.Value() > 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().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("Count"); var total = checked(previous + count); var meta = WorldData.Get("goalGuildRewardByTag")[tag]; if (meta is not null) { var thresholds = (JArray)meta["guildGoals"]![guild.Value("Tier") - 1]!; for (var i = 0; i < thresholds.Count; i++) if (previous < thresholds[i].Value() && total >= thresholds[i].Value()) 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()) { 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("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("Faction") == "FC_INFESTATION" && attacker != 0) throw new ApiException(400, "Invalid invasion allegiance"); var entries = inv.Array("QualifyingInvasions"); var entry = entries.OfType().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("Delta") + upload.Integer("Delta", -1, 1) * multiplier); entry["AttackerScore"] = checked(entry.Value("AttackerScore") + attacker); entry["DefenderScore"] = checked(entry.Value("DefenderScore") + defender); if (invasion.Value("Faction") == "FC_INFESTATION" || inv.Value("noDeathMarks")) continue; var faction = invasion.Value(attacker > 0 ? "Faction" : "DefenderFaction"); var info = WorldData.Get(faction != "FC_GRINEER" ? "grineerDeathSquadInfo" : "corpusDeathSquadInfo"); var flag = info.Value("booleanKey")!; var points = info.Value("numberKey")!; if (inv.Value(flag)) continue; inv[points] = checked(inv.Value(points) + attacker + defender); if (inv.Value(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().ToArray()) { var id = Wire.Id(progress["invasionId"]); var invasion = Invasion(id, GameVersion.For(account)); if (!invasion.Value("Completed")) continue; var attacker = progress.Value("AttackerScore") >= 3; var qualified = attacker || progress.Value("DefenderScore") >= 3; if (qualified && !account.Array("PaidInvasions").Any(x => x.ToString() == id) && invasion[attacker ? "AttackerReward" : "DefenderReward"]?["countedItems"] is JArray reward) { var faction = invasion.Value(attacker ? "Faction" : "DefenderFaction"); var grineer = faction == "FC_GRINEER"; foreach (var item in reward.OfType()) 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(); } } }