Files
DorkNet/DorkNet.Server/Controllers/API/Leaderboard/LeaderboardController.cs
Alexa 327dcb789c fix: correct 2023-03-21 client wire contracts across the API and notify surfaces
Audits every route the March-2023 client can call against what this server
actually serves, and fixes the defects that were breaking gameplay. Adds
docs/recroom-2023-client-api-complete.md as the reference: ~500 route
literals across 13 subsystems, with verb, request/response shape, and a
per-subsystem diff. 315 defects catalogued; the ones fixed here are listed
in its "Already fixed" table.

Path coverage was never the problem — 465 of 506 routes already had
handlers. The failures were in shape, and they cluster into four causes:

- Wrong verb. The verb is a BestHTTP.HTTPMethods ordinal (GET=0 .. PATCH=5),
  confirmed from that enum's static constructor. Routes registered POST-only
  while the client PUTs returned 405, which made room consumables neither
  buyable nor consumable and blocked every room-key edit.
- Bare scalar wrapped in an object. The client reads `1000`, not
  `{"Limit":1000}`; the issuing method signature says which. Wrapping makes
  the deserializer throw and the feature dies silently.
- [FromBody] vs form-urlencoded. The client sends nearly every write as form
  data, which an [ApiController] action bound [FromBody] rejects with 415
  before the handler runs. This alone broke all 13 club member-management
  endpoints. Adds Binding/FormOrJsonModelBinder so this is fixed once.
- Notify dispatch keys. Both enum overloads of the client's RegisterHandler
  lower the id via Int32.ToString() and register only that numeric key, and
  lookup is a case-sensitive TryGetValue that returns silently on a miss. We
  were sending the enum NAME for most ids, so friend-request updates, forced
  logout, maintenance broadcasts, live balance and consumable updates, and
  invention moderation pushes all evaporated with no error anywhere.

Notable behavioural bugs fixed:

- Editing a club announcement deleted it: PUT was a third binding on the
  delete handler. Split apart, and the missing create route added.
- leaderboard/CheckAndSetStat did not exist. The 2023 client has no SetStat
  literal at all, so every leaderboard score it wrote was discarded.
- Setting a club clubhouse cleared it: the handler read roomId from the query
  while the client sends it in the body, then wrote the resulting null.
- Club join requests were inverted (the enum is Open=0, InviteOnly=1,
  AskToJoin=2), so ask-to-join clubs rejected everyone and invite-only clubs
  quietly admitted them.
- Room bans were pushed as id 24, for which the client registers no handler;
  they now go out as ModerationKick with IsBan, so the ban takes effect
  immediately instead of at next login.
- Room-key ownership queries answered for the wrong player, and "has anyone
  bought this key" asked "did I buy it" — always false for the creator.

Also persists settings that were previously acknowledged and dropped
(playlist accessibility/restrictions/level-voting/warning, per-player status
visibility, VR movement mode and avoid-juniors, custom room codes), which is
what the new columns in the migration are for.

One test asserted the old nested PriceAndCurrency response shape; the
client's consumable formatter has no such key and reads Price and
PurchaseCurrencyId flat, so the test was corrected alongside the handler.
2026-07-27 23:27:23 +03:00

