mirror of
https://github.com/DorkSquadRR/DorkNet.git
synced 2026-10-25 23:18:44 -07:00
feat: implement the client routes that had no handler
Sixteen agents, one controller each, over every route the coverage test reported as missing or wrong-verb. Route+verb coverage is now 516/522 (98.9%), up from 90.8%. Each handler was written against binary evidence rather than the audit's prose: verb from the BestHTTP.HTTPMethods ordinal at the call site, response shape from the issuing method's return type, request shape from whether the client uses form fields, a raw JsonUtility body, or query params. Agents were told to skip rather than stub, and several did. New surface worth noting: - Link host: actionlink create/get/consume and datalink get/put, previously unrouted entirely. - Club roster reads: members, banned, requests, requests/search, members/search, each with the client's real sort/paging params and the wire row shape its reader expects (the banned row has no MembershipType field, so it isn't sent). - Home clubhouse set/clear, club disband (soft, via the existing State column), and DELETE mainimage as its own action rather than a verb alias — the client parses the details envelope from it, so it is not status-only. - Club chat threads, comment CRUD, keepsake collect/delete, progression-event xp boosts, image report and cheered/bulk, iOS StoreKit product reporting. The six routes still missing all need storage that does not exist yet (per-role club permissions, club additional-image slots, MinLevel, ClubChatEnabled). Those are left for a single schema change rather than faked. Also excludes DELETE /account/me from the endpoint contract probe. That route is now a real, correctly-guarded account purge, and the probe walks every route with one test player — so calling it destroyed the probe's own session and turned one real event into 49 cascading foreign-key and 401 failures.
This commit is contained in:
@@ -1,59 +1,470 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DorkNet.Server.Auth;
|
||||
using DorkNet.Server.Data;
|
||||
using DorkNet.Server.Data.Entities;
|
||||
|
||||
namespace DorkNet.Server.Controllers.API.Comments;
|
||||
|
||||
/// <summary>
|
||||
/// Room-comment unread counts. Client contract (RecNet.Runtime
|
||||
/// <c>OPELMBNJHNO.DJLNMANKMAA(IReadOnlyCollection<long>)</c>).
|
||||
/// Room comments ("feedback"/"idea" notes players leave in a room, shown by
|
||||
/// the watch's RoomCommentsScreen / RoomCommentsPagedGrid).
|
||||
///
|
||||
/// The response is a JSON <b>ARRAY</b>, not an object. The method's return
|
||||
/// type is <c>Dictionary<long,uint></c>, but that dictionary is built
|
||||
/// client-side: OPELMBNJHNO.txt:889 constructs a
|
||||
/// <c>Func<List<UnreadRoomComments>, Dictionary<long,uint>></c>
|
||||
/// projection that runs over the deserialised payload. So the wire type is
|
||||
/// <c>List<RecNet.UnreadRoomComments></c> — each element an object with a
|
||||
/// room id (Int64) and a count (UInt32), per the two properties on
|
||||
/// RecNet/UnreadRoomComments.txt.
|
||||
/// Every route here is issued by RecNet.Runtime's room-comment service
|
||||
/// <c>OPELMBNJHNO</c> against service host <c>12 = RoomComments</c>
|
||||
/// (<see cref="Services.ConfigService"/> maps that to the <c>roomcomments</c>
|
||||
/// subdomain). The five literals, with the <c>BNDIAONDFFF</c> ctor verb
|
||||
/// ordinal moved into <c>rdx</c> immediately before the builder call
|
||||
/// (BestHTTP.HTTPMethods: 0=GET, 2=POST, 3=PUT, 4=DELETE):
|
||||
///
|
||||
/// This previously returned an object map keyed by room id. Json.NET cannot
|
||||
/// read a JSON object into a <c>List<T></c>, so every call threw and the
|
||||
/// client logged "Failed to get unread room comment counts"
|
||||
/// (OPELMBNJHNO.txt:937) and fell back to an empty dictionary — the watch's
|
||||
/// room-comment unread badge never appeared.
|
||||
/// <list type="bullet">
|
||||
/// <item><c>OPELMBNJHNO.txt:485</c> "comments/get/{0}" — rdx=0 (GET), host [rdx+12]</item>
|
||||
/// <item><c>OPELMBNJHNO.txt:811</c> "comments/unreadcounts" — dynamic GET/POST</item>
|
||||
/// <item><c>OPELMBNJHNO.txt:1216</c> "comments/create/{0}" — rdx=2 (POST), host [r12+12]</item>
|
||||
/// <item><c>OPELMBNJHNO.txt:1627</c> "comments/read/{0}/{1}" — rdx=3 (PUT), host [rbx+12]</item>
|
||||
/// <item><c>OPELMBNJHNO.txt:1935</c> "comments/delete/{0}" — rdx=4 (DELETE), r8=12</item>
|
||||
/// </list>
|
||||
///
|
||||
/// The element's exact property names are attribute-driven and are not
|
||||
/// recoverable from the ISIL (see the note on key aliasing below), so each
|
||||
/// element carries the plausible spellings side by side. Json.NET matches
|
||||
/// case-insensitively and ignores unknown members, so the extra aliases are
|
||||
/// inert whichever name the DTO actually declares.
|
||||
///
|
||||
/// Counts are all zero until per-player comment read-state is tracked; the
|
||||
/// shape is what matters for the client not to throw.
|
||||
/// STORAGE. There is no <c>RoomCommentEntity</c> and adding entities
|
||||
/// needs a migration, so comments live in the <see cref="PlayerSettingEntity"/>
|
||||
/// side-table exactly like the PlayerEvent extras
|
||||
/// (<c>PlayerEventsController.EventExtras</c>): one row per comment with
|
||||
/// <c>PlayerId</c> = the author, <c>Key = roomcomment:{roomId}:{commentId}</c>
|
||||
/// and <c>Value</c> = the JSON payload. Per-player read state is a second,
|
||||
/// disjoint namespace — <c>roomcommentread:{roomId}</c> holding the last-read
|
||||
/// comment id — which is what finally lets
|
||||
/// <see cref="UnreadCounts"/> report real numbers instead of zeroes.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class CommentsController : ControllerBase
|
||||
public class CommentsController(DorkNetDbContext db) : ControllerBase
|
||||
{
|
||||
private long Me => this.RequireCurrentPlayerId();
|
||||
|
||||
/// <summary>Key prefix for a stored comment: <c>roomcomment:{roomId}:{commentId}</c>.</summary>
|
||||
private const string CommentPrefix = "roomcomment:";
|
||||
|
||||
/// <summary>Key prefix for per-player read state: <c>roomcommentread:{roomId}</c>,
|
||||
/// value = last-read comment id. Deliberately a different prefix from
|
||||
/// <see cref="CommentPrefix"/> (not <c>roomcomment:read:…</c>) so the
|
||||
/// suffix match used by <see cref="Delete"/> can never hit a read-state row.</summary>
|
||||
private const string ReadPrefix = "roomcommentread:";
|
||||
|
||||
/// <summary>The <c>RecNet.RoomComment</c> members that are not already
|
||||
/// implied by the storage row's key/owner. <c>Position</c> is three separate
|
||||
/// nullable floats on the wire, not a Vector3: the client's
|
||||
/// <c>Nullable<Vector3></c> property is <c>[IgnoreDataMember]</c> and is
|
||||
/// rebuilt after deserialisation from three internal
|
||||
/// <c>Nullable<float></c> fields (RecNet/RoomComment.txt:495
|
||||
/// <c>FKDDCNLJOLF</c> reads the HasValue byte at <c>[rbx+0x6C]</c>, i.e. the
|
||||
/// first of the three at 0x68/0x70/0x78).
|
||||
///
|
||||
/// Public (not private) so System.Text.Json's reflection-based
|
||||
/// (de)serialiser can see the type and its accessors.</summary>
|
||||
public sealed class CommentPayload
|
||||
{
|
||||
public long? SubRoomId { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
/// <summary><c>RoomComment.EKHGDABMJOJ</c>: Feedback=0, Idea=1, BugReport=2
|
||||
/// (RecNet/RoomComment.cs enum member order).</summary>
|
||||
public int Style { get; set; }
|
||||
public float? X { get; set; }
|
||||
public float? Y { get; set; }
|
||||
public float? Z { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
}
|
||||
|
||||
// ── Reads ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Comment list for a room.
|
||||
///
|
||||
/// <c>OPELMBNJHNO.GMBPJHCBPDP(Int64 roomId, Int32 count, Int64 minId)</c>
|
||||
/// returns <c>FGLDKEJLAKB<List<RecNet.RoomComment>></c>
|
||||
/// (OPELMBNJHNO.txt:341), so the body is a bare JSON <b>array</b> — not a
|
||||
/// paged <c>{Results,TotalResults}</c> container. Verb is GET (rdx=0 at
|
||||
/// instr 044) and both parameters go on the query string, because
|
||||
/// <c>BNDIAONDFFF.AFGEDDANEKP</c> only promotes fields to a form body for
|
||||
/// non-GET verbs: literals "count" (:506) and "minId" (:518).
|
||||
///
|
||||
/// <c>minId</c> is a lower bound on the comment id (the only caller,
|
||||
/// FeedbackManager.txt:948, passes count=100 and a carried-forward id), so
|
||||
/// it is applied inclusively and the newest <c>count</c> matches are
|
||||
/// returned newest-first — which is the order the paged grid renders.
|
||||
///
|
||||
/// Failure toast if this 404s or the body will not parse:
|
||||
/// "Failed to get room comments for room: {0}" (:537).</summary>
|
||||
[HttpGet("/comments/get/{roomId:long}")]
|
||||
public async Task<IActionResult> Get(long roomId, [FromQuery] int count = 100, [FromQuery] long minId = 0)
|
||||
{
|
||||
if (count <= 0) count = 100;
|
||||
if (count > 500) count = 500;
|
||||
|
||||
var rows = await CommentRowsForRoomAsync(roomId);
|
||||
|
||||
var wire = rows
|
||||
.Where(r => r.CommentId >= minId)
|
||||
.OrderByDescending(r => r.CommentId)
|
||||
.Take(count)
|
||||
.Select(r => ToWire(r.CommentId, roomId, r.AuthorPlayerId, r.Payload, r.Unread))
|
||||
.ToList();
|
||||
|
||||
return Ok(wire);
|
||||
}
|
||||
|
||||
/// <summary>Room-comment unread counts. Client contract (RecNet.Runtime
|
||||
/// <c>OPELMBNJHNO.DJLNMANKMAA(IReadOnlyCollection<long>)</c>).
|
||||
///
|
||||
/// The response is a JSON <b>ARRAY</b>, not an object. The method's return
|
||||
/// type is <c>Dictionary<long,uint></c>, but that dictionary is built
|
||||
/// client-side: OPELMBNJHNO.txt:889 constructs a
|
||||
/// <c>Func<List<UnreadRoomComments>, Dictionary<long,uint>></c>
|
||||
/// projection that runs over the deserialised payload. So the wire type is
|
||||
/// <c>List<RecNet.UnreadRoomComments></c> — each element an object with a
|
||||
/// room id (Int64) and a count (UInt32), per the two properties on
|
||||
/// RecNet/UnreadRoomComments.txt.
|
||||
///
|
||||
/// This previously returned an object map keyed by room id. Json.NET cannot
|
||||
/// read a JSON object into a <c>List<T></c>, so every call threw and the
|
||||
/// client logged "Failed to get unread room comment counts"
|
||||
/// (OPELMBNJHNO.txt:937) and fell back to an empty dictionary — the watch's
|
||||
/// room-comment unread badge never appeared.
|
||||
///
|
||||
/// The element's exact property names are attribute-driven and are not
|
||||
/// recoverable from the ISIL (see the note on key aliasing below), so each
|
||||
/// element carries the plausible spellings side by side. Json.NET matches
|
||||
/// case-insensitively and ignores unknown members, so the extra aliases are
|
||||
/// inert whichever name the DTO actually declares.
|
||||
///
|
||||
/// Counts are real now that <see cref="MarkRead"/> persists per-player read
|
||||
/// state: a room's count is the number of comments authored by somebody
|
||||
/// else whose id is above the caller's last-read id for that room.
|
||||
/// </summary>
|
||||
[HttpPost("/comments/unreadcounts")]
|
||||
[HttpGet("/comments/unreadcounts")]
|
||||
[Consumes("application/json", "application/x-www-form-urlencoded", "multipart/form-data")]
|
||||
public async Task<IActionResult> UnreadCounts()
|
||||
{
|
||||
var roomIds = await ReadRoomIdsAsync();
|
||||
if (roomIds.Count == 0) return Ok(new List<Dictionary<string, object>>());
|
||||
|
||||
var me = Me;
|
||||
var lastRead = await LastReadAsync(me);
|
||||
|
||||
// Key + owner only: the payload column is irrelevant to counting.
|
||||
var keys = await db.PlayerSettings
|
||||
.Where(s => s.Key.StartsWith(CommentPrefix))
|
||||
.Select(s => new { s.Key, s.PlayerId })
|
||||
.ToListAsync();
|
||||
|
||||
var counts = new Dictionary<long, uint>();
|
||||
foreach (var id in roomIds) counts[id] = 0u;
|
||||
|
||||
foreach (var k in keys)
|
||||
{
|
||||
if (!TrySplitCommentKey(k.Key, out var roomId, out var commentId)) continue;
|
||||
if (!counts.ContainsKey(roomId)) continue;
|
||||
if (k.PlayerId == me) continue; // your own notes are never unread
|
||||
if (commentId <= lastRead.GetValueOrDefault(roomId)) continue;
|
||||
counts[roomId]++;
|
||||
}
|
||||
|
||||
var result = roomIds
|
||||
.Select(id => new Dictionary<string, object>
|
||||
{
|
||||
["RoomId"] = id,
|
||||
["UnreadCount"] = 0u,
|
||||
["Count"] = 0u,
|
||||
["UnreadCount"] = counts[id],
|
||||
["Count"] = counts[id],
|
||||
})
|
||||
.ToList();
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// ── Writes ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Posts a new comment into a room.
|
||||
///
|
||||
/// <c>OPELMBNJHNO.JHABIKEMJHK(Int64 roomId, Int64 subRoomId, String message,
|
||||
/// RoomComment/EKHGDABMJOJ style, Nullable<Vector3> position)</c>
|
||||
/// (OPELMBNJHNO.txt:940) returns <c>FGLDKEJLAKB<RecNet.RoomComment></c> —
|
||||
/// a <b>single</b> comment object, not a list and not a status envelope.
|
||||
///
|
||||
/// Verb is POST (rdx=2 at instr 069), so every <c>AFGEDDANEKP</c> field is
|
||||
/// an <c>application/x-www-form-urlencoded</c> body field, never a query
|
||||
/// param. Field literals, in emission order: "message" (:1234),
|
||||
/// "subRoomId" (:1249, boxed Int64), "style" (:1261, boxed <b>UInt32</b>),
|
||||
/// then — only when the <c>Vector3?</c> has a value (the
|
||||
/// <c>Compare [rdi+12], r12 / JumpIfEqual</c> at :1268) — "positionX"
|
||||
/// (:1292), "positionY" (:1314), "positionZ" (:1336), each formatted with
|
||||
/// <c>Single.ToString(CultureInfo.InvariantCulture)</c> (:1285/1289), which
|
||||
/// is why the three floats are parsed invariantly here rather than left to
|
||||
/// model binding.
|
||||
///
|
||||
/// Failure toast: "Failed to Create Comment" (:1359).</summary>
|
||||
[HttpPost("/comments/create/{roomId:long}")]
|
||||
public async Task<IActionResult> Create(
|
||||
long roomId,
|
||||
[FromForm] string? message,
|
||||
[FromForm] long? subRoomId,
|
||||
[FromForm] int style = 0,
|
||||
[FromForm] string? positionX = null,
|
||||
[FromForm] string? positionY = null,
|
||||
[FromForm] string? positionZ = null)
|
||||
{
|
||||
if (!await db.Rooms.AnyAsync(r => r.Id == roomId)) return NotFound();
|
||||
|
||||
message = (message ?? string.Empty).Trim();
|
||||
if (message.Length == 0) return BadRequest();
|
||||
// PlayerSettingEntity.Value is MaxLength(1024) and also carries the
|
||||
// rest of the payload; keep well clear of the column width.
|
||||
if (message.Length > 700) message = message[..700];
|
||||
|
||||
var payload = new CommentPayload
|
||||
{
|
||||
SubRoomId = subRoomId is > 0 ? subRoomId : null,
|
||||
Message = message,
|
||||
Style = style,
|
||||
X = ParseFloat(positionX),
|
||||
Y = ParseFloat(positionY),
|
||||
Z = ParseFloat(positionZ),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
// The client only ever sends all three or none; drop a partial set so
|
||||
// the client's Vector3 reassembly (RoomComment.FKDDCNLJOLF) sees a
|
||||
// consistent null.
|
||||
if (payload.X is null || payload.Y is null || payload.Z is null)
|
||||
payload.X = payload.Y = payload.Z = null;
|
||||
|
||||
var me = Me;
|
||||
var commentId = await NextCommentIdAsync();
|
||||
|
||||
db.PlayerSettings.Add(new PlayerSettingEntity
|
||||
{
|
||||
PlayerId = me,
|
||||
Key = $"{CommentPrefix}{roomId}:{commentId}",
|
||||
Value = JsonSerializer.Serialize(payload),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
// Authoring a comment implies you have read up to it.
|
||||
await SetLastReadAsync(me, roomId, commentId);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(ToWire(commentId, roomId, me, payload, unread: false));
|
||||
}
|
||||
|
||||
/// <summary>Records the newest comment the caller has read in a room, which
|
||||
/// is what clears the watch's unread badge (and what makes
|
||||
/// <see cref="UnreadCounts"/> return non-zero numbers for everyone else).
|
||||
///
|
||||
/// <c>OPELMBNJHNO.MCOIDIBFHIP(Int64 roomId, Int64 commentId)</c>
|
||||
/// (OPELMBNJHNO.txt:1375) returns the status-only <c>LDGADANDBIO</c>, not a
|
||||
/// DTO — the body is never parsed, only the status code. Verb is <b>PUT</b>
|
||||
/// (rdx=3 at instr 059, OPELMBNJHNO.txt:1637); both ids are path segments
|
||||
/// formatted into "comments/read/{0}/{1}" (:1627) and no field is added, so
|
||||
/// the request carries no body at all.
|
||||
///
|
||||
/// Failure toast: "Failed to update latest read comment" (:1656).</summary>
|
||||
[HttpPut("/comments/read/{roomId:long}/{commentId:long}")]
|
||||
public async Task<IActionResult> MarkRead(long roomId, long commentId)
|
||||
{
|
||||
await SetLastReadAsync(Me, roomId, commentId);
|
||||
await db.SaveChangesAsync();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>Deletes a comment.
|
||||
///
|
||||
/// <c>OPELMBNJHNO.NDLOEEHIDED(Int64 commentId)</c> (OPELMBNJHNO.txt:1781)
|
||||
/// returns the status-only <c>LDGADANDBIO</c>. Verb is <b>DELETE</b>
|
||||
/// (rdx=4 at instr 046) and the host ordinal is the only immediate on the
|
||||
/// builder call (r8=12, RoomComments) — see OPELMBNJHNO.txt:1944-1946.
|
||||
/// No fields are attached: the comment id is the whole request.
|
||||
///
|
||||
/// Because the route carries no room id, the storage key is matched by its
|
||||
/// <c>:{commentId}</c> suffix; read-state rows live under a different
|
||||
/// prefix precisely so they cannot collide here. Only the author, the room
|
||||
/// creator, or an accepted co-owner/moderator of the room may delete —
|
||||
/// anyone else gets 403 and the client raises its "Failed to delete
|
||||
/// comment" toast (:1962).</summary>
|
||||
[HttpDelete("/comments/delete/{commentId:long}")]
|
||||
public async Task<IActionResult> Delete(long commentId)
|
||||
{
|
||||
var suffix = ":" + commentId.ToString(CultureInfo.InvariantCulture);
|
||||
var row = await db.PlayerSettings
|
||||
.Where(s => s.Key.StartsWith(CommentPrefix) && s.Key.EndsWith(suffix))
|
||||
.FirstOrDefaultAsync();
|
||||
if (row is null) return NotFound();
|
||||
if (!TrySplitCommentKey(row.Key, out var roomId, out _)) return NotFound();
|
||||
|
||||
var me = Me;
|
||||
if (row.PlayerId != me && !await CanModerateRoomAsync(roomId, me)) return Forbid();
|
||||
|
||||
db.PlayerSettings.Remove(row);
|
||||
await db.SaveChangesAsync();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
// ── Wire shape ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>One <c>RecNet.RoomComment</c>. Member list and CLR types are
|
||||
/// exact (RecNet/RoomComment.cs, cross-checked against the 2023.06.21
|
||||
/// dump.cs:1241576): <c>long</c> comment id, <c>long</c> room id,
|
||||
/// <c>long?</c> sub-room id, <c>int?</c> account id, <c>DateTime</c>
|
||||
/// created-at, <c>string</c> message, the <c>EKHGDABMJOJ</c> style enum, a
|
||||
/// settable <c>bool</c>, three internal <c>float?</c> position components,
|
||||
/// and one computed get-only <c>bool</c> that is never on the wire.
|
||||
///
|
||||
/// KEY NAMES. The 2023 DTOs' JSON names live in DataMember attribute blobs
|
||||
/// in global-metadata.dat and are not recoverable from Cpp2IL output, so
|
||||
/// the names below are taken from the client's own <b>request</b> field
|
||||
/// literals for the same values — "message", "subRoomId", "style",
|
||||
/// "positionX", "positionY", "positionZ" (OPELMBNJHNO.txt:1234-1336) —
|
||||
/// which mirror the server DTO they were serialised from. Json.NET matches
|
||||
/// case-insensitively and ignores unknown members, so the aliases for the
|
||||
/// two members with no request-side counterpart are inert.
|
||||
///
|
||||
/// The settable bool is the unread flag: its only mutator
|
||||
/// <c>RoomComment.MCCJIBCJEJC</c> clears the byte at <c>[rcx+0x64]</c> and
|
||||
/// fires the change event (RoomComment.txt:471-493), and the computed
|
||||
/// get-only bool <c>FOOFBPEMFCB</c> is <c>AccountId == localAccountId ||
|
||||
/// !flag</c> (:442-466, comparing against
|
||||
/// <c>OPMAPIOEIFG.GGAEMNHEHLO</c>). Its declared name is unknown, hence the
|
||||
/// three non-inverting spellings.</summary>
|
||||
private static Dictionary<string, object?> ToWire(
|
||||
long commentId, long roomId, long authorPlayerId, CommentPayload p, bool unread) => new(StringComparer.Ordinal)
|
||||
{
|
||||
["CommentId"] = commentId,
|
||||
["RoomId"] = roomId,
|
||||
["SubRoomId"] = p.SubRoomId,
|
||||
["AccountId"] = (int)authorPlayerId,
|
||||
["CreatedAt"] = p.CreatedAt,
|
||||
["Message"] = p.Message,
|
||||
["Style"] = p.Style,
|
||||
["PositionX"] = p.X,
|
||||
["PositionY"] = p.Y,
|
||||
["PositionZ"] = p.Z,
|
||||
["IsUnread"] = unread,
|
||||
["Unread"] = unread,
|
||||
["IsNew"] = unread,
|
||||
};
|
||||
|
||||
// ── Storage helpers ──────────────────────────────────────────────────
|
||||
|
||||
private sealed record StoredComment(long CommentId, long AuthorPlayerId, CommentPayload Payload, bool Unread);
|
||||
|
||||
/// <summary>Every stored comment for a room, with the caller's unread flag
|
||||
/// resolved against their read-state row.</summary>
|
||||
private async Task<List<StoredComment>> CommentRowsForRoomAsync(long roomId)
|
||||
{
|
||||
var me = Me;
|
||||
var prefix = $"{CommentPrefix}{roomId}:";
|
||||
var rows = await db.PlayerSettings
|
||||
.Where(s => s.Key.StartsWith(prefix))
|
||||
.Select(s => new { s.Key, s.PlayerId, s.Value })
|
||||
.ToListAsync();
|
||||
|
||||
var lastRead = await LastReadAsync(me);
|
||||
var seen = lastRead.GetValueOrDefault(roomId);
|
||||
|
||||
var list = new List<StoredComment>(rows.Count);
|
||||
foreach (var r in rows)
|
||||
{
|
||||
if (!long.TryParse(r.Key[prefix.Length..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var commentId))
|
||||
continue;
|
||||
CommentPayload? payload;
|
||||
try { payload = JsonSerializer.Deserialize<CommentPayload>(r.Value); }
|
||||
catch (JsonException) { continue; }
|
||||
if (payload is null) continue;
|
||||
list.Add(new StoredComment(commentId, r.PlayerId, payload, r.PlayerId != me && commentId > seen));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Comment ids are handed out from the wall clock in milliseconds
|
||||
/// so they stay globally unique and monotonically increasing across
|
||||
/// restarts — the client's <c>minId</c> filter and the unread comparison
|
||||
/// both rely on "higher id == newer".</summary>
|
||||
private async Task<long> NextCommentIdAsync()
|
||||
{
|
||||
var id = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
for (var attempt = 0; attempt < 64; attempt++)
|
||||
{
|
||||
var suffix = ":" + id.ToString(CultureInfo.InvariantCulture);
|
||||
var taken = await db.PlayerSettings
|
||||
.AnyAsync(s => s.Key.StartsWith(CommentPrefix) && s.Key.EndsWith(suffix));
|
||||
if (!taken) break;
|
||||
id++;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>Last-read comment id per room for one player.</summary>
|
||||
private async Task<Dictionary<long, long>> LastReadAsync(long playerId)
|
||||
{
|
||||
var rows = await db.PlayerSettings
|
||||
.Where(s => s.PlayerId == playerId && s.Key.StartsWith(ReadPrefix))
|
||||
.Select(s => new { s.Key, s.Value })
|
||||
.ToListAsync();
|
||||
|
||||
var map = new Dictionary<long, long>();
|
||||
foreach (var r in rows)
|
||||
{
|
||||
if (!long.TryParse(r.Key[ReadPrefix.Length..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var roomId)) continue;
|
||||
if (!long.TryParse(r.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var commentId)) continue;
|
||||
if (!map.TryGetValue(roomId, out var cur) || commentId > cur) map[roomId] = commentId;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>Read state only ever moves forward — the watch re-sends older
|
||||
/// ids as the grid scrolls back up.</summary>
|
||||
private async Task SetLastReadAsync(long playerId, long roomId, long commentId)
|
||||
{
|
||||
var key = $"{ReadPrefix}{roomId}";
|
||||
var row = await db.PlayerSettings.FirstOrDefaultAsync(s => s.PlayerId == playerId && s.Key == key);
|
||||
if (row is null)
|
||||
{
|
||||
db.PlayerSettings.Add(new PlayerSettingEntity
|
||||
{
|
||||
PlayerId = playerId,
|
||||
Key = key,
|
||||
Value = commentId.ToString(CultureInfo.InvariantCulture),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (long.TryParse(row.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var cur) && cur >= commentId) return;
|
||||
row.Value = commentId.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Room creator, or an accepted co-owner (Role 0) / moderator
|
||||
/// (Role 1) — the same grant model
|
||||
/// <see cref="Data.Entities.RoomRoleEntity"/> documents.</summary>
|
||||
private async Task<bool> CanModerateRoomAsync(long roomId, long playerId)
|
||||
{
|
||||
if (await db.Rooms.AnyAsync(r => r.Id == roomId && r.CreatorPlayerId == playerId)) return true;
|
||||
return await db.RoomRoles.AnyAsync(r =>
|
||||
r.RoomId == roomId && r.PlayerId == playerId && r.Accepted && (r.Role == 0 || r.Role == 1));
|
||||
}
|
||||
|
||||
/// <summary>Splits <c>roomcomment:{roomId}:{commentId}</c>.</summary>
|
||||
private static bool TrySplitCommentKey(string key, out long roomId, out long commentId)
|
||||
{
|
||||
roomId = 0;
|
||||
commentId = 0;
|
||||
if (!key.StartsWith(CommentPrefix, StringComparison.Ordinal)) return false;
|
||||
var rest = key[CommentPrefix.Length..];
|
||||
var sep = rest.IndexOf(':');
|
||||
if (sep <= 0) return false;
|
||||
return long.TryParse(rest[..sep], NumberStyles.Integer, CultureInfo.InvariantCulture, out roomId)
|
||||
&& long.TryParse(rest[(sep + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out commentId);
|
||||
}
|
||||
|
||||
private static float? ParseFloat(string? s) =>
|
||||
float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : null;
|
||||
|
||||
private async Task<HashSet<long>> ReadRoomIdsAsync()
|
||||
{
|
||||
var ids = new HashSet<long>();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using DorkNet.Server.Auth;
|
||||
@@ -109,6 +110,109 @@ public class CompatibilityFeatureController(DorkNetDbContext db) : ControllerBas
|
||||
public IActionResult Ps5RecRoomPlusEnabledForAllPlayers()
|
||||
=> Content("true", "application/json");
|
||||
|
||||
/// <summary>The 2023-03-21 client POSTs this — the request is built at
|
||||
/// RecNet.Runtime/GAAPALMODOL.txt:104-106, where the route literal
|
||||
/// <c>"api/AppIntegrity/v1/iosproducts"</c> goes into <c>r9</c> and the
|
||||
/// verb register <c>rdx=2</c> = <c>BestHTTP.HTTPMethods.Post</c> (host
|
||||
/// <c>r8=1</c>). The payload is a RAW JSON body — the serialized list is
|
||||
/// handed to <c>BNDIAONDFFF.FJLLPHFOOJJ</c> (:138), not the
|
||||
/// form-parameter helper — holding
|
||||
/// <c>List<GAAPALMODOL/KOLPHINEHDD></c>, i.e. a top-level array of
|
||||
/// {Name:String, Price:Single, ProductId:String} (getters at
|
||||
/// GAAPALMODOL_NestedType_KOLPHINEHDD.txt:3/25/45; formatter key table,
|
||||
/// which also accepts camel/lower spellings, at KAONMCEONPF.txt:255-306).
|
||||
/// The issuing method's return type is
|
||||
/// <c>FGLDKEJLAKB<PHMHCPEMABG></c> (:3) and PHMHCPEMABG is
|
||||
/// {Boolean, String} (PHMHCPEMABG.txt:3/23) keyed
|
||||
/// <c>Success</c>/<c>Message</c> (GBPDOLJBABB.txt:191-218).
|
||||
///
|
||||
/// <see cref="DorkNet.Server.Controllers.API.AppIntegrity.AppIntegrityController"/>
|
||||
/// registers the same
|
||||
/// path GET-only, so the client's POST hit a 405 and the StoreKit
|
||||
/// price report was dropped. Registering only the POST verb here leaves
|
||||
/// that GET (and its consumers) untouched — the two never collide
|
||||
/// because the method constraints are disjoint.
|
||||
///
|
||||
/// The reported catalogue is what Apple's StoreKit resolved on the
|
||||
/// device, so it is inherently per-account/per-storefront: it is
|
||||
/// persisted as the reporting player's <c>appintegrity:iosproducts</c>
|
||||
/// setting (same PlayerSettings convention as the ban-appeal handler
|
||||
/// above), replacing any earlier report. Only a malformed body answers
|
||||
/// Success=false; the client shows nothing on success and PHMHCPEMABG's
|
||||
/// Message is left empty.</summary>
|
||||
[HttpPost("api/AppIntegrity/v1/iosproducts")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> IosProducts()
|
||||
{
|
||||
var pid = this.RequireCurrentPlayerId();
|
||||
|
||||
List<IosProduct>? products;
|
||||
try
|
||||
{
|
||||
products = await JsonSerializer.DeserializeAsync<List<IosProduct>>(
|
||||
Request.Body,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return IosProductsResult(false, "malformed_product_list");
|
||||
}
|
||||
|
||||
if (products is null) return IosProductsResult(false, "malformed_product_list");
|
||||
|
||||
// "{productId}={price}" pairs rather than the raw JSON: the
|
||||
// localized Name adds nothing a server-side reader needs and
|
||||
// PlayerSettingEntity.Value caps at 1024 chars, so entries are
|
||||
// dropped (never truncated mid-pair) once the budget is spent.
|
||||
var parts = new List<string>();
|
||||
var length = 0;
|
||||
foreach (var p in products)
|
||||
{
|
||||
var productId = p.ProductId?.Trim();
|
||||
if (string.IsNullOrEmpty(productId)) continue;
|
||||
var pair = $"{productId}={p.Price.ToString(CultureInfo.InvariantCulture)}";
|
||||
var cost = parts.Count == 0 ? pair.Length : pair.Length + 1;
|
||||
if (length + cost > 1024) break;
|
||||
parts.Add(pair);
|
||||
length += cost;
|
||||
}
|
||||
|
||||
const string key = "appintegrity:iosproducts";
|
||||
var row = await db.PlayerSettings
|
||||
.FirstOrDefaultAsync(s => s.PlayerId == pid && s.Key == key);
|
||||
if (row is null)
|
||||
{
|
||||
db.PlayerSettings.Add(new PlayerSettingEntity
|
||||
{
|
||||
PlayerId = pid,
|
||||
Key = key,
|
||||
Value = string.Join(';', parts),
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Value = string.Join(';', parts);
|
||||
}
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return IosProductsResult(true, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>PHMHCPEMABG accepts PascalCase, camelCase and all-lowercase
|
||||
/// key spellings (GBPDOLJBABB.txt:191-218), so either casing alone would
|
||||
/// satisfy it; both are emitted for the same reason the CampusCard
|
||||
/// payload above does. Dictionary keys go out verbatim — the global
|
||||
/// serializer sets PropertyNamingPolicy = null
|
||||
/// (Startup/ServiceCollectionExtensions.cs:381).</summary>
|
||||
private IActionResult IosProductsResult(bool success, string message)
|
||||
=> Ok(new Dictionary<string, object?>
|
||||
{
|
||||
["Success"] = success,
|
||||
["Message"] = message,
|
||||
["success"] = success,
|
||||
["message"] = message,
|
||||
});
|
||||
|
||||
[HttpPost("api/clubreporting/v1/report")]
|
||||
[Authorize]
|
||||
[Consumes("application/json", "application/x-www-form-urlencoded", "multipart/form-data")]
|
||||
@@ -192,6 +296,18 @@ public class CompatibilityFeatureController(DorkNetDbContext db) : ControllerBas
|
||||
public long PlatformAccountSubscribedPlayerId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One entry of the client's raw JSON array —
|
||||
/// GAAPALMODOL/KOLPHINEHDD, whose three properties are String, Single,
|
||||
/// String in that field order (offsets 0x10/0x18/0x20 in
|
||||
/// GAAPALMODOL_NestedType_KOLPHINEHDD.txt) and whose formatter writes
|
||||
/// the keys Name / Price / ProductId (KAONMCEONPF.txt:321-360).</summary>
|
||||
private sealed class IosProduct
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public float Price { get; set; }
|
||||
public string? ProductId { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ClubReportRequest
|
||||
{
|
||||
public long ClubId { get; set; }
|
||||
|
||||
@@ -590,6 +590,236 @@ public class CustomAvatarItemsController(
|
||||
return Ok(new { Success = true, Balance = newBalance, Item = ToWire(item) });
|
||||
}
|
||||
|
||||
/// <summary>POST api/customAvatarItems/v1/{id}/report — file a moderation
|
||||
/// report against another player's custom shirt. No report route was
|
||||
/// registered anywhere on the server, so the report dialog's "Submit"
|
||||
/// button 404'd and the client toasted "Unable to report custom avatar
|
||||
/// item {0}".
|
||||
///
|
||||
/// Verb ordinal <c>dl=2</c> = POST, on the URL
|
||||
/// String.Format("{0}/v1/{1}/report") over "api/customAvatarItems"
|
||||
/// (RecNet.Runtime/MPBLNLMCEDL.txt:4261-4275; the failure literal is
|
||||
/// :4301). The body is RAW JSON — JsonConvert.SerializeObject of a
|
||||
/// JEHCPEEKMML handed straight to BNDIAONDFFF.FJLLPHFOOJJ (:4252-4256,
|
||||
/// :4282), NOT form-urlencoded — so the body is read here instead of
|
||||
/// model-bound, exactly like PUT {id} above.
|
||||
///
|
||||
/// The issuing method IALGIAGBJMA (:4079) returns LDGADANDBIO — status
|
||||
/// only. Its continuation chain (0x181F2F300 → 0x1836E6740 →
|
||||
/// BFDGEKKNAPB.PEFKBAEAOPD, :4285-4294) is byte-for-byte the one the
|
||||
/// DELETE {id} path uses (:2206-2215), and that path is satisfied by a
|
||||
/// bare 200, so an empty 200 is the whole response contract here too.
|
||||
///
|
||||
/// JEHCPEEKMML has exactly three members, pinned by field offset from the
|
||||
/// accessor bodies (JEHCPEEKMML.txt:6/86/108) and by the arg-store
|
||||
/// sequence that fills it (:4239-4247): +0x10 the reason enum, +0x18 the
|
||||
/// free-text detail, +0x20 a Nullable<Int32>. Their JSON KEY names
|
||||
/// live in attribute metadata Cpp2IL doesn't render — obfuscated in the
|
||||
/// 2023.06 dump too (EFPKFBKGLCD, dump.cs:1256458-1256469) — so each is
|
||||
/// matched against an alias list, with a positional fallback in
|
||||
/// declaration order for anything unrecognised (Newtonsoft writes members
|
||||
/// in declaration order and the DTO has exactly these three).
|
||||
///
|
||||
/// The reason enum IS readable: LGEPGEHKNAG.KFCMACCLDEJ in the 2023.06
|
||||
/// dump (dump.cs:1250039-1250044) — CoC_Discriminatory=0, CoC_Sexual=1,
|
||||
/// CoC_Trolling=2, Misleading=3, Other=4, InappropriateClothing=5. That is
|
||||
/// a DIFFERENT numbering from <see cref="ReportEntity.Category"/>'s
|
||||
/// RoomieReportCategory convention (Harassment=1 … Other=5), so the
|
||||
/// ordinal is stored verbatim and the readable name is written into the
|
||||
/// message — otherwise a moderator reading the shared queue cannot tell a
|
||||
/// CoC_Sexual=1 clothing report from a Harassment=1 player report.
|
||||
///
|
||||
/// <see cref="ReportEntity"/> has no custom-avatar-item column and adding
|
||||
/// one is a migration, so the reported item's guid is carried in the
|
||||
/// stored text — the same thing the sibling screen-share report handler
|
||||
/// does with its image/instance evidence. That marker prefix is also what
|
||||
/// makes the duplicate check below work.</summary>
|
||||
[HttpPost("{id:guid}/report")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Report(Guid id)
|
||||
{
|
||||
var pid = this.RequireCurrentPlayerId();
|
||||
var item = await db.CustomAvatarItems.FirstOrDefaultAsync(i => i.PublicId == id);
|
||||
if (item is null) return NotFound();
|
||||
// The report button only renders on someone else's item, so this is an
|
||||
// impossible UI state; reject rather than pollute the queue.
|
||||
if (item.CreatorPlayerId == pid) return BadRequest(new { error = "cannot_report_own_item" });
|
||||
|
||||
var req = await ReadReportRequestAsync();
|
||||
// The dialog refuses to submit without a category ("Cannot report
|
||||
// custom clothing without a report category." —
|
||||
// Assembly-CSharp/RRUI/Data/CustomAvatarItemReportModel.txt:1941), so
|
||||
// a missing reason means a non-stock caller; bucket it as Other=4.
|
||||
var reason = req.Reason ?? 4;
|
||||
|
||||
var context = new List<string> { $"reason={ReportReasonName(reason)}({reason})" };
|
||||
// The only in-game caller passes null for the Nullable<Int32>
|
||||
// (CustomAvatarItemReportModel.txt:2008/2011 push rbx=0 for both it and
|
||||
// the trailing bool), so its meaning is unproven — keep whatever a
|
||||
// client does send rather than silently dropping evidence.
|
||||
if (req.Context is { } ctx) context.Add($"ctx={ctx}");
|
||||
|
||||
var details = (req.Details ?? string.Empty).Trim();
|
||||
var message = $"{ReportMarker(id)}{string.Join(' ', context)}] {details}".Trim();
|
||||
if (message.Length > 1000) message = message[..1000];
|
||||
|
||||
// One open report per (reporter, item): the dialog is re-openable and
|
||||
// the client retries on a failed submit, so without this a single
|
||||
// annoyed player can flood the moderation queue.
|
||||
var marker = ReportMarker(id);
|
||||
var duplicate = await db.Reports.AnyAsync(r =>
|
||||
r.ReporterPlayerId == pid && r.ResolvedAt == null && r.Message.StartsWith(marker));
|
||||
if (duplicate)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"[customAvatarItems] duplicate report of {PublicId} by {Pid} ignored", id, pid);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
db.Reports.Add(new ReportEntity
|
||||
{
|
||||
ReporterPlayerId = pid,
|
||||
TargetPlayerId = item.CreatorPlayerId,
|
||||
Category = reason,
|
||||
Message = message,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
logger.LogInformation(
|
||||
"[customAvatarItems] reported {PublicId} (creator {Creator}) by {Pid} reason={Reason}",
|
||||
id, item.CreatorPlayerId, pid, ReportReasonName(reason));
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>Prefix every stored custom-item report with the item guid so
|
||||
/// the row is attributable without a dedicated column, and so the
|
||||
/// duplicate check can find prior reports with a plain LIKE.</summary>
|
||||
private static string ReportMarker(Guid id) => $"[customAvatarItem {id:D} ";
|
||||
|
||||
/// <summary>LGEPGEHKNAG.KFCMACCLDEJ, verbatim from the 2023.06 dump
|
||||
/// (dump.cs:1250039-1250044). Index IS the wire ordinal.</summary>
|
||||
private static readonly string[] ReportReasonNames =
|
||||
{
|
||||
"CoC_Discriminatory", "CoC_Sexual", "CoC_Trolling",
|
||||
"Misleading", "Other", "InappropriateClothing",
|
||||
};
|
||||
|
||||
private static string ReportReasonName(int reason) =>
|
||||
reason >= 0 && reason < ReportReasonNames.Length ? ReportReasonNames[reason] : "Unknown";
|
||||
|
||||
/// <summary>Read the report body. The stock client sends raw JSON, but
|
||||
/// form encodings are accepted too so an admin/tooling caller can post the
|
||||
/// same three fields flat.</summary>
|
||||
private async Task<ReportRequest> ReadReportRequestAsync()
|
||||
{
|
||||
if (Request.HasFormContentType)
|
||||
{
|
||||
var form = await Request.ReadFormAsync();
|
||||
string? Field(params string[] keys)
|
||||
{
|
||||
foreach (var key in keys)
|
||||
if (form[key].FirstOrDefault() is { } v) return v;
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ReportRequest
|
||||
{
|
||||
Reason = ParseReportReason(Field("reason", "Reason", "reportReason", "ReportReason",
|
||||
"category", "Category", "reportCategory", "ReportCategory", "type", "Type")),
|
||||
Details = Field("details", "Details", "description", "Description",
|
||||
"message", "Message", "comment", "Comment"),
|
||||
Context = int.TryParse(
|
||||
Field("contextId", "ContextId", "instanceId", "InstanceId",
|
||||
"roomInstanceId", "RoomInstanceId", "roomId", "RoomId",
|
||||
"accountId", "AccountId", "playerId", "PlayerId"),
|
||||
out var ctx)
|
||||
? ctx
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
using var reader = new StreamReader(Request.Body);
|
||||
return ParseReportJson(await reader.ReadToEndAsync());
|
||||
}
|
||||
|
||||
/// <summary>Lenient JSON → <see cref="ReportRequest"/>. Alias-matched
|
||||
/// first; anything left over is assigned positionally in JEHCPEEKMML's
|
||||
/// declaration order (reason, detail, nullable int) so an unguessed key
|
||||
/// spelling still lands in the right slot.</summary>
|
||||
private static ReportRequest ParseReportJson(string json)
|
||||
{
|
||||
var req = new ReportRequest();
|
||||
if (string.IsNullOrWhiteSpace(json)) return req;
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return req;
|
||||
|
||||
var unmatched = new List<JsonElement>();
|
||||
foreach (var prop in doc.RootElement.EnumerateObject())
|
||||
{
|
||||
switch (prop.Name.ToLowerInvariant())
|
||||
{
|
||||
case "reason" or "reportreason" or "category" or "reportcategory" or "type" or "reporttype":
|
||||
req.Reason ??= ParseReportReason(prop.Value);
|
||||
break;
|
||||
case "details" or "detail" or "description" or "reportdescription"
|
||||
or "message" or "comment" or "text":
|
||||
req.Details ??= AsString(prop.Value);
|
||||
break;
|
||||
case "contextid" or "instanceid" or "roominstanceid" or "roomid"
|
||||
or "accountid" or "playerid" or "reportedplayerid":
|
||||
req.Context ??= AsInt(prop.Value);
|
||||
break;
|
||||
default:
|
||||
unmatched.Add(prop.Value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var value in unmatched)
|
||||
{
|
||||
if (req.Reason is null && ParseReportReason(value) is { } reason)
|
||||
{
|
||||
req.Reason = reason;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (req.Details is null && value.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
req.Details = value.GetString();
|
||||
continue;
|
||||
}
|
||||
|
||||
req.Context ??= AsInt(value);
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
}
|
||||
|
||||
return req;
|
||||
}
|
||||
|
||||
/// <summary>Accept the reason as an ordinal or as one of the enum's own
|
||||
/// names — Newtonsoft writes an int by default, but a StringEnumConverter
|
||||
/// on the DTO (an attribute the dump doesn't render) would write the name.</summary>
|
||||
private static int? ParseReportReason(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number => value.TryGetInt32(out var n) ? n : null,
|
||||
JsonValueKind.String => ParseReportReason(value.GetString()),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static int? ParseReportReason(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return null;
|
||||
if (int.TryParse(value, out var ordinal)) return ordinal;
|
||||
var index = Array.FindIndex(
|
||||
ReportReasonNames,
|
||||
n => string.Equals(n, value, StringComparison.OrdinalIgnoreCase));
|
||||
return index >= 0 ? index : null;
|
||||
}
|
||||
|
||||
private async Task EnsureOwnershipAsync(long playerId, long itemId)
|
||||
{
|
||||
if (await db.CustomAvatarItemOwnership.AnyAsync(o =>
|
||||
@@ -971,6 +1201,18 @@ public class CustomAvatarItemsController(
|
||||
public bool Deleted { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The three members of the client's report DTO JEHCPEEKMML,
|
||||
/// in its declaration order: the reason enum (+0x10), the free-text
|
||||
/// detail (+0x18) and an unidentified Nullable<Int32> (+0x20) that
|
||||
/// the stock report dialog always leaves null. All nullable so
|
||||
/// "not sent" is distinguishable from "sent empty".</summary>
|
||||
public sealed class ReportRequest
|
||||
{
|
||||
public int? Reason { get; set; }
|
||||
public string? Details { get; set; }
|
||||
public int? Context { get; set; }
|
||||
}
|
||||
|
||||
public sealed class DesignRequest
|
||||
{
|
||||
public Guid? Id { get; set; }
|
||||
|
||||
@@ -322,6 +322,41 @@ public class ImagesController(
|
||||
return Ok(BuildImageInfo(photo, photo.UploaderPlayerId));
|
||||
}
|
||||
|
||||
/// <summary>GET <c>api/images/v6/{id}</c> — single photo by numeric id.
|
||||
/// The 2023-03-21 client builds the path with
|
||||
/// <c>String.Format("{0}v6/{1}", "api/images/", id)</c>
|
||||
/// (<c>KLJOGJHBONK.txt:2694-2698</c>) and passes verb 0 = GET into the
|
||||
/// request-builder ctor (<c>:2702 Move rdx, 0</c> → <c>:2708 Call
|
||||
/// 0x1830036A0</c>); no query fields are attached.
|
||||
///
|
||||
/// The issuing method <c>KLJOGJHBONK.HLANOFILAEO(System.Int64)</c> returns
|
||||
/// <c>FGLDKEJLAKB<IReadOnlyList<Int32>></c>, but that is a
|
||||
/// CLIENT-SIDE projection: a
|
||||
/// <c>Func<LGLCPNPJCEC, IReadOnlyList<Int32>></c>
|
||||
/// (<c>:2756</c>) reduces the wire object to its tagged-player ids. So the
|
||||
/// body must be ONE <c>LGLCPNPJCEC</c> object — an array breaks the reader —
|
||||
/// with the 12 keys its generated serializer registers
|
||||
/// (<c>IBILPLGNAJE.txt:819-1078</c>: Id, ImageName, PlayerId, RoomId,
|
||||
/// PlayerEventId, Accessibility, AccessibilityLocked, Type, CreatedAt,
|
||||
/// TaggedPlayerIds, CheerCount, CommentCount), all of which
|
||||
/// <see cref="BuildImageInfo"/> already emits.
|
||||
///
|
||||
/// Without this route the request fell through to
|
||||
/// <c>api/images/{*path}</c>, which rejects "123" as a non-image filename →
|
||||
/// 404 on every photo-detail open. Visibility matches the by-name lookup:
|
||||
/// public photos to anyone, private ones only to their uploader.</summary>
|
||||
[HttpGet("api/images/v6/{id:long}")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> ImageByIdV6(long id)
|
||||
{
|
||||
var pid = this.CurrentPlayerId();
|
||||
var photo = await db.Photos.FirstOrDefaultAsync(p =>
|
||||
p.Id == id && p.DeletedAt == null &&
|
||||
(p.IsPublic || (pid != null && p.UploaderPlayerId == pid.Value)));
|
||||
if (photo is null) return NotFound();
|
||||
return Ok(BuildImageInfo(photo, photo.UploaderPlayerId));
|
||||
}
|
||||
|
||||
/// <summary>GET <c>api/images/v2/named</c> — the watch's
|
||||
/// <c>Images.DownloadNamedImageMappings</c> endpoint. Returns a
|
||||
/// list of <c>NamedImageDTO</c> entries; an empty list is a valid
|
||||
@@ -522,6 +557,51 @@ public class ImagesController(
|
||||
return Ok(new { deleted = id });
|
||||
}
|
||||
|
||||
/// <summary>POST <c>api/images/v1/{id}/report</c> — file a moderation
|
||||
/// report against a photo from the in-game photo viewer.
|
||||
/// <c>KLJOGJHBONK.IDAJEMBKAGF(System.Int64)</c> formats the path as
|
||||
/// <c>String.Format("{0}v1/{1}/report", "api/images/", id)</c>
|
||||
/// (<c>KLJOGJHBONK.txt:4010-4014</c>) and moves verb 2 = POST into the
|
||||
/// builder ctor (<c>:4021 Move rdx, 2</c>, host 1 at <c>:4020</c>).
|
||||
///
|
||||
/// The request carries NO fields and NO body — no category, no free text —
|
||||
/// and the reply is dispatched through <c>BNDIAONDFFF.KDOPJCNKOOK</c>
|
||||
/// (<c>:4031</c>), which never deserialises it: the call is
|
||||
/// fire-and-forget, so the client cannot tell a 404 from a 200 and every
|
||||
/// report was being dropped silently. Everything actionable therefore has
|
||||
/// to be derived server-side from the photo id, which is why the reported
|
||||
/// photo's uploader becomes the report target and the photo's room the
|
||||
/// context. Category 5 = "Other", matching the screenshare reporter's
|
||||
/// default for reports that arrive without one.</summary>
|
||||
[HttpPost("api/images/v1/{id:long}/report")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> ReportPhoto(long id)
|
||||
{
|
||||
var reporter = this.RequireCurrentPlayerId();
|
||||
var photo = await db.Photos.FirstOrDefaultAsync(p => p.Id == id && p.DeletedAt == null);
|
||||
if (photo is null) return NotFound();
|
||||
|
||||
// ReportEntity has no TargetPhotoId column, so the photo id + blob name
|
||||
// ride in the message text the same way club reports carry "[club {id}]"
|
||||
// — a moderator needs the actual image to act on the report.
|
||||
var message = $"[photo {photo.Id} {photo.BlobName}] reported from the in-game photo viewer";
|
||||
db.Reports.Add(new ReportEntity
|
||||
{
|
||||
ReporterPlayerId = reporter,
|
||||
TargetPlayerId = photo.UploaderPlayerId,
|
||||
RoomId = photo.RoomId,
|
||||
Category = 5,
|
||||
Message = message[..Math.Min(1000, message.Length)],
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
logger.LogInformation(
|
||||
"[images] photo {PhotoId} reported by {Reporter} (uploader {Uploader}, room {RoomId})",
|
||||
photo.Id, reporter, photo.UploaderPlayerId, photo.RoomId);
|
||||
|
||||
return Ok(new RecNetResult { Success = true, Error = string.Empty });
|
||||
}
|
||||
|
||||
// ── Legacy v1 ops (real persistence, was Ack-only stubs) ─────────
|
||||
|
||||
public sealed class CheerImageRequest
|
||||
@@ -530,23 +610,48 @@ public class ImagesController(
|
||||
public long PhotoId { get; set; }
|
||||
}
|
||||
|
||||
public sealed class BulkCheeredRequest
|
||||
{
|
||||
public List<long>? SavedImageIds { get; set; }
|
||||
public List<long>? ImageIds { get; set; }
|
||||
}
|
||||
/// <summary>Field names the cheer-state batch accepts. The 2023-03-21
|
||||
/// client sends the singular <c>"id"</c>
|
||||
/// (<c>KLJOGJHBONK.txt:3763 Move rdx, "id"</c>); the older spellings are
|
||||
/// kept so the 2020.12 watch and our own tooling keep working.</summary>
|
||||
private static readonly string[] CheerBulkIdKeys =
|
||||
{ "id", "ids", "SavedImageId", "SavedImageIds", "ImageId", "ImageIds" };
|
||||
|
||||
/// <summary>GET — and POST once the id list reaches 100 — for
|
||||
/// <c>api/images/v{4,5}/cheered/bulk</c>: the caller's cheer state for a
|
||||
/// batch of photos (the hearts on the photo feed).
|
||||
///
|
||||
/// VERB: the client picks it at runtime.
|
||||
/// <c>KLJOGJHBONK.JCLGICHPPGB(IEnumerable<Int64>)</c> calls
|
||||
/// <c>ALHIJCJOLCB.JIECAFGCODK(count, 100)</c> and moves the result straight
|
||||
/// into the request-builder's verb register
|
||||
/// (<c>KLJOGJHBONK.txt:3747 Call ALHIJCJOLCB.JIECAFGCODK</c> →
|
||||
/// <c>:3755 Move rdx, rdi</c> → <c>:3753 Move r9,
|
||||
/// "api/images/v5/cheered/bulk"</c>) — GET (0) for short lists, POST (2) for
|
||||
/// long ones. Registering POST only meant the common case fell into the
|
||||
/// <c>api/images/{*path}</c> byte catch-all and 404'd, so cheer state never
|
||||
/// loaded.
|
||||
///
|
||||
/// REQUEST: one field, <c>"id"</c>, added via
|
||||
/// <c>BNDIAONDFFF.AFGEDDANEKP("id", ids)</c> (<c>KLJOGJHBONK.txt:3763</c>).
|
||||
/// The builder emits fields as query values on GET and form values on POST —
|
||||
/// never as a JSON body — so the ids are read straight off the request
|
||||
/// instead of through <c>[FromBody]</c>, which would 415 the form POST
|
||||
/// before the action ran.
|
||||
///
|
||||
/// RESPONSE: <c>List<LAKGLIDCEDE></c>, i.e.
|
||||
/// <c>[{"SavedImageId":Int64,"IsCheered":Boolean}]</c> — key literals in the
|
||||
/// generated serializer at <c>KJEIGGBIIHP.txt:215,242</c>. One entry per
|
||||
/// requested id so the client's cache has no holes.</summary>
|
||||
[HttpGet("api/images/v4/cheered/bulk")]
|
||||
[HttpGet("api/images/v5/cheered/bulk")]
|
||||
[HttpPost("api/images/v4/cheered/bulk")]
|
||||
[HttpPost("api/images/v5/cheered/bulk")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> CheeredBulk([FromBody] BulkCheeredRequest? body)
|
||||
public async Task<IActionResult> CheeredBulk()
|
||||
{
|
||||
var pid = this.RequireCurrentPlayerId();
|
||||
var ids = (body?.SavedImageIds ?? body?.ImageIds ?? new())
|
||||
.Where(id => id > 0)
|
||||
.Distinct()
|
||||
.Take(200)
|
||||
.ToList();
|
||||
var ids = await ReadCheerBulkIdsAsync();
|
||||
if (ids.Count == 0) return Ok(Array.Empty<object>());
|
||||
|
||||
var cheered = await db.Cheers
|
||||
@@ -561,6 +666,82 @@ public class ImagesController(
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>Collect the cheer-state batch ids from wherever this client
|
||||
/// put them: query values on the GET path, form values on the POST path
|
||||
/// (both produced by <c>BNDIAONDFFF</c>'s field list), or a JSON body for
|
||||
/// non-game callers. Repeated fields and comma-joined values are both
|
||||
/// accepted because the builder's query assembler emits one
|
||||
/// <c>&id=</c> per element while our own admin tooling sends a single
|
||||
/// comma-separated value.</summary>
|
||||
private async Task<List<long>> ReadCheerBulkIdsAsync()
|
||||
{
|
||||
var ids = new List<long>();
|
||||
|
||||
void Collect(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
foreach (var part in raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
if (long.TryParse(part, out var id) && id > 0) ids.Add(id);
|
||||
}
|
||||
|
||||
foreach (var key in CheerBulkIdKeys)
|
||||
foreach (var value in Request.Query[key])
|
||||
Collect(value);
|
||||
|
||||
if (Request.HasFormContentType)
|
||||
{
|
||||
var form = await Request.ReadFormAsync();
|
||||
foreach (var key in CheerBulkIdKeys)
|
||||
foreach (var value in form[key])
|
||||
Collect(value);
|
||||
}
|
||||
else if (Request.ContentLength is > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Request.EnableBuffering();
|
||||
Request.Body.Position = 0;
|
||||
using var doc = await JsonDocument.ParseAsync(Request.Body, cancellationToken: HttpContext.RequestAborted);
|
||||
Request.Body.Position = 0;
|
||||
CollectJsonIds(doc.RootElement, Collect);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON — the query/form pass above is authoritative.
|
||||
}
|
||||
}
|
||||
|
||||
return ids.Distinct().Take(500).ToList();
|
||||
}
|
||||
|
||||
/// <summary>Pull ids out of a JSON body that is either a bare array of
|
||||
/// numbers or an object keyed by one of <see cref="CheerBulkIdKeys"/>.</summary>
|
||||
private static void CollectJsonIds(JsonElement root, Action<string?> collect)
|
||||
{
|
||||
switch (root.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in root.EnumerateArray()) CollectJsonIds(item, collect);
|
||||
break;
|
||||
case JsonValueKind.Object:
|
||||
foreach (var key in CheerBulkIdKeys)
|
||||
{
|
||||
foreach (var prop in root.EnumerateObject())
|
||||
{
|
||||
if (!string.Equals(prop.Name, key, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
CollectJsonIds(prop.Value, collect);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case JsonValueKind.Number:
|
||||
collect(root.GetRawText());
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
collect(root.GetString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>POST <c>api/images/v1/cheer</c> — cheer a photo.
|
||||
/// Was previously Ack-only; now persists a <c>CheerEntity</c> row
|
||||
/// keyed on <c>TargetPhotoId</c> + bumps <c>Photos.CheerCount</c>.
|
||||
|
||||
@@ -1144,6 +1144,222 @@ public class InventionsController(
|
||||
return Ok(new { Success = true, Message = string.Empty });
|
||||
}
|
||||
|
||||
// ── Rec Room Studio remote run ───────────────────────────────────────
|
||||
|
||||
/// <summary>One uploaded blob as the client describes it: three strings.
|
||||
/// Wire keys are literal in the generated serializer — "Filename", "Hash",
|
||||
/// "OwnershipProof" (FLELPHJDLNG.txt:255/274/290, with camelCase and
|
||||
/// all-lowercase aliases registered alongside each). The backing type is
|
||||
/// <c>CFPEPOJAMHH/IFIBBJDIHJH</c>, three <c>System.String</c> accessors
|
||||
/// (CFPEPOJAMHH_NestedType_IFIBBJDIHJH.txt:3/25/47). Same triple the room
|
||||
/// save commit sends on <c>rooms/{id}/subrooms/{id}/data</c>; declared here
|
||||
/// so this controller binds its own body.</summary>
|
||||
public sealed class StudioBlobRef
|
||||
{
|
||||
public string? Filename { get; set; }
|
||||
public string? Hash { get; set; }
|
||||
public string? OwnershipProof { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Body of <c>remote-run/push-to-studio</c> — RecNet type
|
||||
/// <c>FNAGBPCAGJD</c>. Field order/types come from the request builder
|
||||
/// (EHIOLHBGODG.txt:045-070 writes +16 String, +24 Int64, +32 Int64,
|
||||
/// +40 String, +48/+56 the two blob refs, +64 a <c>Nullable<Int32></c>)
|
||||
/// and the property accessors on FNAGBPCAGJD.txt:3-141. The JSON key for
|
||||
/// each is literal in the generated serializer OFMNNCMPEPA.txt:535-698:
|
||||
/// <c>SessionId, RoomId, SubRoomId, UnityAssetId, RoomData, SubRoomData,
|
||||
/// SavedByAccountId</c> (camel/lower aliases registered too).</summary>
|
||||
public sealed class PushToStudioRequest
|
||||
{
|
||||
public string? SessionId { get; set; }
|
||||
public long RoomId { get; set; }
|
||||
public long SubRoomId { get; set; }
|
||||
public string? UnityAssetId { get; set; }
|
||||
public StudioBlobRef? RoomData { get; set; }
|
||||
public StudioBlobRef? SubRoomData { get; set; }
|
||||
public int? SavedByAccountId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>POST <c>remote-run/push-to-studio</c> — hands the room the
|
||||
/// player just uploaded to the paired Rec Room Studio session, WITHOUT
|
||||
/// committing it as the room's live save (that is the separate
|
||||
/// <c>rooms/{id}/subrooms/{id}/data</c> path; the client's two flows are
|
||||
/// sibling methods OGPDOMCNIFM.txt:271 vs :449).
|
||||
///
|
||||
/// <para><b>Verb.</b> POST. The request builder at EHIOLHBGODG.txt:411-417
|
||||
/// moves the route literal <c>"remote-run/push-to-studio"</c> into r9 and
|
||||
/// <c>2</c> (BestHTTP HTTPMethods.Post) into rdx before
|
||||
/// <c>BNDIAONDFFF..ctor(verb, host, route)</c>. No cmov — one verb only.
|
||||
/// The body is RAW JSON, not form fields: :433 hands the serialized DTO to
|
||||
/// <c>BNDIAONDFFF.FJLLPHFOOJJ</c> (RawJsonForm, <c>application/json</c>),
|
||||
/// so this binds via <see cref="Binding.FormOrJsonModelBinder"/> — the
|
||||
/// explicit [ModelBinder] is required or [ApiController] re-infers
|
||||
/// [FromBody] and 415s a form-shaped caller.</para>
|
||||
///
|
||||
/// <para><b>Response.</b> <c>FGLDKEJLAKB<CEELGOLBHIL></c>
|
||||
/// (EHIOLHBGODG.txt:217) — a single RemoteRunDetails object, EIGHT keys,
|
||||
/// all literal in its generated reader PPHLKNGCGOE.txt:599-786:
|
||||
/// <c>SessionId</c> (String), <c>RoomId</c> and <c>SubRoomId</c>
|
||||
/// (<c>Nullable<Int64></c> — CEELGOLBHIL.txt:25/51), then
|
||||
/// <c>UnityAssetId, RoomDataFilename, RoomDataHash, SubRoomDataFilename,
|
||||
/// SubRoomDataHash</c> (String). Note the response FLATTENS the two blob
|
||||
/// refs the request nests, and drops OwnershipProof. A failed/malformed
|
||||
/// reply surfaces the client's "Failed to push to Rec Room Studio" toast
|
||||
/// (EHIOLHBGODG.txt:445).</para>
|
||||
///
|
||||
/// <para><b>What it persists.</b> The pushed blobs were already stored by
|
||||
/// <c>/upload</c> (every FileType there inserts a
|
||||
/// <see cref="RoomDataBlobEntity"/>), so the push is a registration step:
|
||||
/// it stamps the sub-room save blob with the room + sub-room it belongs to
|
||||
/// — that is what makes it appear in the per-sub-room
|
||||
/// <c>datahistory</c>/"Restore to old version" list, which the FileType=6
|
||||
/// room-metadata upload path (RoomId=0, SubRoomId=null) cannot do on its
|
||||
/// own — writes the session id into
|
||||
/// <see cref="RoomEntity.StudioSessionId"/> (the column that exists for
|
||||
/// exactly this and is echoed in room details), records the pushed Unity
|
||||
/// asset id on the sub-room's <see cref="RoomSceneEntity"/>, and keeps the
|
||||
/// whole push under <c>remoterun:{SessionId}</c> in
|
||||
/// <see cref="PlayerSettingEntity"/> so the details survive for the paired
|
||||
/// Studio session to resolve. <see cref="RoomEntity.IsRoomLinkedToRecRoomStudio"/>
|
||||
/// is deliberately NOT flipped: it changes in-room MakerPen UI and the
|
||||
/// client has no unlink call, so a push must not one-way-toggle it.</para>
|
||||
///
|
||||
/// <para><b>Not implemented:</b> live relay of the details to a second
|
||||
/// logged-in session. The client's receive side
|
||||
/// (<c>EHIOLHBGODG.MCPBJLHFOBC(CEELGOLBHIL)</c> → the
|
||||
/// <c>Action<CEELGOLBHIL></c> that MBOJJFBIAGE.txt:366/978 subscribes)
|
||||
/// has no call site anywhere in the IsilDump, so the notification id that
|
||||
/// carries it cannot be established from the binary — inventing one would
|
||||
/// be a guess. The HTTP round-trip is complete and the push is durable
|
||||
/// either way.</para></summary>
|
||||
[HttpPost("remote-run/push-to-studio")]
|
||||
[HttpPost("roomserver/remote-run/push-to-studio")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult> PushToStudio(
|
||||
[ModelBinder(typeof(Binding.FormOrJsonModelBinder))] PushToStudioRequest req)
|
||||
{
|
||||
var pid = CurrentPlayerId;
|
||||
|
||||
var sessionId = Clamp((req.SessionId ?? string.Empty).Trim(), 100);
|
||||
if (sessionId.Length == 0)
|
||||
return BadRequest(new { Error = "missing SessionId" });
|
||||
|
||||
var room = await db.Rooms.FirstOrDefaultAsync(r => r.Id == req.RoomId);
|
||||
if (room is null) return NotFound();
|
||||
|
||||
// Same gate the room-save upload uses (StorageController.UploadRoomSave):
|
||||
// creator, admin, or an accepted CoOwner (Role 0).
|
||||
var canPush = room.CreatorPlayerId == pid
|
||||
|| await db.Players.AnyAsync(p => p.Id == pid && p.IsAdmin)
|
||||
|| await db.RoomRoles.AnyAsync(r =>
|
||||
r.RoomId == room.Id && r.PlayerId == pid && r.Accepted && r.Role == 0);
|
||||
if (!canPush) return Forbid();
|
||||
|
||||
var subRoomId = req.SubRoomId;
|
||||
var scene = await db.RoomScenes
|
||||
.FirstOrDefaultAsync(s => s.RoomId == room.Id && s.OrderIndex == subRoomId);
|
||||
|
||||
var subRoomDataFilename = Clamp((req.SubRoomData?.Filename ?? string.Empty).Trim(), 128);
|
||||
if (subRoomDataFilename.Length == 0)
|
||||
return BadRequest(new { Error = "missing SubRoomData.Filename" });
|
||||
|
||||
// The push names blobs the client uploaded moments ago; if the row is
|
||||
// absent the bytes are not on this server and Studio could never fetch
|
||||
// them. Fail loudly rather than answering with a filename that 404s.
|
||||
var subRoomBlob = await db.RoomDataBlobs
|
||||
.FirstOrDefaultAsync(b => b.BlobName == subRoomDataFilename);
|
||||
if (subRoomBlob is null)
|
||||
return BadRequest(new { Error = "unknown SubRoomData.Filename" });
|
||||
if (subRoomBlob.RoomId == 0) subRoomBlob.RoomId = room.Id;
|
||||
subRoomBlob.SubRoomId ??= subRoomId;
|
||||
|
||||
var roomDataFilename = Clamp((req.RoomData?.Filename ?? string.Empty).Trim(), 128);
|
||||
if (roomDataFilename.Length > 0)
|
||||
{
|
||||
// FileType=6 (RoomMetadata) uploads land with RoomId=0 — the push
|
||||
// is the first point at which the owning room is known.
|
||||
var roomBlob = await db.RoomDataBlobs
|
||||
.FirstOrDefaultAsync(b => b.BlobName == roomDataFilename);
|
||||
if (roomBlob is null)
|
||||
return BadRequest(new { Error = "unknown RoomData.Filename" });
|
||||
if (roomBlob.RoomId == 0) roomBlob.RoomId = room.Id;
|
||||
}
|
||||
|
||||
var unityAssetId = Clamp((req.UnityAssetId ?? string.Empty).Trim(), 64);
|
||||
if (unityAssetId.Length == 0)
|
||||
{
|
||||
unityAssetId = scene?.StudioUnityAssetId ?? string.Empty;
|
||||
}
|
||||
else if (scene is not null && scene.StudioUnityAssetId != unityAssetId)
|
||||
{
|
||||
scene.StudioUnityAssetId = unityAssetId;
|
||||
scene.DataModifiedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
var roomDataHash = Clamp((req.RoomData?.Hash ?? string.Empty).Trim(), 128);
|
||||
var subRoomDataHash = Clamp((req.SubRoomData?.Hash ?? string.Empty).Trim(), 128);
|
||||
|
||||
room.StudioSessionId = sessionId;
|
||||
|
||||
var record = System.Text.Json.JsonSerializer.Serialize(new
|
||||
{
|
||||
RoomId = room.Id,
|
||||
SubRoomId = subRoomId,
|
||||
UnityAssetId = unityAssetId,
|
||||
RoomDataFilename = roomDataFilename,
|
||||
RoomDataHash = roomDataHash,
|
||||
SubRoomDataFilename = subRoomDataFilename,
|
||||
SubRoomDataHash = subRoomDataHash,
|
||||
SavedByAccountId = req.SavedByAccountId ?? (int)pid,
|
||||
PushedAt = DateTime.UtcNow,
|
||||
});
|
||||
if (record.Length > 1024)
|
||||
{
|
||||
// PlayerSettingEntity.Value is varchar(1024); truncating JSON would
|
||||
// store an unparseable fragment, so drop the optional hashes first.
|
||||
record = System.Text.Json.JsonSerializer.Serialize(new
|
||||
{
|
||||
RoomId = room.Id,
|
||||
SubRoomId = subRoomId,
|
||||
UnityAssetId = unityAssetId,
|
||||
RoomDataFilename = roomDataFilename,
|
||||
SubRoomDataFilename = subRoomDataFilename,
|
||||
SavedByAccountId = req.SavedByAccountId ?? (int)pid,
|
||||
PushedAt = DateTime.UtcNow,
|
||||
});
|
||||
}
|
||||
|
||||
var key = $"remoterun:{sessionId}";
|
||||
var setting = await db.PlayerSettings
|
||||
.FirstOrDefaultAsync(s => s.PlayerId == pid && s.Key == key);
|
||||
if (setting is null)
|
||||
db.PlayerSettings.Add(new PlayerSettingEntity
|
||||
{
|
||||
PlayerId = pid, Key = key, Value = record,
|
||||
});
|
||||
else
|
||||
setting.Value = record;
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
SessionId = sessionId,
|
||||
RoomId = (long?)room.Id,
|
||||
SubRoomId = (long?)subRoomId,
|
||||
UnityAssetId = unityAssetId,
|
||||
RoomDataFilename = roomDataFilename,
|
||||
RoomDataHash = roomDataHash,
|
||||
SubRoomDataFilename = subRoomDataFilename,
|
||||
SubRoomDataHash = subRoomDataHash,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Trim a wire string to a column's length. Every string that
|
||||
/// reaches a MaxLength column here comes straight off the request.</summary>
|
||||
private static string Clamp(string value, int max)
|
||||
=> value.Length <= max ? value : value[..max];
|
||||
|
||||
// ── Wire serializers ─────────────────────────────────────────────────
|
||||
|
||||
private static int ClampInventionPermission(int v) => v switch
|
||||
|
||||
@@ -19,27 +19,75 @@ public class KeepsakesController(DorkNetDbContext db, DomainConfig domain) : Con
|
||||
{
|
||||
private long Me => this.RequireCurrentPlayerId();
|
||||
|
||||
/// <summary>Marker category for collection rows; never surfaced as a keepsake instance.</summary>
|
||||
private const string CollectionCategory = "collection";
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors <c>KeepsakeGlobalConfigDTO.SocialXpBoostEnabled</c> below. The collect handler has
|
||||
/// to agree with what <c>globalconfig</c> advertises, so the flag lives in one place.
|
||||
/// </summary>
|
||||
private const bool SocialXpBoostEnabled = false;
|
||||
|
||||
private const int KeepsakeRoomLimit = 64;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Mine()
|
||||
{
|
||||
await EnsureLoginKeepsakeAsync(Me);
|
||||
var rows = await db.Keepsakes
|
||||
.Where(k => k.PlayerId == Me)
|
||||
.Where(k => k.PlayerId == Me && k.Category != CollectionCategory)
|
||||
.OrderByDescending(k => k.EarnedAt)
|
||||
.ToListAsync();
|
||||
return Ok(rows.Select(ToWire));
|
||||
}
|
||||
|
||||
// KeepsakeCategoryConfigDTO = {KeepsakeCategoryId(enum), VisualId, LimitPerRoom, XpValue,
|
||||
// IconOutlineImageName, IconFilledImageName} - dump.cs:1234842-1234878; the accepted wire key
|
||||
// names are enumerated by its Utf8Json formatter (IsilDump/RecNet.Runtime/HIKOJENMDKE.txt:66-160
|
||||
// - "KeepsakeCategoryId"/"VisualId"/"LimitPerRoom"/"XpValue" plus camel/lower aliases).
|
||||
// KeepsakeCategoryId is the PIHCLHIKEPH enum (dump.cs:1199524: Explore=0, GreenPowerCore=1,
|
||||
// Present=2, PurplePowerCore=3, UnnamedKeepsakeNumber1..5 = 4..8), and the client folds this
|
||||
// list into a Dictionary<PIHCLHIKEPH, KeepsakeCategoryConfigDTO> (NCCLEJPIABA.DHMFBMMAGCL,
|
||||
// NCCLEJPIABA.txt:4204) that every placed instance is looked up in. The previous three-entry
|
||||
// list keyed by our internal account/event/room buckets covered ids 0-2 only, so six of the
|
||||
// nine placeable categories had no config - and, since collect prices the reward from XpValue,
|
||||
// no reward either.
|
||||
private static readonly (int Id, string VisualId)[] CategoryConfigs =
|
||||
[
|
||||
(0, "Explore"),
|
||||
(1, "GreenPowerCore"),
|
||||
(2, "Present"),
|
||||
(3, "PurplePowerCore"),
|
||||
(4, "UnnamedKeepsakeNumber1"),
|
||||
(5, "UnnamedKeepsakeNumber2"),
|
||||
(6, "UnnamedKeepsakeNumber3"),
|
||||
(7, "UnnamedKeepsakeNumber4"),
|
||||
(8, "UnnamedKeepsakeNumber5"),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// XP a single keepsake collection is worth. This is the one number both
|
||||
/// <c>api/keepsakes/categories</c> (as <c>XpValue</c>) and
|
||||
/// <c>api/keepsakes/{id}/collect</c> (as <c>TotalXp</c>) are derived from, so the toast the
|
||||
/// client renders after a collect matches the config it already downloaded.
|
||||
/// </summary>
|
||||
private const int KeepsakeXpValue = 25;
|
||||
|
||||
[HttpGet("categories")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Categories()
|
||||
{
|
||||
var results = new[]
|
||||
{
|
||||
new { KeepsakeCategoryId = 0, VisualId = "account", LimitPerRoom = 0, XpValue = 0, IconOutlineImageName = string.Empty, IconFilledImageName = string.Empty },
|
||||
new { KeepsakeCategoryId = 1, VisualId = "event", LimitPerRoom = 0, XpValue = 0, IconOutlineImageName = string.Empty, IconFilledImageName = string.Empty },
|
||||
new { KeepsakeCategoryId = 2, VisualId = "room", LimitPerRoom = 64, XpValue = 0, IconOutlineImageName = string.Empty, IconFilledImageName = string.Empty },
|
||||
};
|
||||
var results = CategoryConfigs
|
||||
.Select(c => new
|
||||
{
|
||||
KeepsakeCategoryId = c.Id,
|
||||
c.VisualId,
|
||||
LimitPerRoom = KeepsakeRoomLimit,
|
||||
XpValue = KeepsakeXpValue,
|
||||
IconOutlineImageName = string.Empty,
|
||||
IconFilledImageName = string.Empty,
|
||||
})
|
||||
.ToArray();
|
||||
return Ok(new
|
||||
{
|
||||
Results = results,
|
||||
@@ -81,10 +129,26 @@ public class KeepsakesController(DorkNetDbContext db, DomainConfig domain) : Con
|
||||
// Key names follow the same RecNet naming the room endpoint below already uses; the literal
|
||||
// JSON names live in Newtonsoft attribute metadata the dumps do not render, so they are
|
||||
// unverified - Json.NET matching is case-insensitive and ignores unknown members.
|
||||
//
|
||||
// CollectionRecords is what the CALLER has picked up, which is a different set from what the
|
||||
// caller PLACED: it is fed by the collect handler below (Category=CollectionCategory rows).
|
||||
var eventInstanceIds = rows
|
||||
.Select(r => TryParseInstanceKey(r.EventKey, out _, out _, out _, out var id) ? id : StableKeepsakeInstanceId(r.Id))
|
||||
.ToHashSet();
|
||||
var collected = (await LoadMyCollectionsAsync())
|
||||
.Where(c => eventInstanceIds.Contains(c.InstanceId))
|
||||
.GroupBy(c => c.RoomId)
|
||||
.Select(group => (object)new
|
||||
{
|
||||
RoomId = group.Key,
|
||||
KeepsakeInstanceIds = group.Select(c => c.InstanceId).Distinct().Select(id => id.ToString("D")).ToList(),
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
Instances = GroupInstanceIdsByRoom(rows),
|
||||
CollectionRecords = GroupInstanceIdsByRoom(rows.Where(r => r.PlayerId == Me)),
|
||||
CollectionRecords = collected,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,21 +169,136 @@ public class KeepsakesController(DorkNetDbContext db, DomainConfig domain) : Con
|
||||
.OrderByDescending(k => k.EarnedAt)
|
||||
.ToListAsync();
|
||||
var instances = rows.Select(row => ToRoomInstanceWire(row, roomId)).ToList();
|
||||
|
||||
// KeepsakeCollectionRecordDTO = {Int32 AccountId, Guid KeepsakeInstanceId, DateTime
|
||||
// CollectedAt} - dump.cs:1234642-1234666, wire keys confirmed by its Utf8Json formatter
|
||||
// (IsilDump/RecNet.Runtime/CNNAFLNKDCL.txt:48,75,99). Scoped to the caller: the DTO carries
|
||||
// AccountId so the client can filter, but returning only the caller's rows is correct under
|
||||
// either reading and keeps other players' pickups out of the payload.
|
||||
var collectPrefix = $"collect:{roomIdText}:";
|
||||
var me = Me;
|
||||
var collectionRecords = await db.Keepsakes
|
||||
.Where(k => k.PlayerId == me
|
||||
&& k.Category == CollectionCategory
|
||||
&& EF.Functions.Like(k.EventKey, collectPrefix + "%"))
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
Instances = instances,
|
||||
CollectionRecords = Array.Empty<object>(),
|
||||
CollectionRecords = collectionRecords
|
||||
.Where(k => TryParseCollectionKey(k.EventKey, out _, out _))
|
||||
.Select(k =>
|
||||
{
|
||||
TryParseCollectionKey(k.EventKey, out _, out var instanceId);
|
||||
return (object)new
|
||||
{
|
||||
AccountId = k.PlayerId is > 0 and <= int.MaxValue ? (int)k.PlayerId : 0,
|
||||
KeepsakeInstanceId = instanceId.ToString("D"),
|
||||
CollectedAt = k.EarnedAt,
|
||||
};
|
||||
})
|
||||
.ToList(),
|
||||
KeepsakeProgressionEventIds = Array.Empty<long>(),
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a placed keepsake instance. The 2023 client issues
|
||||
/// <c>DELETE api/keepsakes/{guid}</c> - <c>NCCLEJPIABA.JBKENCNIEPA(System.Guid)</c> builds
|
||||
/// <c>String.Format("{0}/{1}", "api/keepsakes", guid)</c> and passes verb 4 (DELETE) to the
|
||||
/// BNDIAONDFFF ctor (NCCLEJPIABA.txt:1544, 1687-1698 - <c>Move rdx, 4</c>). Its return type is
|
||||
/// the non-generic <c>LDGADANDBIO</c> promise, so no response body is deserialised; a bare 200
|
||||
/// is enough. Client-side the tool refuses unless the caller is at least a room co-owner
|
||||
/// ("Must be at least a room co-owner to modify keepsakes.",
|
||||
/// RecRoom.Keepsakes.Runtime/PDFJLLECNBE.txt:3363), which we re-check server-side.
|
||||
/// </summary>
|
||||
[HttpDelete("{keepsakeInstanceId:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid keepsakeInstanceId)
|
||||
{
|
||||
var instance = await FindInstanceAsync(keepsakeInstanceId);
|
||||
if (instance is null) return NotFound();
|
||||
|
||||
var roomId = TryParseInstanceKey(instance.EventKey, out var parsedRoomId, out _, out _, out _)
|
||||
? parsedRoomId
|
||||
: 0;
|
||||
if (!await CanModifyInstanceAsync(instance, roomId, Me)) return Forbid();
|
||||
|
||||
// Drop the collection rows for this instance too, or they linger as records pointing at a
|
||||
// keepsake nobody can see and keep suppressing a future re-placement's collect.
|
||||
var suffix = keepsakeInstanceId.ToString("N");
|
||||
var orphanedCollections = await db.Keepsakes
|
||||
.Where(k => k.Category == CollectionCategory && EF.Functions.Like(k.EventKey, $"%:{suffix}"))
|
||||
.ToListAsync();
|
||||
|
||||
db.Keepsakes.Remove(instance);
|
||||
db.Keepsakes.RemoveRange(orphanedCollections
|
||||
.Where(k => TryParseCollectionKey(k.EventKey, out _, out var id) && id == keepsakeInstanceId));
|
||||
await db.SaveChangesAsync();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the caller picked up a placed keepsake and reports the XP it was worth. The
|
||||
/// 2023 client issues <c>POST api/keepsakes/{guid}/collect</c> -
|
||||
/// <c>NCCLEJPIABA.HFGKFAHFELM(System.Guid)</c> formats <c>"{0}/{1}/collect"</c> over
|
||||
/// "api/keepsakes" and passes verb 2 (POST) (NCCLEJPIABA.txt:1738, 1963-1974 -
|
||||
/// <c>Move rdx, 2</c>), with no request body. The response type is
|
||||
/// <c>FGLDKEJLAKB<DHNBKMHDANK></c>; DHNBKMHDANK is a two-Int32 object whose Utf8Json
|
||||
/// formatter writes "TotalXp" and "SocialBoostXp" (RecNet.Runtime/PKCMBJFBHBO.txt:42,69,100,121
|
||||
/// - reader also accepts totalXp/socialBoostXp). The consumer computes
|
||||
/// <c>TotalXp - SocialBoostXp</c> for the base figure and shows the boost separately
|
||||
/// (PDFJLLECNBE_NestedType_LKIPMJFEAFK.txt:82-99), so TotalXp is the whole award, boost
|
||||
/// included - not a running account total.
|
||||
/// </summary>
|
||||
[HttpPost("{keepsakeInstanceId:guid}/collect")]
|
||||
public async Task<IActionResult> Collect(Guid keepsakeInstanceId)
|
||||
{
|
||||
var instance = await FindInstanceAsync(keepsakeInstanceId);
|
||||
if (instance is null) return NotFound();
|
||||
|
||||
var parsed = TryParseInstanceKey(instance.EventKey, out var roomId, out _, out var categoryConfigId, out _);
|
||||
if (!parsed)
|
||||
{
|
||||
roomId = 0;
|
||||
categoryConfigId = CategoryId(instance.Category);
|
||||
}
|
||||
|
||||
var me = Me;
|
||||
var collectKey = BuildCollectionKey(roomId, keepsakeInstanceId);
|
||||
var alreadyCollected = await db.Keepsakes
|
||||
.AnyAsync(k => k.PlayerId == me && k.Category == CollectionCategory && k.EventKey == collectKey);
|
||||
|
||||
// Re-collecting is a no-op award rather than an error: the client only ever renders the two
|
||||
// numbers, and paying out twice for one instance would be a fabricated reward.
|
||||
if (alreadyCollected) return Ok(new { TotalXp = 0, SocialBoostXp = 0 });
|
||||
|
||||
db.Keepsakes.Add(new KeepsakeEntity
|
||||
{
|
||||
PlayerId = me,
|
||||
Category = CollectionCategory,
|
||||
EventKey = collectKey,
|
||||
EarnedAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
TotalXp = XpValueFor(categoryConfigId),
|
||||
// SocialBoostXp is the boost slice *of* TotalXp - the client renders
|
||||
// TotalXp - SocialBoostXp as the base figure - and globalconfig above advertises
|
||||
// SocialXpBoostEnabled=false, so there is no slice and the whole award is base XP.
|
||||
SocialBoostXp = 0,
|
||||
});
|
||||
}
|
||||
|
||||
[HttpGet("globalconfig")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult GlobalConfig() => Ok(new
|
||||
{
|
||||
KeepsakeFeatureEnabled = true,
|
||||
KeepsakeRoomLimit = 64,
|
||||
SocialXpBoostEnabled = false,
|
||||
KeepsakeRoomLimit,
|
||||
SocialXpBoostEnabled,
|
||||
});
|
||||
|
||||
[HttpPost]
|
||||
@@ -353,6 +532,100 @@ public class KeepsakesController(DorkNetDbContext db, DomainConfig domain) : Con
|
||||
return true;
|
||||
}
|
||||
|
||||
// A collection record is stored as its own keepsake row so no schema change is needed:
|
||||
// Category = "collection", EventKey = "collect:{roomId}:{instanceGuid:N}"
|
||||
// The room id is baked in so the room endpoint can filter by prefix and the event endpoint can
|
||||
// group by room without re-reading the instance rows. "collect:" shares no prefix with the
|
||||
// "room:"/"event:" instance keys, so collection rows never leak into an instance query, and
|
||||
// Mine() filters the category out of the legacy keepsake list.
|
||||
private static string BuildCollectionKey(long roomId, Guid instanceId)
|
||||
=> $"collect:{roomId.ToString(CultureInfo.InvariantCulture)}:{instanceId:N}";
|
||||
|
||||
private static bool TryParseCollectionKey(string? eventKey, out long roomId, out Guid instanceId)
|
||||
{
|
||||
roomId = 0;
|
||||
instanceId = Guid.Empty;
|
||||
var parts = (eventKey ?? string.Empty).Split(':');
|
||||
if (parts.Length != 3 || !string.Equals(parts[0], "collect", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out roomId)) return false;
|
||||
return Guid.TryParseExact(parts[2], "N", out instanceId);
|
||||
}
|
||||
|
||||
private async Task<List<(long RoomId, Guid InstanceId)>> LoadMyCollectionsAsync()
|
||||
{
|
||||
var me = Me;
|
||||
var rows = await db.Keepsakes
|
||||
.Where(k => k.PlayerId == me && k.Category == CollectionCategory)
|
||||
.Select(k => k.EventKey)
|
||||
.ToListAsync();
|
||||
var results = new List<(long RoomId, Guid InstanceId)>(rows.Count);
|
||||
foreach (var key in rows)
|
||||
{
|
||||
if (TryParseCollectionKey(key, out var roomId, out var instanceId))
|
||||
results.Add((roomId, instanceId));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the guid the client holds (from <c>api/keepsakes/rooms/{roomId}</c>, or the guid
|
||||
/// this server handed back from POST <c>api/keepsakes</c>) to the row that encodes it.
|
||||
/// </summary>
|
||||
private async Task<KeepsakeEntity?> FindInstanceAsync(Guid keepsakeInstanceId)
|
||||
{
|
||||
var suffix = keepsakeInstanceId.ToString("N");
|
||||
var candidates = await db.Keepsakes
|
||||
.Where(k => (k.Category == "room" || k.Category == "event")
|
||||
&& EF.Functions.Like(k.EventKey, $"%:{suffix}"))
|
||||
.ToListAsync();
|
||||
var match = candidates.FirstOrDefault(k =>
|
||||
TryParseInstanceKey(k.EventKey, out _, out _, out _, out var id) && id == keepsakeInstanceId);
|
||||
if (match is not null) return match;
|
||||
|
||||
// Rows written before the instance id was encoded into EventKey are reported to the client
|
||||
// with the MD5-derived StableKeepsakeInstanceId, which no LIKE can match. Resolve those by
|
||||
// id only - the projection keeps it to one column over the short-key rows.
|
||||
var legacyIds = await db.Keepsakes
|
||||
.Where(k => (k.Category == "room" || k.Category == "event")
|
||||
&& !EF.Functions.Like(k.EventKey, "%:%:%:%"))
|
||||
.Select(k => k.Id)
|
||||
.ToListAsync();
|
||||
var legacyId = legacyIds.FirstOrDefault(id => StableKeepsakeInstanceId(id) == keepsakeInstanceId);
|
||||
return legacyId == 0 ? null : await db.Keepsakes.FirstOrDefaultAsync(k => k.Id == legacyId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Placement and removal are gated client-side on room co-ownership
|
||||
/// ("Must be at least a room co-owner to modify keepsakes.", PDFJLLECNBE.txt:3363); the placer
|
||||
/// and server admins are allowed through as well.
|
||||
/// </summary>
|
||||
private async Task<bool> CanModifyInstanceAsync(KeepsakeEntity instance, long roomId, long playerId)
|
||||
{
|
||||
if (instance.PlayerId == playerId) return true;
|
||||
|
||||
if (roomId > 0)
|
||||
{
|
||||
var creatorId = await db.Rooms.AsNoTracking()
|
||||
.Where(r => r.Id == roomId)
|
||||
.Select(r => (long?)r.CreatorPlayerId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (creatorId == playerId) return true;
|
||||
|
||||
var isCoOwner = await db.RoomRoles.AnyAsync(r =>
|
||||
r.RoomId == roomId && r.PlayerId == playerId && r.Role == 0 && r.Accepted);
|
||||
if (isCoOwner) return true;
|
||||
}
|
||||
|
||||
return await db.Players
|
||||
.Where(p => p.Id == playerId)
|
||||
.Select(p => p.IsAdmin)
|
||||
.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
private static int XpValueFor(int keepsakeCategoryConfigId)
|
||||
=> CategoryConfigs.Any(c => c.Id == keepsakeCategoryConfigId) ? KeepsakeXpValue : 0;
|
||||
|
||||
private static int CategoryId(string? category) =>
|
||||
string.Equals(category, "event", StringComparison.OrdinalIgnoreCase) ? 1 :
|
||||
string.Equals(category, "room", StringComparison.OrdinalIgnoreCase) ? 2 :
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -240,6 +242,318 @@ public class PhotosController(
|
||||
return Ok(new { deleted = id });
|
||||
}
|
||||
|
||||
// ── 2023 home feed (Discovery host) ───────────────────────────────
|
||||
|
||||
/// <summary>The only <c>FeedItemType</c> (client enum
|
||||
/// <c>DAAEHNDDCCH</c>) the 2023 feed list can render: an image.
|
||||
/// Two independent confirmations in the binary — the list spawner
|
||||
/// builds one <c>RRUI.Data.ImageFeedItemModel</c> per returned item
|
||||
/// (<c>Assembly-CSharp/RRUI/Data/FeedListModelController_NestedType_FeedListSpawnerImpl.txt:294</c>
|
||||
/// "044 Call ImageFeedItemModel.Set"), and the share deep-link
|
||||
/// handler maps the path segment "image" + an Int64 id onto an
|
||||
/// injected feed item constructed with the enum literal 0
|
||||
/// (<c>Assembly-CSharp/RecRoom/Sharing/LinkManager.txt:5646</c>
|
||||
/// Move rdx,"image" … :5665 Move rdx,0 … :5668 Call
|
||||
/// EKLOCIPFHII..ctor). FeedItemId is therefore an image id, which on
|
||||
/// DorkNet is <see cref="PhotoEntity.Id"/> — the same id space
|
||||
/// <c>api/images/v5/bulk</c> resolves.</summary>
|
||||
private const int FeedItemTypeImage = 0;
|
||||
|
||||
/// <summary>Ranking revision stamped on the envelope and on every
|
||||
/// item. The client never interprets it: it copies the Int16 off the
|
||||
/// response into the list model and replays it in the impression
|
||||
/// telemetry it later posts back (<c>FeedListModel_NestedType_OLMJPGEMAKM.txt</c>
|
||||
/// "031 Move rax,[rdi+40] / 032 Move [rcx+280],rax" then
|
||||
/// "040 Call FeedListModel.LMDNOKJCBGE"). Bump it when the ordering
|
||||
/// below changes so the telemetry can tell the cohorts apart.</summary>
|
||||
private const short FeedAlgoVersion = 1;
|
||||
|
||||
/// <summary>POST /feed/query — the 2023 client's personalised home
|
||||
/// feed. Host is Discovery (host enum 19) and the verb is POST:
|
||||
/// <c>RecNet.Runtime/KGLCPCEGCFF.txt:166-178</c> loads
|
||||
/// r9 = "feed/query", r8 = 19, rdx = 2 (BestHTTP POST) into the
|
||||
/// shared BNDIAONDFFF request ctor. The body is a RAW JSON document
|
||||
/// (the issuing method takes an already-serialised
|
||||
/// <c>System.String</c> and hands it to BNDIAONDFFF.FJLLPHFOOJJ),
|
||||
/// NOT form fields — so it is read straight off Request.Body.
|
||||
///
|
||||
/// Request keys (reader BAEBDMPPKKE.txt:331-414, each registered in
|
||||
/// PascalCase/camelCase/lowercase): Take:Int32,
|
||||
/// ContinuationToken:String?, InjectedFeedItems:[{FeedItemType,
|
||||
/// FeedItemId}], FeedInstanceId:String?.
|
||||
///
|
||||
/// Response is the generic result envelope AECMPGPHAII<T>
|
||||
/// {Success, Error, Value} (keys at AEGADMDIKNE.txt:243-286) wrapping
|
||||
/// BDIFPHKLFKD {Items, FeedInstanceId, FeedContext,
|
||||
/// FeedAlgorithmVersion} (keys at EHKEOCKBCDH.txt:331-414). Anything
|
||||
/// else — including a 404 — rejects the promise and the home tab
|
||||
/// renders its failure state.
|
||||
///
|
||||
/// FeedContext is the continuation cursor, not a display string: the
|
||||
/// RefreshPage continuation reads field +32 (FeedContext) as the
|
||||
/// third element of its (count, items, nextToken) tuple and feeds it
|
||||
/// back as the next request's ContinuationToken
|
||||
/// (<c>FeedListModel_NestedType_OLMJPGEMAKM.txt</c> "062 Move r9,
|
||||
/// [rdi+32]"). An empty FeedContext therefore ends pagination.
|
||||
///
|
||||
/// Anonymous-safe like the other feed reads; when the caller is
|
||||
/// authenticated the ordering is personalised (friends/subscriptions
|
||||
/// first) and blocked/ignored uploaders are filtered out.</summary>
|
||||
[HttpPost("/feed/query")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult> FeedQuery()
|
||||
{
|
||||
var take = 20;
|
||||
string? continuationToken = null;
|
||||
string? requestedInstanceId = null;
|
||||
var requestedInjected = new List<long>();
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = await JsonDocument.ParseAsync(Request.Body);
|
||||
if (doc.RootElement.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
var root = doc.RootElement;
|
||||
if (TryFeedProp(root, "Take", out var takeEl) &&
|
||||
takeEl.ValueKind == JsonValueKind.Number && takeEl.TryGetInt32(out var t))
|
||||
take = t;
|
||||
if (TryFeedProp(root, "ContinuationToken", out var ctEl) &&
|
||||
ctEl.ValueKind == JsonValueKind.String)
|
||||
continuationToken = ctEl.GetString();
|
||||
if (TryFeedProp(root, "FeedInstanceId", out var fiEl) &&
|
||||
fiEl.ValueKind == JsonValueKind.String)
|
||||
requestedInstanceId = fiEl.GetString();
|
||||
if (TryFeedProp(root, "InjectedFeedItems", out var injEl) &&
|
||||
injEl.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var entry in injEl.EnumerateArray())
|
||||
{
|
||||
if (entry.ValueKind != JsonValueKind.Object) continue;
|
||||
// Non-image injected items can't be rendered by the
|
||||
// 2023 list, so echoing them back would produce a
|
||||
// blank card. Drop them.
|
||||
var type = TryFeedProp(entry, "FeedItemType", out var tyEl) &&
|
||||
tyEl.ValueKind == JsonValueKind.Number &&
|
||||
tyEl.TryGetInt32(out var ty)
|
||||
? ty : FeedItemTypeImage;
|
||||
if (type != FeedItemTypeImage) continue;
|
||||
if (TryFeedProp(entry, "FeedItemId", out var idEl) &&
|
||||
idEl.ValueKind == JsonValueKind.Number &&
|
||||
idEl.TryGetInt64(out var id) && id > 0)
|
||||
requestedInjected.Add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Unparseable/empty body — treat as a default first-page pull
|
||||
// rather than 400, so a malformed retry still shows content.
|
||||
}
|
||||
|
||||
take = Math.Clamp(take, 1, 50);
|
||||
var me = this.CurrentPlayerId();
|
||||
|
||||
// Uploaders the caller can't see: anyone they blocked or ignored,
|
||||
// plus anyone who blocked them.
|
||||
var hidden = new List<long>();
|
||||
var affinity = new List<long>();
|
||||
if (me is long meId)
|
||||
{
|
||||
hidden = await db.Relationships
|
||||
.Where(r => (r.RequesterId == meId &&
|
||||
(r.Status == RelationshipStatus.Blocked || r.Ignored)) ||
|
||||
(r.TargetId == meId && r.Status == RelationshipStatus.Blocked))
|
||||
.Select(r => r.RequesterId == meId ? r.TargetId : r.RequesterId)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
var friends = await db.Relationships
|
||||
.Where(r => r.Status == RelationshipStatus.Friend &&
|
||||
(r.RequesterId == meId || r.TargetId == meId))
|
||||
.Select(r => r.RequesterId == meId ? r.TargetId : r.RequesterId)
|
||||
.ToListAsync();
|
||||
var follows = await db.Subscriptions
|
||||
.Where(s => s.SubscriberPlayerId == meId)
|
||||
.Select(s => s.TargetPlayerId)
|
||||
.ToListAsync();
|
||||
affinity = friends.Concat(follows)
|
||||
.Where(id => id > 0 && !hidden.Contains(id))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
}
|
||||
|
||||
var resumed = TryDecodeFeedCursor(continuationToken,
|
||||
out var phase, out var cursorTicks, out var cursorId, out var carriedInjected);
|
||||
|
||||
// Injected items are pinned to the head of the FIRST page only, in
|
||||
// the order the client asked for them (they come from a share
|
||||
// deep-link the player just followed). Their ids ride along in the
|
||||
// cursor so later pages don't repeat them organically.
|
||||
var injectedIds = resumed ? carriedInjected : requestedInjected.Distinct().ToArray();
|
||||
var itemIds = new List<long>();
|
||||
if (!resumed && injectedIds.Length > 0)
|
||||
{
|
||||
var pinned = await VisibleFeedPhotos(hidden)
|
||||
.Where(p => injectedIds.Contains(p.Id))
|
||||
.Select(p => p.Id)
|
||||
.ToListAsync();
|
||||
itemIds.AddRange(injectedIds.Where(pinned.Contains));
|
||||
}
|
||||
|
||||
DateTime? cutoffAt = resumed && cursorTicks > 0 && cursorTicks <= DateTime.MaxValue.Ticks
|
||||
? new DateTime(cursorTicks)
|
||||
: (DateTime?)null;
|
||||
var cutoffId = resumed ? cursorId : 0L;
|
||||
if (phase < 0) phase = 0;
|
||||
|
||||
// Phase 0 = photos from people the caller follows or is friends
|
||||
// with; phase 1 = everyone else. Both are newest-first, and the
|
||||
// cursor is (CreatedAt, Id) so a photo posted mid-scroll can never
|
||||
// shift a row onto a page the client already consumed.
|
||||
while (itemIds.Count < take && phase <= 1)
|
||||
{
|
||||
if (phase == 0 && affinity.Count == 0)
|
||||
{
|
||||
phase = 1;
|
||||
cutoffAt = null;
|
||||
cutoffId = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
var need = take - itemIds.Count;
|
||||
var q = VisibleFeedPhotos(hidden);
|
||||
if (injectedIds.Length > 0)
|
||||
q = q.Where(p => !injectedIds.Contains(p.Id));
|
||||
q = phase == 0
|
||||
? q.Where(p => affinity.Contains(p.UploaderPlayerId))
|
||||
: q.Where(p => !affinity.Contains(p.UploaderPlayerId));
|
||||
if (cutoffAt is DateTime at)
|
||||
{
|
||||
var atId = cutoffId;
|
||||
q = q.Where(p => p.CreatedAt < at || (p.CreatedAt == at && p.Id < atId));
|
||||
}
|
||||
|
||||
var batch = await q
|
||||
.OrderByDescending(p => p.CreatedAt)
|
||||
.ThenByDescending(p => p.Id)
|
||||
.Take(need)
|
||||
.Select(p => new { p.Id, p.CreatedAt })
|
||||
.ToListAsync();
|
||||
itemIds.AddRange(batch.Select(b => b.Id));
|
||||
|
||||
if (batch.Count < need)
|
||||
{
|
||||
phase++;
|
||||
cutoffAt = null;
|
||||
cutoffId = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
cutoffAt = batch[^1].CreatedAt;
|
||||
cutoffId = batch[^1].Id;
|
||||
}
|
||||
}
|
||||
|
||||
// Empty FeedContext = end of the feed; the client stops paging.
|
||||
var nextContext = phase > 1
|
||||
? string.Empty
|
||||
: EncodeFeedCursor(phase, cutoffAt?.Ticks ?? 0, cutoffId, injectedIds);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
Success = true,
|
||||
Error = (string?)null,
|
||||
Value = new
|
||||
{
|
||||
Items = itemIds.Select(id => new
|
||||
{
|
||||
FeedItemType = FeedItemTypeImage,
|
||||
FeedItemId = id,
|
||||
FeedAlgorithmVersion = FeedAlgoVersion,
|
||||
}).ToList(),
|
||||
// The client sends the instance id it generated for this
|
||||
// scroll session and stores whatever comes back; echoing it
|
||||
// keeps its impression telemetry stitched to one session.
|
||||
FeedInstanceId = string.IsNullOrWhiteSpace(requestedInstanceId)
|
||||
? Guid.NewGuid().ToString("N")
|
||||
: requestedInstanceId,
|
||||
FeedContext = nextContext,
|
||||
FeedAlgorithmVersion = FeedAlgoVersion,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Photos eligible for the public home feed: live, public,
|
||||
/// and not from an uploader the caller blocked/ignored.</summary>
|
||||
private IQueryable<PhotoEntity> VisibleFeedPhotos(List<long> hidden)
|
||||
{
|
||||
var q = db.Photos.Where(p => p.IsPublic && p.DeletedAt == null);
|
||||
if (hidden.Count > 0)
|
||||
q = q.Where(p => !hidden.Contains(p.UploaderPlayerId));
|
||||
return q;
|
||||
}
|
||||
|
||||
/// <summary>Case-insensitive property lookup — the 2023 generated
|
||||
/// writers emit PascalCase but their readers register all three
|
||||
/// casings, so tolerate whatever the client sends.</summary>
|
||||
private static bool TryFeedProp(JsonElement obj, string name, out JsonElement value)
|
||||
{
|
||||
foreach (var prop in obj.EnumerateObject())
|
||||
{
|
||||
if (string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = prop.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Opaque base64url cursor handed to the client as
|
||||
/// FeedContext. Carries the phase, the (CreatedAt, Id) keyset
|
||||
/// position within that phase, and the pinned injected ids so they
|
||||
/// stay suppressed on later pages.</summary>
|
||||
private static string EncodeFeedCursor(int phase, long ticks, long lastId, IReadOnlyList<long> injected)
|
||||
{
|
||||
var raw = $"1|{phase}|{ticks}|{lastId}|{string.Join(',', injected)}";
|
||||
return Convert.ToBase64String(Encoding.UTF8.GetBytes(raw))
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
|
||||
private static bool TryDecodeFeedCursor(string? token, out int phase,
|
||||
out long ticks, out long lastId, out long[] injected)
|
||||
{
|
||||
phase = 0;
|
||||
ticks = 0;
|
||||
lastId = 0;
|
||||
injected = Array.Empty<long>();
|
||||
if (string.IsNullOrWhiteSpace(token)) return false;
|
||||
try
|
||||
{
|
||||
var b64 = token.Replace('-', '+').Replace('_', '/');
|
||||
b64 = b64.PadRight(b64.Length + ((4 - (b64.Length % 4)) % 4), '=');
|
||||
var parts = Encoding.UTF8.GetString(Convert.FromBase64String(b64)).Split('|');
|
||||
if (parts.Length != 5 || parts[0] != "1") return false;
|
||||
if (!int.TryParse(parts[1], out phase)) return false;
|
||||
if (!long.TryParse(parts[2], out ticks)) return false;
|
||||
if (!long.TryParse(parts[3], out lastId)) return false;
|
||||
injected = parts[4]
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(s => long.TryParse(s, out var v) ? v : 0L)
|
||||
.Where(v => v > 0)
|
||||
.ToArray();
|
||||
return true;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Garbage/stale cursor — restart the feed from the top instead
|
||||
// of failing the whole pull.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Trim/dedupe tagged ids and drop the uploader's own id.
|
||||
|
||||
@@ -33,7 +33,8 @@ namespace DorkNet.Server.Controllers.API.PlayerEvents;
|
||||
[Authorize]
|
||||
public class PlayerEventsController(
|
||||
DorkNetDbContext db,
|
||||
NotificationService notifications) : ControllerBase
|
||||
NotificationService notifications,
|
||||
PlayerPresenceService presence) : ControllerBase
|
||||
{
|
||||
private long Me => this.RequireCurrentPlayerId();
|
||||
|
||||
@@ -351,6 +352,101 @@ public class PlayerEventsController(
|
||||
return Ok(rows.Select(ResponseWire).ToList());
|
||||
}
|
||||
|
||||
// ── Event instance browser ───────────────────────────────────────────
|
||||
|
||||
/// <summary>GET <c>event/{eventId}/instances</c> — the "which instance of
|
||||
/// this event are my friends in" browser behind the event card's join
|
||||
/// button. Served from the MATCHMAKING-HOST root (no <c>api/</c> prefix),
|
||||
/// which is why it lives on an absolute route here even though the feature
|
||||
/// is a player-event one.
|
||||
///
|
||||
/// Binary evidence: <c>Matchmaking+<GetEventInstanceBrowser>b__0</c>
|
||||
/// (<c>Matchmaking_NestedType_CBMHJMNIHNN.txt:14</c>) formats the literal
|
||||
/// <c>"event/{0}/instances"</c> at <c>:296</c> with <c>[rdi+16]</c> — the
|
||||
/// PlayerEventId off the HPIOAGDJHDH the lambda closes over — then news up
|
||||
/// BNDIAONDFFF with <c>rdx = 0</c> at <c>:124</c>, i.e.
|
||||
/// <c>BestHTTP.HTTPMethods.Get</c>. The declared return type is
|
||||
/// <c>FGLDKEJLAKB<List<PNDCMIMEJLD>></c>, so the body is a BARE
|
||||
/// JSON ARRAY. PNDCMIMEJLD's getters (<c>PNDCMIMEJLD.txt:3-197</c>) are, in
|
||||
/// order, Int64/Int64/Int64/Boolean/DateTime/List<Int32>/String/Int32/
|
||||
/// Boolean/String = RoomInstanceId, RoomId, SubRoomId, IsFull, CreatedAt,
|
||||
/// PlayerIds, SubroomName, PlayerCount, HasModPresent, HashedInstanceId —
|
||||
/// byte-for-byte the SimpleRoomInstance the <c>room/{id}/instances</c>
|
||||
/// browser already returns (<c>Matchmaking.txt:14237</c> issues the room
|
||||
/// variant through the identical BNDIAONDFFF/verb-0 sequence). The last
|
||||
/// four are filled in locally on the watch and are not read back off the
|
||||
/// wire, so we emit the same six camelCase keys
|
||||
/// (<c>Controllers/Match/MatchController.cs:545-553</c>); the 2023 Utf8Json
|
||||
/// formatters carry a camelCase variant per key, so both client
|
||||
/// generations parse it.
|
||||
///
|
||||
/// The event itself only supplies the room to browse: an event is pinned to
|
||||
/// one RoomId, plus the SubRoomId the host picked in the v2 create/edit body
|
||||
/// (persisted in <see cref="EventExtras"/>). Sub-room hops allocate their
|
||||
/// own instance ids and photon rooms, so when the event names a sub-room we
|
||||
/// only surface instances sitting in it.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("/event/{eventId:long}/instances")]
|
||||
public async Task<IActionResult> EventInstances(long eventId)
|
||||
{
|
||||
var evt = await db.PlayerEvents.FirstOrDefaultAsync(e => e.Id == eventId);
|
||||
if (evt is null) return NotFound();
|
||||
|
||||
var extras = (await LoadExtrasAsync(new[] { evt }))[evt.Id];
|
||||
var subRoomId = extras.SubRoomId is long sub && sub > 0 ? sub : (long?)null;
|
||||
|
||||
// Same sourcing as the room browser: presence rows are the live truth
|
||||
// (one instance per distinct PhotonRoomId), and the caller's OWN private
|
||||
// instances are merged in so the host can still see the instance they
|
||||
// created before anyone has joined it. Another player's private
|
||||
// PhotonRoomId is never listed.
|
||||
var pid = this.CurrentPlayerId() ?? 0;
|
||||
var privates = pid == 0
|
||||
? new List<PrivateInstanceEntity>()
|
||||
: await db.PrivateInstances
|
||||
.Where(p => p.RoomId == evt.RoomId && p.OwnerPlayerId == pid)
|
||||
.ToListAsync();
|
||||
|
||||
var byKey = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
foreach (var (room, playerIds) in presence.EnumerateActiveInstances(evt.RoomId))
|
||||
{
|
||||
if (string.IsNullOrEmpty(room.PhotonRoomId)) continue;
|
||||
if (subRoomId is long want && room.SubRoomId != want) continue;
|
||||
byKey[room.PhotonRoomId] = new
|
||||
{
|
||||
roomInstanceId = room.RoomInstanceId,
|
||||
roomId = room.RoomId,
|
||||
subRoomId = room.SubRoomId,
|
||||
// MaxCapacity is the per-instance cap the matchmaker handed
|
||||
// out, so this is a real answer rather than a constant false.
|
||||
isFull = room.MaxCapacity > 0 && playerIds.Count >= room.MaxCapacity,
|
||||
// Presence rows are a TTL cache with no creation timestamp —
|
||||
// there is no stored "instance opened at" for a live instance,
|
||||
// so report the observation time. Private-instance rows below
|
||||
// do carry a real CreatedAt and use it.
|
||||
createdAt = DateTime.UtcNow,
|
||||
playerIds = playerIds.Select(p => (int)p).ToArray(),
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var p in privates)
|
||||
{
|
||||
if (string.IsNullOrEmpty(p.PhotonRoomId) || byKey.ContainsKey(p.PhotonRoomId)) continue;
|
||||
if (subRoomId is long want && p.SubRoomId != want) continue;
|
||||
byKey[p.PhotonRoomId] = new
|
||||
{
|
||||
roomInstanceId = p.Id,
|
||||
roomId = p.RoomId,
|
||||
subRoomId = p.SubRoomId,
|
||||
isFull = false,
|
||||
createdAt = DateTime.SpecifyKind(p.CreatedAt, DateTimeKind.Utc),
|
||||
playerIds = Array.Empty<int>(),
|
||||
};
|
||||
}
|
||||
|
||||
return Ok(byKey.Values.ToList());
|
||||
}
|
||||
|
||||
// ── Wire shape ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The PlayerEvent fields the 2023 client carries that
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using DorkNet.Server.Auth;
|
||||
using DorkNet.Server.Data;
|
||||
using DorkNet.Server.Data.Entities;
|
||||
using DorkNet.Server.Services;
|
||||
|
||||
namespace DorkNet.Server.Controllers.API.ProgressionEvents;
|
||||
|
||||
[ApiController]
|
||||
public class ProgressionEventsController(DorkNetDbContext db, ServerSettingsService serverSettings) : ControllerBase
|
||||
public class ProgressionEventsController(
|
||||
DorkNetDbContext db,
|
||||
ServerSettingsService serverSettings,
|
||||
IConfiguration config) : ControllerBase
|
||||
{
|
||||
/// <summary>CurrencyType enum value the rest of the server uses for
|
||||
/// RecCenter tokens (mirrors <c>ProgressionController.RecCenterTokens</c>).</summary>
|
||||
private const int RecCenterTokens = 2;
|
||||
|
||||
[HttpGet("api/progressionEvents")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Progress()
|
||||
@@ -39,30 +48,29 @@ public class ProgressionEventsController(DorkNetDbContext db, ServerSettingsServ
|
||||
|
||||
var weekly = await serverSettings.GetWeeklyChallengesAsync();
|
||||
var (start, end) = CurrentWeekWindow();
|
||||
// The boost fields must agree with api/progressionEvents/{id}/xpboosts:
|
||||
// ProgressionEventsPurchasableXpBoostModel.Set() takes the guid the
|
||||
// event advertises here and looks it up in the xpboosts list, and
|
||||
// ProgressionEventsModel.GetPurchasableXpBoostId() gates the whole
|
||||
// boost sheet on PurchasableXpBoostId being non-null. Deriving both
|
||||
// from one catalogue keeps them from drifting.
|
||||
var boosts = BoostCatalogue(activeId);
|
||||
var headline = boosts.Count > 0 ? boosts[0] : null;
|
||||
return Ok(new
|
||||
{
|
||||
ProgressionEventId = activeId,
|
||||
Name = "Weekly Progression",
|
||||
Rewards = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
ProgressionEventRewardId = activeId * 1000L,
|
||||
GiftDropId = weekly.Reward.GiftDropId != 0 ? weekly.Reward.GiftDropId : activeId,
|
||||
ImageName = string.Empty,
|
||||
Xp = weekly.Reward.Xp,
|
||||
RewardIndex = 0,
|
||||
IsBonus = false,
|
||||
},
|
||||
},
|
||||
Rewards = BuildRewards(weekly.Reward, activeId),
|
||||
KeepsakeRoomLists = Array.Empty<object>(),
|
||||
StartTime = start,
|
||||
EndTime = end,
|
||||
CollectionEndTime = end,
|
||||
UsesBoost = false,
|
||||
UsesBoost = headline is not null,
|
||||
BoostDailyGameplayMinutesLimit = 0,
|
||||
BoostXpMultiplier = 1.0,
|
||||
PurchasableXpBoostId = (Guid?)null,
|
||||
// ProgressionEventDTO.BoostXpMultiplier is a float at +0x50
|
||||
// (dump.cs:1198957) — emit a real number, not an integer token.
|
||||
BoostXpMultiplier = (double)(headline?.XpMultiplier ?? 1),
|
||||
PurchasableXpBoostId = headline?.Id,
|
||||
ActiveExperiment = string.Empty,
|
||||
ChallengesIconImageName = string.Empty,
|
||||
RewardsPipImageName = string.Empty,
|
||||
@@ -88,24 +96,349 @@ public class ProgressionEventsController(DorkNetDbContext db, ServerSettingsServ
|
||||
{
|
||||
var me = this.RequireCurrentPlayerId();
|
||||
|
||||
// Count this player's completed progression-event objectives so the
|
||||
// record reflects real progress rather than a flat zero.
|
||||
var completed = await db.ObjectiveProgress
|
||||
// Count the reward-claim sentinels this player owns FOR THIS EVENT
|
||||
// (written by Collect below). The previous query counted every
|
||||
// `progressionEvent:` row, which also matches the xpBoost purchase
|
||||
// sentinels StorefrontsBuyController writes — a boost purchase
|
||||
// silently advanced the claimed-reward pip.
|
||||
var claimPrefix = RewardClaimPrefix(progressionEventId);
|
||||
var collected = await db.ObjectiveProgress
|
||||
.CountAsync(o => o.PlayerId == me
|
||||
&& o.IsCompleted
|
||||
&& o.Key.StartsWith("progressionEvent:"));
|
||||
&& o.Key.StartsWith(claimPrefix));
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
ProgressionEventId = progressionEventId,
|
||||
Xp = 0,
|
||||
ClaimedRewardIndex = completed > 0 ? completed - 1 : -1,
|
||||
ClaimedRewardIndex = collected > 0 ? collected - 1 : -1,
|
||||
PurchasedXpBoostCount = 0,
|
||||
DailyBoostGameplayMinutes = 0,
|
||||
XpBoostExpiresAt = (DateTime?)null,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Reward collection ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// POST <c>api/progressionEvents/collect/{eventId}/{rewardIndex}</c> —
|
||||
/// claim one reward chest off the progression track.
|
||||
///
|
||||
/// Binary evidence: <c>RecNet.Runtime/CDBFONFHJDO.txt:1208</c>
|
||||
/// (<c>GKANPKEGBGE(Int64 eventId, Int32 rewardIndex)</c>) formats
|
||||
/// <c>"{0}/collect/{1}/{2}"</c> against <c>"api/progressionEvents"</c>
|
||||
/// (ISIL 041/043) and moves <c>2</c> = <c>HTTPMethods.Post</c> into the
|
||||
/// verb argument at ISIL 055. No request body is passed — the two route
|
||||
/// segments are the whole request.
|
||||
///
|
||||
/// The return type is <c>FGLDKEJLAKB<FFFIMAGLKEG/FHMABOHAEED></c>,
|
||||
/// and <c>FHMABOHAEED</c> is the client's GiftPackage DTO — the very
|
||||
/// same object <c>GiftManager.RunConsumeGift</c> /
|
||||
/// <c>GiftManager.DequeueGift</c> take
|
||||
/// (<c>Assembly-CSharp/GiftManager.txt:3226,3395</c>), whose wire keys are
|
||||
/// Id / FromPlayerId / ConsumableItemDesc / AvatarItemType /
|
||||
/// AvatarItemDesc / EquipmentPrefabName / EquipmentModificationGuid /
|
||||
/// CurrencyType / Currency / Xp / GiftContext / GiftRarity / Message /
|
||||
/// Platform / PlatformsToSpawnOn / BalanceType
|
||||
/// (<c>RecNet.Runtime/FKANCKLCCDI.txt:1051-1390</c>).
|
||||
///
|
||||
/// That means the client will POST the returned <c>Id</c> back to
|
||||
/// <c>api/avatar/v2/gifts/consume</c>, so this MUST persist a real
|
||||
/// <see cref="GiftPackageEntity"/> rather than synthesise a wire blob —
|
||||
/// an unpersisted Id 404s on consume and the player loses the reward.
|
||||
/// The payload itself comes from the admin-configured weekly reward
|
||||
/// (<see cref="WeeklyChallengeReward"/>), i.e. exactly what
|
||||
/// <see cref="Event"/> advertises on the track, so the chest hands over
|
||||
/// what the UI promised. XP / tokens / level ride on the package and are
|
||||
/// granted by the existing consume path, not here — granting in both
|
||||
/// places would double-pay.
|
||||
///
|
||||
/// Idempotent: the claim sentinel is an <see cref="ObjectiveProgressEntity"/>
|
||||
/// whose Key embeds the created gift id, so a retried or duplicated POST
|
||||
/// returns the original package instead of minting a second one.
|
||||
/// No <c>GiftPackageReceived</c> push is sent (unlike
|
||||
/// <c>avatar/v2/gifts/generate</c>): the RRUI reward flow already spawns
|
||||
/// the box from this response, and a push would spawn a second one.
|
||||
/// </summary>
|
||||
[HttpPost("api/progressionEvents/collect/{eventId:long}/{rewardIndex:int}")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Collect(long eventId, int rewardIndex)
|
||||
{
|
||||
var me = this.RequireCurrentPlayerId();
|
||||
|
||||
// Only the live event's track is claimable — the client only ever
|
||||
// renders the active event, and letting an arbitrary id through
|
||||
// would let a replayed request re-roll last week's chest.
|
||||
var activeId = CurrentProgressionEventId();
|
||||
if (eventId != activeId) return NotFound();
|
||||
|
||||
var weekly = await serverSettings.GetWeeklyChallengesAsync();
|
||||
var rewards = BuildRewards(weekly.Reward, activeId);
|
||||
if (rewardIndex < 0 || rewardIndex >= rewards.Count) return NotFound();
|
||||
|
||||
// Already claimed? The sentinel key carries the gift id so we can
|
||||
// hand back the same package (the client may retry after a dropped
|
||||
// response, and it needs a consumable Id either way).
|
||||
var sentinelPrefix = $"{RewardClaimPrefix(eventId)}{rewardIndex}:gift:";
|
||||
var sentinel = await db.ObjectiveProgress
|
||||
.FirstOrDefaultAsync(o => o.PlayerId == me && o.Key.StartsWith(sentinelPrefix));
|
||||
if (sentinel is not null)
|
||||
{
|
||||
if (long.TryParse(sentinel.Key[sentinelPrefix.Length..], out var priorId))
|
||||
{
|
||||
var prior = await db.GiftPackages
|
||||
.FirstOrDefaultAsync(g => g.Id == priorId && g.RecipientPlayerId == me);
|
||||
if (prior is not null)
|
||||
return Ok(global::DorkNet.Server.Controllers.API.Avatar.V2.AvatarGiftsController.ToWire(prior));
|
||||
}
|
||||
// Sentinel exists but its package was purged — drop the stale
|
||||
// marker and fall through to re-issue, otherwise the player is
|
||||
// permanently locked out of a reward they never received.
|
||||
db.ObjectiveProgress.Remove(sentinel);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var reward = weekly.Reward;
|
||||
var gift = new GiftPackageEntity
|
||||
{
|
||||
RecipientPlayerId = me,
|
||||
FromPlayerId = null,
|
||||
// The weekly reward config carries a raw avatar desc, which is
|
||||
// always an outfit item (AvatarItemType 0); hair dyes are
|
||||
// configured through ConsumableItemDesc instead. Leave the type
|
||||
// null when there is no avatar payload so the client doesn't
|
||||
// render an empty outfit tile.
|
||||
AvatarItemType = string.IsNullOrWhiteSpace(reward.AvatarItemDesc) ? (int?)null : 0,
|
||||
AvatarItemDescOrHairDyeDesc = reward.AvatarItemDesc,
|
||||
ConsumableItemDesc = reward.ConsumableItemDesc,
|
||||
EquipmentPrefabName = reward.EquipmentPrefabName,
|
||||
EquipmentModificationGuid = reward.EquipmentModificationGuid,
|
||||
CurrencyType = reward.Tokens > 0 ? RecCenterTokens : 0,
|
||||
Currency = reward.Tokens,
|
||||
Xp = reward.Xp,
|
||||
Level = reward.Level,
|
||||
GiftContext = reward.GiftContext,
|
||||
GiftRarity = reward.GiftRarity,
|
||||
Message = $"Progression event reward {rewardIndex + 1}",
|
||||
Platform = -1,
|
||||
PackageVariant = "Standard",
|
||||
PackageMaterial = string.Empty,
|
||||
IsValid = true,
|
||||
SupportsCurrentPlatform = true,
|
||||
};
|
||||
db.GiftPackages.Add(gift);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
db.ObjectiveProgress.Add(new ObjectiveProgressEntity
|
||||
{
|
||||
PlayerId = me,
|
||||
Key = $"{sentinelPrefix}{gift.Id}",
|
||||
IsCompleted = true,
|
||||
ClearedAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(global::DorkNet.Server.Controllers.API.Avatar.V2.AvatarGiftsController.ToWire(gift));
|
||||
}
|
||||
|
||||
// ── Purchasable XP boosts ────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// GET <c>api/progressionEvents/{eventId}/xpboosts</c> — the boost
|
||||
/// offers the client's purchase sheet renders.
|
||||
///
|
||||
/// Binary evidence: <c>RecNet.Runtime/CDBFONFHJDO.txt:1465</c>
|
||||
/// (<c>HKMBEFABIBD(Int64 eventId)</c>) formats
|
||||
/// <c>"{0}/{1}/xpboosts"</c> against <c>"api/progressionEvents"</c>
|
||||
/// (ISIL 026/028) and moves <c>0</c> = <c>HTTPMethods.Get</c> into the
|
||||
/// verb argument at ISIL 034. The declared return type is
|
||||
/// <c>List<ProgressionEventPurchasableXpBoostDTO></c>, i.e. a bare
|
||||
/// JSON array — no paged container.
|
||||
///
|
||||
/// Element keys and their order come from the generated Utf8Json
|
||||
/// formatter <c>RecNet.Runtime/OFGIPBHIAGF.txt:605-698</c>:
|
||||
/// ProgressionEventPurchasableXpBoostId (Guid), Cost (Int32),
|
||||
/// XpMultiplier (Int32 — <c>get_XpMultiplierFromBoost</c> reads the DTO's
|
||||
/// +0x24 int field, NOT a float), XpCap (Int32), LookbackDurationTicks
|
||||
/// (Int64), CooldownDurationTicks (Int64).
|
||||
///
|
||||
/// The boost id must be STABLE across calls: the client caches it from
|
||||
/// here, passes it to <c>previewEarnedXp</c>, and posts it as
|
||||
/// <c>purchasableXpBoostId</c> to
|
||||
/// <c>api/storefronts/v1/buyProgressionEventXpBoost</c> (which keys its
|
||||
/// purchase sentinel on it). See <see cref="OfferId"/>.
|
||||
/// </summary>
|
||||
[HttpGet("api/progressionEvents/{eventId:long}/xpboosts")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult XpBoosts(long eventId) =>
|
||||
Ok(BoostCatalogue(eventId).Select(b => new
|
||||
{
|
||||
ProgressionEventPurchasableXpBoostId = b.Id,
|
||||
b.Cost,
|
||||
b.XpMultiplier,
|
||||
b.XpCap,
|
||||
b.LookbackDurationTicks,
|
||||
b.CooldownDurationTicks,
|
||||
}));
|
||||
|
||||
/// <summary>
|
||||
/// GET <c>api/progressionEvents/{eventId}/xpboosts/{boostId}/previewEarnedXp</c>
|
||||
/// — how much XP buying this boost right now would hand the caller.
|
||||
///
|
||||
/// Binary evidence: <c>RecNet.Runtime/CDBFONFHJDO.txt:1612</c>
|
||||
/// (<c>GBNFGMOGLNG(Int64 eventId, Guid boostId)</c>) formats
|
||||
/// <c>"{0}/{1}/xpboosts/{2}/previewEarnedXp"</c> against
|
||||
/// <c>"api/progressionEvents"</c> (ISIL 036/038) and moves <c>0</c> =
|
||||
/// <c>HTTPMethods.Get</c> into the verb argument at ISIL 049. The return
|
||||
/// type is <c>FGLDKEJLAKB<System.Int32></c> — a BARE integer body,
|
||||
/// not an object; the value lands in
|
||||
/// <c>ProgressionEventsPurchasableXpBoostModel.get_XpEarnedFromBoost</c>
|
||||
/// and is echoed back as the <c>expectedXp</c> form field of
|
||||
/// <c>buyProgressionEventXpBoost</c>, which grants exactly that much.
|
||||
///
|
||||
/// Cooldown is real state: <c>buyProgressionEventXpBoost</c> stamps
|
||||
/// <c>progressionEvent:{eventId}:xpBoost:{guid:N}</c> in ObjectiveProgress
|
||||
/// on every purchase, so a boost still inside its
|
||||
/// <c>CooldownDurationTicks</c> window previews as 0 and the client's
|
||||
/// <c>get_XPBoostIsAvailableForPurchase</c> keeps the button disabled.
|
||||
///
|
||||
/// Fidelity note: live Rec Room multiplied the XP the player actually
|
||||
/// earned during <c>LookbackDurationTicks</c>. DorkNet has no timestamped
|
||||
/// XP ledger (<see cref="LevelService.AwardXpAsync"/> mutates
|
||||
/// <c>PlayerEntity.XP</c> in place), so a boost here pays its configured
|
||||
/// <c>XpCap</c> — the cap is the payout, and <c>XpMultiplier</c> is the
|
||||
/// figure the sheet renders as "Nx".
|
||||
/// </summary>
|
||||
[HttpGet("api/progressionEvents/{eventId:long}/xpboosts/{boostId:guid}/previewEarnedXp")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> PreviewEarnedXp(long eventId, Guid boostId)
|
||||
{
|
||||
var me = this.RequireCurrentPlayerId();
|
||||
|
||||
var offer = BoostCatalogue(eventId).FirstOrDefault(b => b.Id == boostId);
|
||||
if (offer is null) return Ok(0);
|
||||
|
||||
// Same key StorefrontsBuyController.BuyProgressionEventXpBoost writes.
|
||||
var purchaseKey = $"progressionEvent:{eventId}:xpBoost:{boostId:N}";
|
||||
var lastPurchase = await db.ObjectiveProgress
|
||||
.Where(o => o.PlayerId == me && o.Key == purchaseKey)
|
||||
.Select(o => o.ClearedAt)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (offer.CooldownDurationTicks > 0
|
||||
&& lastPurchase is DateTime at
|
||||
&& DateTime.UtcNow - at < TimeSpan.FromTicks(offer.CooldownDurationTicks))
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
return Ok(offer.XpCap);
|
||||
}
|
||||
|
||||
// ── Shared shape helpers ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>One pip on the progression track. Field types are taken from
|
||||
/// <c>ProgressionEventRewardDTO</c> (dump.cs:1199338): ProgressionEventRewardId
|
||||
/// is Int64 at +0x10 but <b>GiftDropId is Int32</b> at +0x18 (the audit doc
|
||||
/// says Int64 — the binary disagrees), then string ImageName, Int32 Xp,
|
||||
/// Int32 RewardIndex, bool IsBonus.</summary>
|
||||
public sealed record EventReward(
|
||||
long ProgressionEventRewardId,
|
||||
int GiftDropId,
|
||||
string ImageName,
|
||||
int Xp,
|
||||
int RewardIndex,
|
||||
bool IsBonus);
|
||||
|
||||
/// <summary>The progression track's reward list. One source of truth for
|
||||
/// <see cref="Event"/> (which renders the pips) and <see cref="Collect"/>
|
||||
/// (which bounds-checks the claimed index), so the two can't drift into a
|
||||
/// state where the client can see a chest the server refuses to open.</summary>
|
||||
private static IReadOnlyList<EventReward> BuildRewards(WeeklyChallengeReward reward, long activeId) =>
|
||||
[
|
||||
new EventReward(
|
||||
ProgressionEventRewardId: activeId * 1000L,
|
||||
// yyyyMMdd fits Int32 comfortably, so the event id doubles as a
|
||||
// stable placeholder drop id when no reward drop is configured.
|
||||
GiftDropId: reward.GiftDropId != 0 ? reward.GiftDropId : (int)activeId,
|
||||
ImageName: string.Empty,
|
||||
Xp: reward.Xp,
|
||||
RewardIndex: 0,
|
||||
IsBonus: false),
|
||||
];
|
||||
|
||||
private static string RewardClaimPrefix(long eventId) => $"progressionEvent:{eventId}:reward:";
|
||||
|
||||
// ── XP-boost catalogue ───────────────────────────────────────────────
|
||||
|
||||
public sealed record XpBoostOffer(
|
||||
Guid Id,
|
||||
int Cost,
|
||||
int XpMultiplier,
|
||||
int XpCap,
|
||||
long LookbackDurationTicks,
|
||||
long CooldownDurationTicks);
|
||||
|
||||
/// <summary>The boosts this deployment sells for a given event.
|
||||
///
|
||||
/// Configured under <c>ProgressionEvents:XpBoosts</c> as an array of
|
||||
/// <c>{Cost, XpMultiplier, XpCap, LookbackMinutes, CooldownMinutes}</c>;
|
||||
/// with nothing configured we fall back to a single built-in offer (same
|
||||
/// pattern as <see cref="ServerSettingsService.DefaultWeeklyChallenges"/>
|
||||
/// and the built-in NUX checklist). Set
|
||||
/// <c>ProgressionEvents:EnableXpBoosts</c> to false to sell none — the
|
||||
/// event then reports <c>UsesBoost=false</c> and the sheet stays shut.</summary>
|
||||
private IReadOnlyList<XpBoostOffer> BoostCatalogue(long eventId)
|
||||
{
|
||||
if (!config.GetValue("ProgressionEvents:EnableXpBoosts", true))
|
||||
return [];
|
||||
|
||||
var configured = config.GetSection("ProgressionEvents:XpBoosts").GetChildren().ToList();
|
||||
if (configured.Count == 0)
|
||||
{
|
||||
return
|
||||
[
|
||||
new XpBoostOffer(
|
||||
Id: OfferId(eventId, 0),
|
||||
Cost: 250,
|
||||
XpMultiplier: 2,
|
||||
XpCap: 500,
|
||||
LookbackDurationTicks: TimeSpan.FromHours(1).Ticks,
|
||||
CooldownDurationTicks: TimeSpan.FromHours(24).Ticks),
|
||||
];
|
||||
}
|
||||
|
||||
var offers = new List<XpBoostOffer>(configured.Count);
|
||||
for (var i = 0; i < configured.Count; i++)
|
||||
{
|
||||
var section = configured[i];
|
||||
var cap = Math.Max(0, section.GetValue("XpCap", 500));
|
||||
offers.Add(new XpBoostOffer(
|
||||
Id: OfferId(eventId, i),
|
||||
Cost: Math.Max(0, section.GetValue("Cost", 250)),
|
||||
XpMultiplier: Math.Max(1, section.GetValue("XpMultiplier", 2)),
|
||||
XpCap: cap,
|
||||
LookbackDurationTicks: TimeSpan.FromMinutes(
|
||||
Math.Max(0, section.GetValue("LookbackMinutes", 60))).Ticks,
|
||||
CooldownDurationTicks: TimeSpan.FromMinutes(
|
||||
Math.Max(0, section.GetValue("CooldownMinutes", 1440))).Ticks));
|
||||
}
|
||||
return offers;
|
||||
}
|
||||
|
||||
/// <summary>Deterministic per-(event, slot) boost id. The client caches
|
||||
/// the guid from <see cref="XpBoosts"/> and replays it to
|
||||
/// <see cref="PreviewEarnedXp"/> and to
|
||||
/// <c>storefronts/v1/buyProgressionEventXpBoost</c>, whose purchase /
|
||||
/// cooldown sentinel is keyed on it — a freshly generated guid per request
|
||||
/// would make every preview miss its own catalogue entry and reset the
|
||||
/// cooldown on every call. Derived rather than stored because the boost
|
||||
/// catalogue itself lives in configuration, not the database.</summary>
|
||||
private static Guid OfferId(long eventId, int index) =>
|
||||
new(System.Security.Cryptography.SHA256.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes($"dorknet:progressionEventXpBoost:{eventId}:{index}"))
|
||||
.AsSpan(0, 16));
|
||||
|
||||
private static long CurrentProgressionEventId()
|
||||
{
|
||||
var (start, _) = CurrentWeekWindow();
|
||||
|
||||
@@ -2291,6 +2291,109 @@ public class RoomsController(
|
||||
public async Task<IActionResult> CreatedByOther(long otherPlayerId)
|
||||
=> Ok((await rooms.CreatedByAsync(otherPlayerId)).Select(RoomService.ToWireRoom).ToList());
|
||||
|
||||
/// <summary>Per-player showcase curation, stored in the existing generic
|
||||
/// player-settings table as a CSV of room ids. Colon-namespaced to match
|
||||
/// the other server-owned keys (<c>settings:partyinvite</c>).</summary>
|
||||
private const string ShowcaseSettingKey = "rooms:showcase";
|
||||
private const int ShowcaseMaxRooms = 50;
|
||||
|
||||
/// <summary>GET <c>showcase/{accountId}</c> — the profile "Showcase Rooms"
|
||||
/// carousel (<c>RoomListModel.JMGLGEKHHAK.PlayerShowcaseRooms = 7</c>,
|
||||
/// dump.cs:2042498, driven by
|
||||
/// <c>AccountModelController.RoomsShowcaseLinkImpl</c> at dump.cs:2113041).
|
||||
/// Distinct from <c>PlayerCreatedRooms = 5</c>, which is the
|
||||
/// <c>rooms/createdby/{id}</c> list above.
|
||||
///
|
||||
/// <para><b>Verb.</b> <c>NLDBPDCNNCF.EJPNHLIJNPM</c> formats the literal
|
||||
/// <c>"showcase/{0}"</c> (NLDBPDCNNCF.txt ISIL 021 at :4484) and moves the
|
||||
/// HTTPMethods ordinal <c>0</c> (= GET) into rdx immediately before the
|
||||
/// dispatch call (ISIL 031/032 at :4494-4495). No cmov, so GET is the only
|
||||
/// verb. The path arg is boxed as <c>System.Int32</c> (ISIL 017) — the
|
||||
/// account id.</para>
|
||||
///
|
||||
/// <para><b>Response shape.</b> The issuing method's return type is the
|
||||
/// contract: <c>Task<List<System.Int64>></c>
|
||||
/// (NLDBPDCNNCF.txt:4422) — a BARE JSON array of room ids, not Room
|
||||
/// objects and not a <c>{Results,TotalResults}</c> container. The Rooms the
|
||||
/// UI renders are a purely client-side projection: the cache entry
|
||||
/// <c><GetRoomsShowcase>b__0</c> is typed
|
||||
/// <c>Task<IReadOnlyList<Int64>></c>
|
||||
/// (IBEOONPEELF_NestedType_HHDHJPIJBJB.txt:14) and the outer
|
||||
/// <c>IBEOONPEELF.EJPNHLIJNPM</c> resolves those ids through the room cache
|
||||
/// to <c>FGLDKEJLAKB<IReadOnlyList<NEMINAEBALC>></c>
|
||||
/// (IBEOONPEELF.txt:8952) before <c>RoomListModel</c> consumes it
|
||||
/// (RoomListModel.txt ISIL 742 at :5819).</para>
|
||||
///
|
||||
/// <para><b>Backing data.</b> <c>showcase/{0}</c> is the only showcase
|
||||
/// literal in the binary — the 2023 client can read the list but never
|
||||
/// writes it (curation lived on the website), so the curated order is kept
|
||||
/// in the existing per-player settings store under
|
||||
/// <see cref="ShowcaseSettingKey"/> and is writable through
|
||||
/// <c>PUT /settings/v1/{accountId}</c> with no new schema. Curated ids are
|
||||
/// re-validated against Rooms on every read so a room that has since been
|
||||
/// archived or privatised drops off the profile, and the curated order is
|
||||
/// preserved. A player who never curated one falls back to the rooms they
|
||||
/// actually created, most prominent first — the showcase the carousel is
|
||||
/// there to display.</para>
|
||||
///
|
||||
/// <para>Unauthenticated on purpose: this is another player's profile
|
||||
/// surface, and the sibling <c>rooms/createdby/{id}</c> is open too. The
|
||||
/// owner viewing their own profile additionally sees their non-public
|
||||
/// picks; everyone else sees public rooms only.</para></summary>
|
||||
[HttpGet("showcase/{accountId:long}")]
|
||||
// roomserver/ twin: EJPNHLIJNPM lives on NLDBPDCNNCF, whose requests all
|
||||
// arrive with the roomserver/ prefix in this deployment
|
||||
// (docs/recroom-2023-room-save.md:83-93) — same reason every other
|
||||
// NLDBPDCNNCF route in this file is registered twice.
|
||||
[HttpGet("roomserver/showcase/{accountId:long}")]
|
||||
public async Task<IActionResult> RoomsShowcase(long accountId)
|
||||
{
|
||||
var viewerIsOwner = CurrentPlayerId == accountId;
|
||||
|
||||
var curatedCsv = await db.PlayerSettings.AsNoTracking()
|
||||
.Where(s => s.PlayerId == accountId && s.Key == ShowcaseSettingKey)
|
||||
.Select(s => s.Value)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
var curatedIds = (curatedCsv ?? string.Empty)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(v => long.TryParse(v, out var id) ? id : 0L)
|
||||
.Where(id => id > 0)
|
||||
.Distinct()
|
||||
.Take(ShowcaseMaxRooms)
|
||||
.ToList();
|
||||
|
||||
if (curatedIds.Count > 0)
|
||||
{
|
||||
var visible = await db.Rooms.AsNoTracking()
|
||||
.Where(r => curatedIds.Contains(r.Id)
|
||||
&& r.State == 0
|
||||
&& !r.IsDormRoom
|
||||
&& !r.HiddenFromBrowse
|
||||
&& (r.Accessibility == 1 || viewerIsOwner))
|
||||
.Select(r => r.Id)
|
||||
.ToListAsync();
|
||||
var visibleSet = visible.ToHashSet();
|
||||
// Curated order is the display order — filter, don't re-sort.
|
||||
var ordered = curatedIds.Where(visibleSet.Contains).ToList();
|
||||
if (ordered.Count > 0) return Ok(ordered);
|
||||
}
|
||||
|
||||
var fallback = await db.Rooms.AsNoTracking()
|
||||
.Where(r => r.CreatorPlayerId == accountId
|
||||
&& r.State == 0
|
||||
&& !r.IsDormRoom
|
||||
&& !r.HiddenFromBrowse
|
||||
&& (r.Accessibility == 1 || viewerIsOwner))
|
||||
.OrderByDescending(r => r.HotScore)
|
||||
.ThenByDescending(r => r.VisitCount)
|
||||
.ThenByDescending(r => r.UpdatedAt)
|
||||
.Select(r => r.Id)
|
||||
.Take(ShowcaseMaxRooms)
|
||||
.ToListAsync();
|
||||
return Ok(fallback);
|
||||
}
|
||||
|
||||
[HttpGet("api/rooms/v1/visitedby/me")]
|
||||
[HttpGet("api/rooms/v2/visitedby/me")]
|
||||
[HttpGet("api/rooms/v3/visitedby/me")]
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DorkNet.Server.Auth;
|
||||
using DorkNet.Server.Binding;
|
||||
using DorkNet.Server.Data;
|
||||
using DorkNet.Server.Data.Entities;
|
||||
using DorkNet.Server.Services;
|
||||
|
||||
namespace DorkNet.Server.Controllers.API.Subscriptions;
|
||||
|
||||
/// <summary>
|
||||
/// The creator-subscription mutation pair the 2023-03-21 client hits from a
|
||||
/// profile card's Subscribe button. Both live at the bare two-segment route
|
||||
/// <c>subscription/{accountId}</c> on the Clubs host (enum value 13); the
|
||||
/// route literal is <c>"subscription/{0}"</c> formatted with a boxed
|
||||
/// <c>System.Int32</c> account id at
|
||||
/// <c>RecNet.Runtime/IKMMOCKDKAF.txt:6551 (POST, verb rdx=2)</c> and
|
||||
/// <c>:6862 (DELETE, verb rdx=4)</c>. Callers are the account-model wrappers
|
||||
/// <c>OBEEEEAMLJI.BDJCLAGIHBN/LPFOPPHGDHG(Int32 accountId, …)</c>
|
||||
/// (<c>Assembly-CSharp/OBEEEEAMLJI.txt:644,793</c>) behind
|
||||
/// <c>AGUI/StackedUI/SubscribeConditionalButton</c>, so the path segment is
|
||||
/// always a player account id — never a club id.
|
||||
///
|
||||
/// The GET side of this surface already exists but lives with the club reads
|
||||
/// (<c>ClubsController</c>: <c>subscription/details/{id}</c>,
|
||||
/// <c>subscription/subscriberCount/{id}</c>, <c>subscription/mine/member</c>)
|
||||
/// and <c>PlayerSubscriptionsController</c>
|
||||
/// (<c>subscription/top/creators/today</c>). Only the two writes were missing,
|
||||
/// which made every subscribe/unsubscribe 404 and surface the client's
|
||||
/// <c>"Failed to subscribe to {0}"</c> / <c>"Failed to unsubscribe from {0}"</c>
|
||||
/// toast (format literals at <c>IKMMOCKDKAF.txt:6663</c> and the DELETE's
|
||||
/// matching continuation).
|
||||
///
|
||||
/// Neither response body is parsed: the client's continuation is a bare
|
||||
/// <c>Func<IPCJLCNIBEG<Int64>, …></c> whose only use is the
|
||||
/// success/failure branch, after which it invalidates its subscription cache
|
||||
/// and re-reads <c>subscription/mine/member</c> + <c>subscription/details</c>.
|
||||
/// Any 2xx is therefore sufficient — but the reads it follows up with must
|
||||
/// reflect the write, which is why these handlers touch BOTH subscription
|
||||
/// tables (see <see cref="Subscribe"/>).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class SubscriptionsController(
|
||||
DorkNetDbContext db,
|
||||
ClubService clubs,
|
||||
ILogger<SubscriptionsController> logger) : ControllerBase
|
||||
{
|
||||
private long Me => this.RequireCurrentPlayerId();
|
||||
|
||||
/// <summary>
|
||||
/// Body of the subscribe POST. The client appends exactly one
|
||||
/// form-urlencoded field via <c>BNDIAONDFFF.AFGEDDANEKP("roomId", …)</c>
|
||||
/// (<c>IKMMOCKDKAF.txt:6726 — Move rdx, "roomId"</c>), boxed from an
|
||||
/// <c>ObscuredLong</c> holding the room the player is standing in. The
|
||||
/// preceding compare against <c>-1</c> (<c>:6713</c>,
|
||||
/// <c>Compare rax, 18446744073709551615</c> → jump past the append) means
|
||||
/// the field is OMITTED entirely when the player is not in a room, so it
|
||||
/// must be optional. Unsubscribe sends no body at all.
|
||||
/// </summary>
|
||||
public sealed class SubscribeRequest
|
||||
{
|
||||
public long RoomId { get; set; } = -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// POST <c>/subscription/{accountId}</c> — subscribe to a creator.
|
||||
///
|
||||
/// Writes two rows, because the 2023 client's post-subscribe refresh reads
|
||||
/// two differently-sourced endpoints and both have to agree:
|
||||
/// * <see cref="DorkNetDbContext.Subscriptions"/> (player→player) is what
|
||||
/// <c>subscription/details/{id}</c>, <c>subscription/subscriberCount/{id}</c>,
|
||||
/// <c>subscription/top/creators/today</c> and the PlayerState reputation
|
||||
/// aggregate all count. This is the canonical row.
|
||||
/// * <see cref="DorkNetDbContext.ClubSubscriptions"/> is what
|
||||
/// <c>subscription/mine/member</c> and
|
||||
/// <c>announcements/v2/subscription/mine/unread</c> read. A creator's
|
||||
/// "creator club" is the club they own (same resolution
|
||||
/// <c>subscription/details</c> uses for its <c>ClubId</c> field — oldest
|
||||
/// id wins), so when the target owns one we mirror the subscription
|
||||
/// there too. Without the mirror the subscribe succeeds but the
|
||||
/// creator never appears in the client's own subscribed list and the
|
||||
/// button flips straight back to "Subscribe" on the next cache refresh.
|
||||
/// Creators with no club get only the canonical row, which is all their
|
||||
/// profile card reads.
|
||||
///
|
||||
/// Idempotent: re-subscribing is a 200 no-op rather than a unique-index
|
||||
/// violation (both tables carry a unique pair index).
|
||||
/// </summary>
|
||||
[HttpPost("/subscription/{accountId:long}")]
|
||||
public async Task<IActionResult> Subscribe(
|
||||
long accountId,
|
||||
[ModelBinder(typeof(FormOrJsonModelBinder))] SubscribeRequest req)
|
||||
{
|
||||
var me = Me;
|
||||
if (accountId == me) return BadRequest(new { Error = "cannot_subscribe_to_self" });
|
||||
|
||||
var targetExists = await db.Players.AnyAsync(p => p.Id == accountId);
|
||||
if (!targetExists) return NotFound(new { Error = "account_not_found" });
|
||||
|
||||
var changed = false;
|
||||
|
||||
var existing = await db.Subscriptions.FirstOrDefaultAsync(
|
||||
s => s.SubscriberPlayerId == me && s.TargetPlayerId == accountId);
|
||||
if (existing is null)
|
||||
{
|
||||
db.Subscriptions.Add(new SubscriptionEntity
|
||||
{
|
||||
SubscriberPlayerId = me,
|
||||
TargetPlayerId = accountId,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
|
||||
var creatorClubId = await CreatorClubIdAsync(accountId);
|
||||
if (creatorClubId != 0)
|
||||
{
|
||||
var existingClub = await db.ClubSubscriptions.FirstOrDefaultAsync(
|
||||
s => s.PlayerId == me && s.ClubId == creatorClubId);
|
||||
if (existingClub is null)
|
||||
{
|
||||
db.ClubSubscriptions.Add(new ClubSubscriptionEntity
|
||||
{
|
||||
ClubId = creatorClubId,
|
||||
PlayerId = me,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) await db.SaveChangesAsync();
|
||||
|
||||
// roomId is pure attribution — "which room was this creator discovered
|
||||
// in". There is no column for it on SubscriptionEntity and this pass
|
||||
// adds no schema, so it is recorded in the log rather than silently
|
||||
// dropped; the subscription itself is fully persisted above.
|
||||
if (req.RoomId > 0)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Player {SubscriberId} subscribed to creator {AccountId} from room {RoomId}.",
|
||||
me, accountId, req.RoomId);
|
||||
}
|
||||
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DELETE <c>/subscription/{accountId}</c> — unsubscribe. Same route
|
||||
/// literal, verb register <c>rdx=4</c> at
|
||||
/// <c>IKMMOCKDKAF.txt:6864</c>; the request carries no parameters
|
||||
/// (<c>AFGEDDANEKP</c> is never called on the builder before the send),
|
||||
/// so there is nothing to bind.
|
||||
///
|
||||
/// Removes both rows written by <see cref="Subscribe"/> so the canonical
|
||||
/// counts and the <c>subscription/mine/member</c> list drop the creator
|
||||
/// together. Unsubscribing when not subscribed is a 200 no-op — the client
|
||||
/// treats any non-2xx as the "Failed to unsubscribe from {0}" toast, and a
|
||||
/// double-tap of an already-removed subscription is not a failure the
|
||||
/// player should see.
|
||||
/// </summary>
|
||||
[HttpDelete("/subscription/{accountId:long}")]
|
||||
public async Task<IActionResult> Unsubscribe(long accountId)
|
||||
{
|
||||
var me = Me;
|
||||
|
||||
var row = await db.Subscriptions.FirstOrDefaultAsync(
|
||||
s => s.SubscriberPlayerId == me && s.TargetPlayerId == accountId);
|
||||
if (row is not null) db.Subscriptions.Remove(row);
|
||||
|
||||
var creatorClubId = await CreatorClubIdAsync(accountId);
|
||||
if (creatorClubId != 0)
|
||||
{
|
||||
var clubRow = await db.ClubSubscriptions.FirstOrDefaultAsync(
|
||||
s => s.PlayerId == me && s.ClubId == creatorClubId);
|
||||
if (clubRow is not null) db.ClubSubscriptions.Remove(clubRow);
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The club id <c>subscription/details/{accountId}</c> reports as the
|
||||
/// creator's <c>ClubId</c>: the oldest live club the account owns, or 0
|
||||
/// when they own none. Kept byte-identical to that handler's resolution so
|
||||
/// subscribing writes the row the details card points the player at.
|
||||
/// </summary>
|
||||
private async Task<long> CreatorClubIdAsync(long accountId)
|
||||
{
|
||||
var created = await clubs.CreatedByAsync(accountId);
|
||||
return created.Count > 0 ? created.Min(c => c.Id) : 0L;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user