using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class StatsApi(TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["uploadController", "viewController", "leaderboardGetController", "leaderboardU10Controller", "leaderboardPostController", "getProfileViewingDataGetController", "getProfileViewingDataPostController"];
private static readonly Dictionary<string, string> WeaponFields = new() { ["FIRE_WEAPON"] = "fired", ["HIT_ENTITY_ITEM"] = "hits", ["HEADSHOT_ITEM"] = "headshots", ["KILL_ENEMY_ITEM"] = "kills", ["KILL_ASSIST_ITEM"] = "assists" };
private static readonly Dictionary<string, string> EnemyFields = new() { ["KILL_ENEMY"] = "kills", ["EXECUTE_ENEMY"] = "executions", ["HEADSHOT"] = "headshots", ["KILL_ASSIST"] = "assists", ["DIE"] = "deaths" };
private static readonly Dictionary<string, string> MissionFields = new() { ["GS_SUCCESS"] = "MissionsCompleted", ["GS_QUIT"] = "MissionsQuit", ["GS_FAILURE"] = "MissionsFailed", ["GS_INTERRUPTED"] = "MissionsInterrupted", ["GS_DUMPED"] = "MissionsDumped" };
private static readonly HashSet<string> EventScores = ["Halloween16", "AmalgamEventScoreMax", "Halloween19ScoreMax", "FlotillaEventScore", "FlotillaSpaceBadgesTier1", "FlotillaSpaceBadgesTier2", "FlotillaSpaceBadgesTier3", "FlotillaGroundBadgesTier1", "FlotillaGroundBadgesTier2", "FlotillaGroundBadgesTier3", "MechSurvivalScoreMax", "HiveEventScore"];
public ApiResponse Handle(string controller, JObject state, JObject? account, ApiRequest request)
{
if (controller.StartsWith("leaderboard", StringComparison.Ordinal)) return Leaderboard(controller, state, request);
if (controller == "uploadController") { Update(state, account!, request.ObjectBody()); return ApiResponse.Text(); }
var body = request.ObjectBody();
if (request.Q("guild") == "1" || request.Q("guildId") is not null || body["GuildId"] is not null)
{
var guildId = request.Q("guildId") ?? body.Value<string>("GuildId") ?? request.Q("id") ?? request.Q("lookupId") ?? request.Q("accountId"); var guild = GuildApi.Find(state, guildId ?? "") ?? throw new ApiException(409, "Could not find guild");
var profile = GuildProfile(state, guild); return ApiResponse.Json(controller == "viewController" ? profile["Stats"] : profile);
}
var id = controller == "viewController" ? request.Q("id") ?? request.Q("lookupId") ?? request.Q("accountId") : request.Q("playerId") ?? body.Value<string>("AccountId");
var target = id is null ? null : state.Obj("accounts")[id] as JObject;
if (target is null) throw new ApiException(409, "Could not find requested account");
return ApiResponse.Json(controller == "viewController" ? View(target) : Profile(target));
}
public void Update(JObject state, JObject account, JObject body)
{
var stats = account.Obj("Stats");
if (body["add"] is JObject add)
{
foreach (var p in add.Properties())
{
if (WeaponFields.TryGetValue(p.Name, out var weaponField)) UpdateArray(stats, "Weapons", weaponField, p.Value);
else if (EnemyFields.TryGetValue(p.Name, out var enemyField))
{
foreach (var entry in Entries(p.Value))
{
var enemy = Entry(stats.Array("Enemies"), entry.Name); var value = Number(entry.Value);
if (p.Name == "KILL_ENEMY" && add["CAPTURE_ENEMY"] is JObject captures && captures[entry.Name] is JToken capture)
{ var captured = Number(capture); Increment(enemy, "captures", captured); value = Math.Max(0, value - captured); }
Increment(enemy, enemyField, value);
if (p.Name == "DIE") Increment(stats, "Deaths", value);
}
}
else switch (p.Name)
{
case "MISSION_COMPLETE": foreach (var entry in Entries(p.Value)) if (MissionFields.TryGetValue(entry.Name, out var field)) Increment(stats, field, Number(entry.Value)); break;
case "PICKUP_ITEM": Increment(stats, "PickupCount", Entries(p.Value).Sum(x => Number(x.Value))); break;
case "MELEE_KILL": Increment(stats, "MeleeKills", Entries(p.Value).Sum(x => Number(x.Value))); break;
case "SCAN": UpdateArray(stats, "Scans", "scans", p.Value); break;
case "USE_ABILITY": UpdateArray(stats, "Abilities", "used", p.Value); break;
case "INCOME": Increment(stats, "Income", Number(p.Value)); break;
case "HiveEventScoreSum": Increment(stats, p.Name, Number(p.Value)); break;
case "CIPHER":
if (p.Value["0"] is JToken failed) Increment(stats, "CiphersFailed", Number(failed));
if (p.Value["1"] is JToken solved) Increment(stats, "CiphersSolved", Number(solved));
break;
}
}
}
if (body["timers"] is JObject timers)
{
if (timers["EQUIP_WEAPON"] is JToken equipped) UpdateArray(stats, "Weapons", "equipTime", equipped);
if (timers["CURRENT_MISSION_TIME"] is JToken time) Increment(stats, "TimePlayedSec", Number(time));
else if (timers["MISSION_TIME"] is JObject missions) Increment(stats, "TimePlayedSec", missions.Properties().Sum(x => Number(x.Value)));
if (timers["CIPHER_TIME"] is JToken cipherTime) Increment(stats, "CipherTime", Number(cipherTime));
}
if (body["max"] is JObject maxima)
{
foreach (var p in maxima.Properties())
{
if (p.Name == "WEAPON_XP") UpdateArray(stats, "Weapons", "xp", p.Value, true);
else if (p.Name is "MISSION_SCORE" or "RACE_SCORE")
{
foreach (var entry in Entries(p.Value))
{
var name = entry.Name.Replace("/Lotus/Types/Keys/", "", StringComparison.Ordinal); var score = Number(entry.Value);
var item = p.Name == "MISSION_SCORE" ? Entry(stats.Array("Missions"), name) : stats.Obj("Races").Obj(name);
item["highScore"] = Math.Max(item.Value<double>("highScore"), score);
Submit(state, account, p.Name == "MISSION_SCORE" ? "weekly" : "daily", name, score);
}
}
else if (p.Name == "OlliesCrashCourseScore")
{
var score = Number(p.Value); var previous = stats.Value<double>(p.Name); var acquire = new ItemAcquisition(new ItemCatalog(), clock, account);
if (previous == 0) acquire.Add(account.Obj("Inventory"), "/Lotus/Types/Items/EmailItems/PlayedOlliesCrashCourseEmailItem");
if (score >= 9991000 && previous < 9991000) acquire.Add(account.Obj("Inventory"), "/Lotus/Types/Items/EmailItems/BeatOlliesCrashCourseInNinetySecEmailItem");
stats[p.Name] = Math.Max(previous, score); Submit(state, account, "weekly", p.Name, score);
}
else if (EventScores.Contains(p.Name) || p.Name is "ZephyrScore" or "CaliberChicksScore" or "SentinelGameScore" or "DojoObstacleScore")
{
var value = Number(p.Value); stats[p.Name] = Math.Max(stats.Value<double>(p.Name), value);
if (EventScores.Contains(p.Name)) Submit(state, account, "events", p.Name == "HiveEventScore" ? "HiveEvent" : p.Name, value);
else if (p.Name is "SentinelGameScore" or "DojoObstacleScore") Submit(state, account, "weekly", p.Name, value);
}
}
}
if (body["set"] is JObject set)
foreach (var (key, field) in new[] { ("ELO_RATING", "Rating"), ("RANK", "Rank"), ("PLAYER_LEVEL", "PlayerLevel") })
if (set[key] is JToken value) stats[field] = Number(value);
}
public static JObject View(JObject account)
{
var result = (JObject)account.Obj("Stats").DeepClone();
foreach (var xp in account.Obj("Inventory").Array("XPInfo").OfType<JObject>()) Entry(result.Array("Weapons"), xp.RequiredString("ItemType"))["xp"] = xp["XP"];
return FormatNumbers(result);
}
private static JObject Profile(JObject account)
{
var inv = account.Obj("Inventory");
var equipment = new JObject { ["WeaponSkins"] = new JArray(), ["XPInfo"] = inv.Array("XPInfo").DeepClone() };
var profile = new JObject { ["AccountId"] = Wire.Oid(account.Value<string>("id")!), ["DisplayName"] = account["DisplayName"], ["PlayerLevel"] = AccountRules.Mastery(inv), ["LoadOutInventory"] = equipment, ["Created"] = Wire.Date(Wire.DateMs(account["Created"])), ["MigratedToConsole"] = false };
foreach (var name in new[] { "PlayerSkills", "ChallengeProgress", "DeathMarks", "Harvestable", "DeathSquadable", "TitleType", "Missions", "Affiliations", "DailyFocus", "Wishlist", "Alignment", "Staff", "Founder", "Guide", "Moderator", "Partner", "Accolades" }.Concat(inv.Properties().Where(x => x.Name.StartsWith("DailyAffiliation", StringComparison.Ordinal)).Select(x => x.Name)))
if (inv[name] is JToken value) profile[name] = value.DeepClone();
var loadoutId = Wire.Id(inv.Array("CurrentLoadOutIds").FirstOrDefault());
var loadout = account.Obj("Loadouts").Array("NORMAL").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == loadoutId);
if (loadout is not null)
{
profile["LoadOutPreset"] = loadout.DeepClone(); ((JObject)profile["LoadOutPreset"]!).Remove("ItemId");
foreach (var (shortName, category) in new[] { ("s", "Suits"), ("p", "Pistols"), ("l", "LongGuns"), ("m", "Melee") })
{
var item = inv.Array(category).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(loadout[shortName]?["ItemId"]));
if (item is null) continue;
var copy = (JObject)item.DeepClone(); equipment[category] = new JArray(copy);
foreach (var config in copy.Array("Configs").OfType<JObject>())
if (config["Skins"] is JArray skins)
for (var i = 0; i < skins.Count; i++)
{
var type = skins[i]!.ToString();
if (type.Length == 24) type = inv.Array("WeaponSkins").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == type)?.Value<string>("ItemType") ?? "";
skins[i] = type;
if (type.Length > 0) equipment.Array("WeaponSkins").UniqueAdd(new JObject { ["ItemType"] = type });
}
}
}
return new JObject { ["Results"] = new JArray(profile), ["TechProjects"] = new JArray(), ["XpComponents"] = new JArray(), ["Stats"] = View(account) };
}
private static JObject GuildProfile(JObject state, JObject guild)
{
var members = guild.Array("Members").Where(x => x.Value<int>("status") == 0).Select(x => state["accounts"]?[x.Value<string>("accountId") ?? ""] as JObject).OfType<JObject>().ToArray(); var combined = new JObject();
foreach (var member in members)
{
var stats = View(member);
foreach (var property in stats.Properties().Where(x => x.Value.Type is JTokenType.Integer or JTokenType.Float)) Increment(combined, property.Name, property.Value.Value<double>());
foreach (var array in new[] { "Weapons", "Enemies", "Scans", "Missions", "PVP" })
foreach (var item in (stats[array] as JArray ?? []).OfType<JObject>())
{
var target = Entry(combined.Array(array), item.RequiredString("type")); foreach (var field in item.Properties().Where(x => x.Value.Type is JTokenType.Integer or JTokenType.Float)) Increment(target, field.Name, field.Value.Value<double>());
}
}
var results = new JArray(members.Take(4).Select(x => Profile(x)["Results"]![0]!.DeepClone()));
if (results.First is JObject first)
{
first["GuildId"] = Wire.Oid(guild.RequiredString("id")); foreach (var (from, to) in new[] { ("Name", "GuildName"), ("Tier", "GuildTier"), ("XP", "GuildXp"), ("Class", "GuildClass"), ("Emblem", "GuildEmblem") }) first[to] = guild[from]?.DeepClone();
}
var components = new JArray();
foreach (var claimed in guild["ClaimedXP"] as JArray ?? [])
{
var table = (JObject)GameData.Table("DojoRecipes")[claimed.ToString().EndsWith(".level", StringComparison.Ordinal) ? "rooms" : "decos"]!; var recipe = table.Properties().FirstOrDefault(x => x.Value.Value<string>("resultType") == claimed.ToString()); if (recipe is not null) components.Add(new JObject { ["StoreTypeName"] = GameData.StoreType(recipe.Name) });
}
var projects = (JArray)guild.Array("TechProjects").DeepClone(); foreach (var project in projects.OfType<JObject>()) project.Remove("CompletionProcessed");
return new JObject { ["Results"] = results, ["Stats"] = FormatNumbers(combined), ["TechProjects"] = projects, ["XpComponents"] = components };
}
private static JObject FormatNumbers(JObject stats)
{
// Native integer fields reject JSON such as 1.0. Keep timer fractions,
// but serialize integral values as integers, as the upstream server does.
foreach (var token in stats.Descendants().OfType<JValue>().Where(x => x.Type == JTokenType.Float).ToArray())
{
var value = token.Value<double>();
if (double.IsFinite(value) && value == Math.Truncate(value) && Math.Abs(value) <= 9_007_199_254_740_991)
token.Replace(new JValue((long)value));
}
return stats;
}
private void Submit(JObject state, JObject account, string schedule, string name, double score)
{
var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); const long week = 604800000; const long monday = 1734307200000;
var expiry = schedule == "daily" ? (now / 86400000 + 1) * 86400000 : schedule == "weekly" ? (now - monday) / week * week + monday + week : long.MaxValue;
var entry = state.Obj("leaderboards").Obj($"{schedule}.accounts.{name}").Obj(account.Value<string>("id")!);
var previous = entry.Value<long>("expiry") > now ? entry.Value<double>("score") : 0;
var guildId = Wire.Id(account["Inventory"]?["GuildId"]); var guild = GuildApi.Find(state, guildId);
if (guild is not null && guild.Array("Members").Any(x => x.Value<string>("accountId") == account.Value<string>("id") && x.Value<int>("status") == 0))
{
var clan = state.Obj("leaderboards").Obj($"{schedule}.guilds.{name}").Obj(guildId); var prior = clan.Value<long>("expiry") > now ? clan.Value<double>("score") : 0;
clan["score"] = schedule == "events" ? prior + Math.Max(0, score - previous) : Math.Max(prior, score); clan["expiry"] = expiry; clan["name"] = guild["Name"]!.DeepClone(); clan["guildTier"] = guild["Tier"]!.DeepClone(); entry["guildId"] = guildId;
}
else entry.Remove("guildId");
entry["score"] = Math.Max(previous, score); entry["expiry"] = expiry; entry["name"] = account["DisplayName"];
}
private ApiResponse Leaderboard(string controller, JObject state, ApiRequest request)
{
var body = request.ObjectBody();
var guildId = request.Q("guildId") ?? body.Value<string>("guildId"); var guildTierText = request.Q("guildTier") ?? body.Value<string>("guildTier"); var guildTier = guildTierText is null ? 0 : int.Parse(guildTierText); if (guildTier is < 0 or > 5) throw new ApiException(400, "Invalid guild tier");
var kind = guildTier > 0 || guildId is not null ? "guilds" : "accounts";
var name = request.Q("field") ?? body.RequiredString("field");
if (controller == "leaderboardGetController" && !name.StartsWith("archived.", StringComparison.Ordinal)) name = "archived." + name;
name = name.Replace("archived.", "events." + kind + ".", StringComparison.Ordinal);
if (!name.Contains('.')) name = "events." + kind + "." + name;
var before = int.Parse(request.Q("before") ?? body.Value<string>("before") ?? "0");
var after = int.Parse(request.Q("after") ?? body.Value<string>("after") ?? "20");
if (before is < 0 or > 1000 || after is < 0 or > 1000) throw new ApiException(400, "Leaderboard page is outside limits");
var pivot = request.Q("pivotId") ?? request.Q("pivotAccountId") ?? body.Value<string>("pivotId");
var entries = (state.Obj("leaderboards")[name] as JObject ?? new()).Properties().Where(x => x.Value.Value<long>("expiry") > clock.GetUtcNow().ToUnixTimeMilliseconds() && (guildTier == 0 || x.Value.Value<int>("guildTier") == guildTier) && (guildId is null || x.Value.Value<string>("guildId") == guildId)).OrderByDescending(x => x.Value.Value<double>("score")).ThenBy(x => x.Name, StringComparer.Ordinal).ToArray();
var start = before; var count = Math.Max(0, after - before);
if (pivot is not null)
{
var index = Array.FindIndex(entries, x => x.Name == pivot); start = Math.Max(0, index - before); count = index < 0 ? 0 : index - start + 1 + after;
}
var results = new JArray(entries.Skip(start).Take(count).Select((x, i) => controller == "leaderboardGetController"
? new JObject { ["DisplayName"] = x.Value["name"], ["score"] = x.Value["score"], ["rank"] = start + i + 1 }
: new JObject { ["_id"] = x.Name, ["n"] = x.Value["name"], ["s"] = x.Value["score"], ["r"] = start + i + 1 }));
return ApiResponse.Json(new JObject { [controller == "leaderboardGetController" ? "players" : "results"] = results });
}
private static IEnumerable<JProperty> Entries(JToken token) => token is JObject obj ? obj.Properties() : throw new ApiException(400, "Expected keyed statistics");
private static double Number(JToken token)
{
if (token.Type is not (JTokenType.Integer or JTokenType.Float)) throw new ApiException(400, "Expected numeric statistic");
var value = token.Value<double>(); if (!double.IsFinite(value) || value is < 0 or > 1e15) throw new ApiException(400, "Invalid statistic"); return value;
}
private static void Increment(JObject obj, string key, double value) => obj[key] = obj.Value<double>(key) + value;
private static JObject Entry(JArray array, string type)
{
var entry = array.OfType<JObject>().FirstOrDefault(x => x.Value<string>("type") == type);
if (entry is null) { entry = new JObject { ["type"] = type }; array.Add(entry); } return entry;
}
private static void UpdateArray(JObject stats, string key, string field, JToken data, bool maximum = false)
{
foreach (var entry in Entries(data))
{
var item = Entry(stats.Array(key), entry.Name); var value = Number(entry.Value);
item[field] = maximum ? Math.Max(item.Value<double>(field), value) : item.Value<double>(field) + value;
}
}
}
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class StatsApi(TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["uploadController", "viewController", "leaderboardGetController", "leaderboardU10Controller", "leaderboardPostController", "getProfileViewingDataGetController", "getProfileViewingDataPostController"];
private static readonly Dictionary<string, string> WeaponFields = new() { ["FIRE_WEAPON"] = "fired", ["HIT_ENTITY_ITEM"] = "hits", ["HEADSHOT_ITEM"] = "headshots", ["KILL_ENEMY_ITEM"] = "kills", ["KILL_ASSIST_ITEM"] = "assists" };
private static readonly Dictionary<string, string> EnemyFields = new() { ["KILL_ENEMY"] = "kills", ["EXECUTE_ENEMY"] = "executions", ["HEADSHOT"] = "headshots", ["KILL_ASSIST"] = "assists", ["DIE"] = "deaths" };
private static readonly Dictionary<string, string> MissionFields = new() { ["GS_SUCCESS"] = "MissionsCompleted", ["GS_QUIT"] = "MissionsQuit", ["GS_FAILURE"] = "MissionsFailed", ["GS_INTERRUPTED"] = "MissionsInterrupted", ["GS_DUMPED"] = "MissionsDumped" };
private static readonly HashSet<string> EventScores = ["Halloween16", "AmalgamEventScoreMax", "Halloween19ScoreMax", "FlotillaEventScore", "FlotillaSpaceBadgesTier1", "FlotillaSpaceBadgesTier2", "FlotillaSpaceBadgesTier3", "FlotillaGroundBadgesTier1", "FlotillaGroundBadgesTier2", "FlotillaGroundBadgesTier3", "MechSurvivalScoreMax", "HiveEventScore"];
public ApiResponse Handle(string controller, JObject state, JObject? account, ApiRequest request)
{
if (controller.StartsWith("leaderboard", StringComparison.Ordinal)) return Leaderboard(controller, state, request);
if (controller == "uploadController") { Update(state, account!, request.ObjectBody()); return ApiResponse.Text(); }
var body = request.ObjectBody();
if (request.Q("guild") == "1" || request.Q("guildId") is not null || body["GuildId"] is not null)
{
var guildId = request.Q("guildId") ?? body.Value<string>("GuildId") ?? request.Q("id") ?? request.Q("lookupId") ?? request.Q("accountId"); var guild = GuildApi.Find(state, guildId ?? "") ?? throw new ApiException(409, "Could not find guild");
var profile = GuildProfile(state, guild); return ApiResponse.Json(controller == "viewController" ? profile["Stats"] : profile);
}
var id = controller == "viewController" ? request.Q("id") ?? request.Q("lookupId") ?? request.Q("accountId") : request.Q("playerId") ?? body.Value<string>("AccountId");
var target = id is null ? null : state.Obj("accounts")[id] as JObject;
if (target is null) throw new ApiException(409, "Could not find requested account");
return ApiResponse.Json(controller == "viewController" ? View(target) : Profile(target));
}
public void Update(JObject state, JObject account, JObject body)
{
var stats = account.Obj("Stats");
if (body["add"] is JObject add)
{
foreach (var p in add.Properties())
{
if (WeaponFields.TryGetValue(p.Name, out var weaponField)) UpdateArray(stats, "Weapons", weaponField, p.Value);
else if (EnemyFields.TryGetValue(p.Name, out var enemyField))
{
foreach (var entry in Entries(p.Value))
{
var enemy = Entry(stats.Array("Enemies"), entry.Name); var value = Number(entry.Value);
if (p.Name == "KILL_ENEMY" && add["CAPTURE_ENEMY"] is JObject captures && captures[entry.Name] is JToken capture)
{ var captured = Number(capture); Increment(enemy, "captures", captured); value = Math.Max(0, value - captured); }
Increment(enemy, enemyField, value);
if (p.Name == "DIE") Increment(stats, "Deaths", value);
}
}
else switch (p.Name)
{
case "MISSION_COMPLETE": foreach (var entry in Entries(p.Value)) if (MissionFields.TryGetValue(entry.Name, out var field)) Increment(stats, field, Number(entry.Value)); break;
case "PICKUP_ITEM": Increment(stats, "PickupCount", Entries(p.Value).Sum(x => Number(x.Value))); break;
case "MELEE_KILL": Increment(stats, "MeleeKills", Entries(p.Value).Sum(x => Number(x.Value))); break;
case "SCAN": UpdateArray(stats, "Scans", "scans", p.Value); break;
case "USE_ABILITY": UpdateArray(stats, "Abilities", "used", p.Value); break;
case "INCOME": Increment(stats, "Income", Number(p.Value)); break;
case "HiveEventScoreSum": Increment(stats, p.Name, Number(p.Value)); break;
case "CIPHER":
if (p.Value["0"] is JToken failed) Increment(stats, "CiphersFailed", Number(failed));
if (p.Value["1"] is JToken solved) Increment(stats, "CiphersSolved", Number(solved));
break;
}
}
}
if (body["timers"] is JObject timers)
{
if (timers["EQUIP_WEAPON"] is JToken equipped) UpdateArray(stats, "Weapons", "equipTime", equipped);
if (timers["CURRENT_MISSION_TIME"] is JToken time) Increment(stats, "TimePlayedSec", Number(time));
else if (timers["MISSION_TIME"] is JObject missions) Increment(stats, "TimePlayedSec", missions.Properties().Sum(x => Number(x.Value)));
if (timers["CIPHER_TIME"] is JToken cipherTime) Increment(stats, "CipherTime", Number(cipherTime));
}
if (body["max"] is JObject maxima)
{
foreach (var p in maxima.Properties())
{
if (p.Name == "WEAPON_XP") UpdateArray(stats, "Weapons", "xp", p.Value, true);
else if (p.Name is "MISSION_SCORE" or "RACE_SCORE")
{
foreach (var entry in Entries(p.Value))
{
var name = entry.Name.Replace("/Lotus/Types/Keys/", "", StringComparison.Ordinal); var score = Number(entry.Value);
var item = p.Name == "MISSION_SCORE" ? Entry(stats.Array("Missions"), name) : stats.Obj("Races").Obj(name);
item["highScore"] = Math.Max(item.Value<double>("highScore"), score);
Submit(state, account, p.Name == "MISSION_SCORE" ? "weekly" : "daily", name, score);
}
}
else if (p.Name == "OlliesCrashCourseScore")
{
var score = Number(p.Value); var previous = stats.Value<double>(p.Name); var acquire = new ItemAcquisition(new ItemCatalog(), clock, account);
if (previous == 0) acquire.Add(account.Obj("Inventory"), "/Lotus/Types/Items/EmailItems/PlayedOlliesCrashCourseEmailItem");
if (score >= 9991000 && previous < 9991000) acquire.Add(account.Obj("Inventory"), "/Lotus/Types/Items/EmailItems/BeatOlliesCrashCourseInNinetySecEmailItem");
stats[p.Name] = Math.Max(previous, score); Submit(state, account, "weekly", p.Name, score);
}
else if (EventScores.Contains(p.Name) || p.Name is "ZephyrScore" or "CaliberChicksScore" or "SentinelGameScore" or "DojoObstacleScore")
{
var value = Number(p.Value); stats[p.Name] = Math.Max(stats.Value<double>(p.Name), value);
if (EventScores.Contains(p.Name)) Submit(state, account, "events", p.Name == "HiveEventScore" ? "HiveEvent" : p.Name, value);
else if (p.Name is "SentinelGameScore" or "DojoObstacleScore") Submit(state, account, "weekly", p.Name, value);
}
}
}
if (body["set"] is JObject set)
foreach (var (key, field) in new[] { ("ELO_RATING", "Rating"), ("RANK", "Rank"), ("PLAYER_LEVEL", "PlayerLevel") })
if (set[key] is JToken value) stats[field] = Number(value);
}
public static JObject View(JObject account)
{
var result = (JObject)account.Obj("Stats").DeepClone();
foreach (var xp in account.Obj("Inventory").Array("XPInfo").OfType<JObject>()) Entry(result.Array("Weapons"), xp.RequiredString("ItemType"))["xp"] = xp["XP"];
return FormatNumbers(result);
}
private static JObject Profile(JObject account)
{
var inv = account.Obj("Inventory");
var equipment = new JObject { ["WeaponSkins"] = new JArray(), ["XPInfo"] = inv.Array("XPInfo").DeepClone() };
var profile = new JObject { ["AccountId"] = Wire.Oid(account.Value<string>("id")!), ["DisplayName"] = account["DisplayName"], ["PlayerLevel"] = AccountRules.Mastery(inv), ["LoadOutInventory"] = equipment, ["Created"] = Wire.Date(Wire.DateMs(account["Created"])), ["MigratedToConsole"] = false };
foreach (var name in new[] { "PlayerSkills", "ChallengeProgress", "DeathMarks", "Harvestable", "DeathSquadable", "TitleType", "Missions", "Affiliations", "DailyFocus", "Wishlist", "Alignment", "Staff", "Founder", "Guide", "Moderator", "Partner", "Accolades" }.Concat(inv.Properties().Where(x => x.Name.StartsWith("DailyAffiliation", StringComparison.Ordinal)).Select(x => x.Name)))
if (inv[name] is JToken value) profile[name] = value.DeepClone();
var loadoutId = Wire.Id(inv.Array("CurrentLoadOutIds").FirstOrDefault());
var loadout = account.Obj("Loadouts").Array("NORMAL").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == loadoutId);
if (loadout is not null)
{
profile["LoadOutPreset"] = loadout.DeepClone(); ((JObject)profile["LoadOutPreset"]!).Remove("ItemId");
foreach (var (shortName, category) in new[] { ("s", "Suits"), ("p", "Pistols"), ("l", "LongGuns"), ("m", "Melee") })
{
var item = inv.Array(category).OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(loadout[shortName]?["ItemId"]));
if (item is null) continue;
var copy = (JObject)item.DeepClone(); equipment[category] = new JArray(copy);
foreach (var config in copy.Array("Configs").OfType<JObject>())
if (config["Skins"] is JArray skins)
for (var i = 0; i < skins.Count; i++)
{
var type = skins[i]!.ToString();
if (type.Length == 24) type = inv.Array("WeaponSkins").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == type)?.Value<string>("ItemType") ?? "";
skins[i] = type;
if (type.Length > 0) equipment.Array("WeaponSkins").UniqueAdd(new JObject { ["ItemType"] = type });
}
}
}
return new JObject { ["Results"] = new JArray(profile), ["TechProjects"] = new JArray(), ["XpComponents"] = new JArray(), ["Stats"] = View(account) };
}
private static JObject GuildProfile(JObject state, JObject guild)
{
var members = guild.Array("Members").Where(x => x.Value<int>("status") == 0).Select(x => state["accounts"]?[x.Value<string>("accountId") ?? ""] as JObject).OfType<JObject>().ToArray(); var combined = new JObject();
foreach (var member in members)
{
var stats = View(member);
foreach (var property in stats.Properties().Where(x => x.Value.Type is JTokenType.Integer or JTokenType.Float)) Increment(combined, property.Name, property.Value.Value<double>());
foreach (var array in new[] { "Weapons", "Enemies", "Scans", "Missions", "PVP" })
foreach (var item in (stats[array] as JArray ?? []).OfType<JObject>())
{
var target = Entry(combined.Array(array), item.RequiredString("type")); foreach (var field in item.Properties().Where(x => x.Value.Type is JTokenType.Integer or JTokenType.Float)) Increment(target, field.Name, field.Value.Value<double>());
}
}
var results = new JArray(members.Take(4).Select(x => Profile(x)["Results"]![0]!.DeepClone()));
if (results.First is JObject first)
{
first["GuildId"] = Wire.Oid(guild.RequiredString("id")); foreach (var (from, to) in new[] { ("Name", "GuildName"), ("Tier", "GuildTier"), ("XP", "GuildXp"), ("Class", "GuildClass"), ("Emblem", "GuildEmblem") }) first[to] = guild[from]?.DeepClone();
}
var components = new JArray();
foreach (var claimed in guild["ClaimedXP"] as JArray ?? [])
{
var table = (JObject)GameData.Table("DojoRecipes")[claimed.ToString().EndsWith(".level", StringComparison.Ordinal) ? "rooms" : "decos"]!; var recipe = table.Properties().FirstOrDefault(x => x.Value.Value<string>("resultType") == claimed.ToString()); if (recipe is not null) components.Add(new JObject { ["StoreTypeName"] = GameData.StoreType(recipe.Name) });
}
var projects = (JArray)guild.Array("TechProjects").DeepClone(); foreach (var project in projects.OfType<JObject>()) project.Remove("CompletionProcessed");
return new JObject { ["Results"] = results, ["Stats"] = FormatNumbers(combined), ["TechProjects"] = projects, ["XpComponents"] = components };
}
private static JObject FormatNumbers(JObject stats)
{
// Native integer fields reject JSON such as 1.0. Keep timer fractions,
// but serialize integral values as integers, as the upstream server does.
foreach (var token in stats.Descendants().OfType<JValue>().Where(x => x.Type == JTokenType.Float).ToArray())
{
var value = token.Value<double>();
if (double.IsFinite(value) && value == Math.Truncate(value) && Math.Abs(value) <= 9_007_199_254_740_991)
token.Replace(new JValue((long)value));
}
return stats;
}
private void Submit(JObject state, JObject account, string schedule, string name, double score)
{
var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); const long week = 604800000; const long monday = 1734307200000;
var expiry = schedule == "daily" ? (now / 86400000 + 1) * 86400000 : schedule == "weekly" ? (now - monday) / week * week + monday + week : long.MaxValue;
var entry = state.Obj("leaderboards").Obj($"{schedule}.accounts.{name}").Obj(account.Value<string>("id")!);
var previous = entry.Value<long>("expiry") > now ? entry.Value<double>("score") : 0;
var guildId = Wire.Id(account["Inventory"]?["GuildId"]); var guild = GuildApi.Find(state, guildId);
if (guild is not null && guild.Array("Members").Any(x => x.Value<string>("accountId") == account.Value<string>("id") && x.Value<int>("status") == 0))
{
var clan = state.Obj("leaderboards").Obj($"{schedule}.guilds.{name}").Obj(guildId); var prior = clan.Value<long>("expiry") > now ? clan.Value<double>("score") : 0;
clan["score"] = schedule == "events" ? prior + Math.Max(0, score - previous) : Math.Max(prior, score); clan["expiry"] = expiry; clan["name"] = guild["Name"]!.DeepClone(); clan["guildTier"] = guild["Tier"]!.DeepClone(); entry["guildId"] = guildId;
}
else entry.Remove("guildId");
entry["score"] = Math.Max(previous, score); entry["expiry"] = expiry; entry["name"] = account["DisplayName"];
}
private ApiResponse Leaderboard(string controller, JObject state, ApiRequest request)
{
var body = request.ObjectBody();
var guildId = request.Q("guildId") ?? body.Value<string>("guildId"); var guildTierText = request.Q("guildTier") ?? body.Value<string>("guildTier"); var guildTier = guildTierText is null ? 0 : int.Parse(guildTierText); if (guildTier is < 0 or > 5) throw new ApiException(400, "Invalid guild tier");
var kind = guildTier > 0 || guildId is not null ? "guilds" : "accounts";
var name = request.Q("field") ?? body.RequiredString("field");
if (controller == "leaderboardGetController" && !name.StartsWith("archived.", StringComparison.Ordinal)) name = "archived." + name;
name = name.Replace("archived.", "events." + kind + ".", StringComparison.Ordinal);
if (!name.Contains('.')) name = "events." + kind + "." + name;
var before = int.Parse(request.Q("before") ?? body.Value<string>("before") ?? "0");
var after = int.Parse(request.Q("after") ?? body.Value<string>("after") ?? "20");
if (before is < 0 or > 1000 || after is < 0 or > 1000) throw new ApiException(400, "Leaderboard page is outside limits");
var pivot = request.Q("pivotId") ?? request.Q("pivotAccountId") ?? body.Value<string>("pivotId");
var entries = (state.Obj("leaderboards")[name] as JObject ?? new()).Properties().Where(x => x.Value.Value<long>("expiry") > clock.GetUtcNow().ToUnixTimeMilliseconds() && (guildTier == 0 || x.Value.Value<int>("guildTier") == guildTier) && (guildId is null || x.Value.Value<string>("guildId") == guildId)).OrderByDescending(x => x.Value.Value<double>("score")).ThenBy(x => x.Name, StringComparer.Ordinal).ToArray();
var start = before; var count = Math.Max(0, after - before);
if (pivot is not null)
{
var index = Array.FindIndex(entries, x => x.Name == pivot); start = Math.Max(0, index - before); count = index < 0 ? 0 : index - start + 1 + after;
}
var results = new JArray(entries.Skip(start).Take(count).Select((x, i) => controller == "leaderboardGetController"
? new JObject { ["DisplayName"] = x.Value["name"], ["score"] = x.Value["score"], ["rank"] = start + i + 1 }
: new JObject { ["_id"] = x.Name, ["n"] = x.Value["name"], ["s"] = x.Value["score"], ["r"] = start + i + 1 }));
return ApiResponse.Json(new JObject { [controller == "leaderboardGetController" ? "players" : "results"] = results });
}
private static IEnumerable<JProperty> Entries(JToken token) => token is JObject obj ? obj.Properties() : throw new ApiException(400, "Expected keyed statistics");
private static double Number(JToken token)
{
if (token.Type is not (JTokenType.Integer or JTokenType.Float)) throw new ApiException(400, "Expected numeric statistic");
var value = token.Value<double>(); if (!double.IsFinite(value) || value is < 0 or > 1e15) throw new ApiException(400, "Invalid statistic"); return value;
}
private static void Increment(JObject obj, string key, double value) => obj[key] = obj.Value<double>(key) + value;
private static JObject Entry(JArray array, string type)
{
var entry = array.OfType<JObject>().FirstOrDefault(x => x.Value<string>("type") == type);
if (entry is null) { entry = new JObject { ["type"] = type }; array.Add(entry); } return entry;
}
private static void UpdateArray(JObject stats, string key, string field, JToken data, bool maximum = false)
{
foreach (var entry in Entries(data))
{
var item = Entry(stats.Array(key), entry.Name); var value = Number(entry.Value);
item[field] = maximum ? Math.Max(item.Value<double>(field), value) : item.Value<double>(field) + value;
}
}
}