416 lines
17 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DorkNet.Server.Auth;
using DorkNet.Server.Data;
using DorkNet.Server.Data.Entities;
using DorkNet.Server.Services;
namespace DorkNet.Server.Controllers.API.Leaderboard;
/// <summary>
/// leaderboard.{rec.net,localhost}/leaderboard/* — per-stat-channel
/// leaderboard reads + writes. URLs verified against
/// <c>Cpp2IL_ISIL/.../RecNet/Leaderboards.txt:1934, 2416, 2700</c>:
///
/// POST leaderboard/SetStat body: SetStatRequestDTO
/// <c>{StatChannel(int), RoomId(long), StatValue(int)}</c>
/// POST leaderboard/GetPlayerRank body: GetPlayerRankData
/// <c>{PlayerId(int), StatChannel(int), RoomId(long)}</c>
///
/// **Subdomain matters**: the client uses
/// <c>Core.SendRequest(method, Service.Leaderboard, requestUri)</c>
/// where <c>Service.Leaderboard = 9</c> resolves via the
/// <c>RecRoomConfig.ServiceUrls</c> map (we serve via
/// <c>api/config/v2</c>) to <c>https://leaderboard.{apex}</c>. So
/// the actual outbound URL is <c>leaderboard.localhost/leaderboard/SetStat</c>
/// — not <c>api.localhost/api/leaderboard/...</c>.
///
/// Response shapes:
/// SetStat → RequestResult ack <c>{success:true,error:""}</c>
/// GetPlayerRank → FullLeaderboard.Entry — <b>camelCase</b> per
/// <c>FullLeaderboard_NestedType_Entry.txt:111-121</c>:
/// <c>{playerId(int), score(long), rank(int)}</c>.
///
/// Without explicit subdomain routing the request fell through to
/// <see cref="GlobalCatchAllController"/> which returns <c>[]</c>;
/// the client's <c>Util.Deserialize&lt;Entry&gt;</c> tried to cast
/// list-as-dictionary →
/// <c>InvalidCastException: Unable to cast 'List' to 'Dictionary'</c>
/// → "Failed to retrieve leaderboard: Malformed Response".
///
/// We bind both the leaderboard subdomain (canonical) AND the api
/// host (defensive — some 2020 builds may proxy via api/) so either
/// path lands here.
/// </summary>
[ApiController]
public class LeaderboardController(
DorkNetDbContext db,
PlayerPresenceService playerPresence) : ControllerBase
{
public sealed class SetStatRequest
{
public int StatChannel { get; set; }
public long RoomId { get; set; }
public int StatValue { get; set; }
}
/// <summary>POST <c>/leaderboard/SetStat</c> on the leaderboard
/// subdomain (canonical client path) AND <c>/api/leaderboard/SetStat</c>
/// on the api host (legacy / proxy fallback).
///
/// **Wire semantics**: the watch's
/// <c>Leaderboards.ConditionalSetStat_ReturningNewValue</c>
/// (Cpp2IL_ISIL/.../RecNet/Leaderboards.txt:645) handles the
/// per-channel direction (high-score vs low-time-better) LOCALLY
/// via a SetMode enum and only POSTs to <c>SetStat</c> when the
/// new value should replace the cached one. The wire request
/// itself carries no direction hint — it's just
/// <c>{StatChannel, RoomId, StatValue}</c>. So the server must
/// trust the client and assign unconditionally; an earlier
/// <c>Math.Max</c> here silently kept the LARGEST value, which
/// broke channels like StuntRunner (channel 7, low elapsed time
/// wins) where the watch posts the new best and we'd discard it
/// for any prior worse value.</summary>
[HttpPost("/leaderboard/SetStat")]
[HttpPost("/api/leaderboard/SetStat")]
[Authorize]
public async Task<IActionResult> SetStat([FromBody] SetStatRequest req)
{
var pid = this.RequireCurrentPlayerId();
var roomId = ResolveRoomId(req.RoomId, pid);
var row = await db.LeaderboardStats.FirstOrDefaultAsync(s =>
s.RoomId == roomId && s.PlayerId == pid && s.StatChannel == req.StatChannel);
if (row is null)
{
row = new LeaderboardStatEntity
{
PlayerId = pid,
RoomId = roomId,
StatChannel = req.StatChannel,
Value = req.StatValue,
};
db.LeaderboardStats.Add(row);
}
else
{
row.Value = req.StatValue;
row.UpdatedAt = DateTime.UtcNow;
}
// Auto-attach the channel to whichever room the score came
// from so every room implicitly gets its own leaderboards.
// The watch's <c>SetStatRequestDTO</c> carries
// <c>RoomId</c> (see Cpp2IL_ISIL .../SetStatRequestDTO);
// when it's zero (rare — direct stat report outside a room
// context) fall back to the player's current presence so a
// stray score still gets bucketed somewhere visible.
if (roomId > 0)
{
var meta = await db.LeaderboardChannelMeta
.FirstOrDefaultAsync(c => c.RoomId == roomId && c.Channel == req.StatChannel);
if (meta is null)
{
// First time this channel reports. Stamp a meta row so
// the admin SPA's per-room Leaderboards tab surfaces it
// immediately, with a placeholder name the admin can
// rename later. Direction defaults to higher-is-better;
// admin flips the toggle for time-trial channels.
db.LeaderboardChannelMeta.Add(new LeaderboardChannelMetaEntity
{
Channel = req.StatChannel,
RoomId = roomId,
Name = $"Channel {req.StatChannel}",
LowerIsBetter = false,
ValueFormat = "count",
});
}
}
await db.SaveChangesAsync();
return Ok(new { success = true, error = "" });
}
/// <summary>POST <c>/leaderboard/CheckAndSetStat</c> — the compare-and-set
/// form of <see cref="SetStat"/>, and the ONLY stat-write route the
/// 2023-03-21 client has: that build contains no <c>SetStat</c> literal at
/// all. Nothing registered this route, so every leaderboard score written
/// by a 2023 client fell through to the catch-all and was lost.
///
/// The request is <c>RecNet.SetStatRequestDTO</c>, whose property names are
/// NOT obfuscated in the dump: <c>StatChannel</c> (Int32), <c>RoomId</c>
/// (Int64), <c>StatValue</c> (Int32) and the extra
/// <c>CurrentStatValue</c> (Int32?) that distinguishes this route from
/// plain SetStat.
///
/// <c>CurrentStatValue</c> is the value the client believes is currently
/// stored. It is an optimistic-concurrency guard: the write applies only if
/// the server agrees, which stops a stale session from clobbering a newer
/// score. A null means "no expectation" and writes unconditionally, and a
/// mismatch is reported rather than silently dropped so the client can
/// re-read.
///
/// As with SetStat, the client has already decided the new value should win
/// (it applies the per-channel higher/lower-is-better rule locally), so the
/// server does not second-guess the direction.</summary>
[HttpPost("/leaderboard/CheckAndSetStat")]
[HttpPost("/api/leaderboard/CheckAndSetStat")]
[Authorize]
public async Task<IActionResult> CheckAndSetStat([FromBody] CheckAndSetStatRequest req)
{
var pid = this.RequireCurrentPlayerId();
var roomId = ResolveRoomId(req.RoomId, pid);
var row = await db.LeaderboardStats.FirstOrDefaultAsync(s =>
s.RoomId == roomId && s.PlayerId == pid && s.StatChannel == req.StatChannel);
if (req.CurrentStatValue is int expected && row is not null && row.Value != expected)
{
return Ok(new
{
success = false,
error = "stat_value_mismatch",
StatValue = row.Value,
CurrentStatValue = row.Value,
});
}
if (row is null)
{
row = new LeaderboardStatEntity
{
PlayerId = pid,
RoomId = roomId,
StatChannel = req.StatChannel,
Value = req.StatValue,
};
db.LeaderboardStats.Add(row);
}
else
{
row.Value = req.StatValue;
row.UpdatedAt = DateTime.UtcNow;
}
await EnsureChannelMetaAsync(roomId, req.StatChannel);
await db.SaveChangesAsync();
return Ok(new
{
success = true,
error = "",
StatValue = row.Value,
CurrentStatValue = row.Value,
});
}
public sealed class CheckAndSetStatRequest
{
public int StatChannel { get; set; }
public long RoomId { get; set; }
public int StatValue { get; set; }
/// <summary>The value the client believes is stored. Null = write
/// unconditionally.</summary>
public int? CurrentStatValue { get; set; }
}
/// <summary>Stamp a placeholder channel-meta row the first time a channel
/// reports, so the admin SPA's per-room Leaderboards tab surfaces it.</summary>
private async Task EnsureChannelMetaAsync(long roomId, int statChannel)
{
if (roomId <= 0) return;
var meta = await db.LeaderboardChannelMeta
.FirstOrDefaultAsync(c => c.RoomId == roomId && c.Channel == statChannel);
if (meta is not null) return;
db.LeaderboardChannelMeta.Add(new LeaderboardChannelMetaEntity
{
Channel = statChannel,
RoomId = roomId,
Name = $"Channel {statChannel}",
LowerIsBetter = false,
ValueFormat = "count",
});
}
public sealed class GetPlayerRankRequest
{
public int PlayerId { get; set; }
public int StatChannel { get; set; }
public long RoomId { get; set; }
}
[HttpPost("/leaderboard/GetPlayerRank")]
[HttpPost("/api/leaderboard/GetPlayerRank")]
public async Task<IActionResult> GetPlayerRank([FromBody] GetPlayerRankRequest req)
{
var pid = req.PlayerId > 0
? (long)req.PlayerId
: this.CurrentPlayerId() ?? 0;
// Empty/no-row case: return a zero entry. The client tolerates
// this — `Entry.Deserialize` reads playerId/score/rank as
// primitives with defaults.
if (pid == 0)
return Ok(new { playerId = 0, score = 0L, rank = 0 });
var roomId = ResolveRoomId(req.RoomId, pid);
var row = await db.LeaderboardStats.FirstOrDefaultAsync(s =>
s.RoomId == roomId && s.PlayerId == pid && s.StatChannel == req.StatChannel);
if (row is null)
return Ok(new { playerId = (int)pid, score = 0L, rank = 0 });
var lowerIsBetter = await IsLowerIsBetterAsync(roomId, req.StatChannel);
var betterCount = await db.LeaderboardStats
.CountAsync(s => s.RoomId == roomId
&& s.StatChannel == req.StatChannel
&& (lowerIsBetter ? s.Value < row.Value : s.Value > row.Value));
return Ok(new
{
playerId = (int)pid,
score = row.Value,
rank = betterCount + 1,
});
}
public sealed class GetNearbyScoresRequest
{
public int PlayerId { get; set; }
public int StatChannel { get; set; }
public long RoomId { get; set; }
public int WindowSize { get; set; }
}
/// <summary>POST <c>/leaderboard/GetNearbyScores</c> — returns the
/// N entries on either side of the caller's rank. Wire shape per
/// <c>GetNearbyScoresRequestDTO.cs</c>: PlayerId/StatChannel/RoomId
/// inherited from GetRankRequestDTO + WindowSize.</summary>
[HttpPost("/leaderboard/GetNearbyScores")]
[HttpPost("/api/leaderboard/GetNearbyScores")]
public async Task<IActionResult> GetNearbyScores([FromBody] GetNearbyScoresRequest req)
{
var pid = req.PlayerId > 0 ? (long)req.PlayerId : this.CurrentPlayerId() ?? 0;
var window = Math.Clamp(req.WindowSize, 1, 50);
var roomId = ResolveRoomId(req.RoomId, pid);
var lowerIsBetter = await IsLowerIsBetterAsync(roomId, req.StatChannel);
var query = db.LeaderboardStats
.Where(s => s.RoomId == roomId && s.StatChannel == req.StatChannel);
query = lowerIsBetter ? query.OrderBy(s => s.Value) : query.OrderByDescending(s => s.Value);
var all = await query.Select(s => new { s.PlayerId, s.Value }).ToListAsync();
if (all.Count == 0)
{
// Empty case must still come back as a SingleLeaderboard
// Dictionary, not a bare array — the 2020 watch's
// SingleLeaderboard.Deserialize reads dict["rows"]
// (Cpp2IL_ISIL/.../RecNet/SingleLeaderboard.txt:60).
// Returning `[]` cast-fails as List→Dictionary inside
// RecNet.Util.Deserialize, logged repeatedly as
// "Received malformed RecNet response: '[]'" and
// eventually starves the StuntRunner UI of a usable
// leaderboard.
return Ok(new { rows = Array.Empty<object>() });
}
var ranked = all.Select((r, i) => new
{
playerId = (int)r.PlayerId,
score = r.Value,
rank = i + 1,
}).ToList();
var myIdx = ranked.FindIndex(r => r.playerId == (int)pid);
if (myIdx < 0)
{
return Ok(new { rows = ranked.Take(window * 2 + 1).ToArray() });
}
var lo = Math.Max(0, myIdx - window);
var hi = Math.Min(ranked.Count - 1, myIdx + window);
return Ok(new { rows = ranked.GetRange(lo, hi - lo + 1).ToArray() });
}
public sealed class GetRanksRequest
{
public int PlayerId { get; set; }
public int StatChannel { get; set; }
public long RoomId { get; set; }
public int RankStart { get; set; }
public int RankEnd { get; set; }
}
/// <summary>POST <c>/leaderboard/GetRanks</c> — returns a slice of
/// the leaderboard between RankStart and RankEnd (inclusive,
/// 1-indexed). Wire shape per <c>GetRanksRequestDTO.cs</c>.</summary>
[HttpPost("/leaderboard/GetRanks")]
[HttpPost("/api/leaderboard/GetRanks")]
public async Task<IActionResult> GetRanks([FromBody] GetRanksRequest req)
{
var start = Math.Max(1, req.RankStart);
var end = Math.Max(start, req.RankEnd);
var skip = start - 1;
var take = Math.Clamp(end - skip, 1, 200);
var pid = req.PlayerId > 0 ? (long)req.PlayerId : this.CurrentPlayerId() ?? 0;
var roomId = ResolveRoomId(req.RoomId, pid);
var lowerIsBetter = await IsLowerIsBetterAsync(roomId, req.StatChannel);
var query = db.LeaderboardStats
.Where(s => s.RoomId == roomId && s.StatChannel == req.StatChannel);
query = lowerIsBetter ? query.OrderBy(s => s.Value) : query.OrderByDescending(s => s.Value);
var rows = await query.Skip(skip).Take(take).ToListAsync();
var entries = rows.Select((s, i) => new
{
playerId = (int)s.PlayerId,
score = s.Value,
rank = start + i,
}).ToArray();
// SingleLeaderboard wrapper — see GetNearbyScores above.
return Ok(new { rows = entries });
}
/// <summary>Top-N for a channel. Used by the admin tooling and
/// by the watch's full-leaderboard scoreboard view.</summary>
[HttpGet("/leaderboard/Top")]
[HttpGet("/api/leaderboard/Top")]
public async Task<IActionResult> Top([FromQuery] int channel, [FromQuery] long roomId = 0, [FromQuery] int take = 50)
{
take = Math.Clamp(take, 1, 200);
var resolvedRoomId = ResolveRoomId(roomId, this.CurrentPlayerId() ?? 0);
var lowerIsBetter = await IsLowerIsBetterAsync(resolvedRoomId, channel);
var query = db.LeaderboardStats
.Where(s => s.RoomId == resolvedRoomId && s.StatChannel == channel);
query = lowerIsBetter ? query.OrderBy(s => s.Value) : query.OrderByDescending(s => s.Value);
var rows = await query.Take(take).ToListAsync();
// FullLeaderboard wire shape: GlobalOverall / GlobalPeriodic /
// FriendsOverall / FriendsPeriodic + NextResetUTC. Use the
// same Entry list for all four buckets — friends-vs-global
// can come later.
var entries = rows.Select((s, i) => new
{
playerId = (int)s.PlayerId,
score = s.Value,
rank = i + 1,
}).ToArray();
return Ok(new
{
GlobalOverall = entries,
GlobalPeriodic = entries,
FriendsOverall = Array.Empty<object>(),
FriendsPeriodic = Array.Empty<object>(),
NextResetUTC = DateTime.UtcNow.AddDays(7),
});
}
private long ResolveRoomId(long requestedRoomId, long playerId)
{
if (requestedRoomId > 0) return requestedRoomId;
if (playerId > 0) return playerPresence.GetRoom(playerId)?.RoomId ?? 0;
return 0;
}
private async Task<bool> IsLowerIsBetterAsync(long roomId, int channel)
{
var live = await db.LeaderboardChannelMeta
.Where(c => c.RoomId == roomId && c.Channel == channel)
.Select(c => (bool?)c.LowerIsBetter)
.FirstOrDefaultAsync();
return live ?? false;
}
}