diff --git a/api/.sqlx/query-05845fdb39cec480cfa34441c591594827f4b38fa1cc1b81d2974fc8141fa7b5.json b/api/.sqlx/query-05845fdb39cec480cfa34441c591594827f4b38fa1cc1b81d2974fc8141fa7b5.json deleted file mode 100644 index 5127cbf..0000000 --- a/api/.sqlx/query-05845fdb39cec480cfa34441c591594827f4b38fa1cc1b81d2974fc8141fa7b5.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT shown.map AS \"map!\", shown.track AS \"track!\", shown.time AS \"time!\",\n CASE WHEN NOT shown.legacy THEN 1 + (\n SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = shown.map_id AND faster.style = $2 AND faster.track = shown.track\n AND faster.time < shown.time) END AS rank,\n shown.legacy AS \"legacy!\", shown.id AS \"id!\", shown.finished_at\n FROM (\n SELECT DISTINCT ON (both_kinds.map, both_kinds.track) both_kinds.*\n FROM (\n SELECT m.name AS map, pb.map_id, pb.track, pb.time, false AS legacy, pb.run_id AS id,\n pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE $3 AND pb.player_steamid64 = $1 AND pb.style = $2 AND pb.track = $4\n UNION ALL\n SELECT lm.name, NULL::bigint, $4::smallint, l.time, true, l.id::bigint, l.finished_at\n FROM legacy_personal_bests l\n JOIN legacy_maps lm ON lm.id = l.map_id\n WHERE l.player_steamid64 = $1 AND NOT EXISTS (SELECT 1 FROM records_bans b WHERE b.player_steamid64 = $1)\n ) both_kinds\n WHERE $5::text IS NULL OR (both_kinds.map, both_kinds.track) > ($5, $6::smallint)\n ORDER BY both_kinds.map, both_kinds.track, both_kinds.time, both_kinds.legacy\n LIMIT $7\n ) shown\n ORDER BY shown.map, shown.track\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "map!", - "type_info": "Text", - "origin": "Expression" - }, - { - "ordinal": 1, - "name": "track!", - "type_info": "Int2", - "origin": "Expression" - }, - { - "ordinal": 2, - "name": "time!", - "type_info": "Float8", - "origin": "Expression" - }, - { - "ordinal": 3, - "name": "rank", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 4, - "name": "legacy!", - "type_info": "Bool", - "origin": "Expression" - }, - { - "ordinal": 5, - "name": "id!", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "finished_at", - "type_info": "Timestamptz", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Int8", - "Text", - "Bool", - "Int2", - "Text", - "Int2", - "Int8" - ] - }, - "nullable": [ - null, - null, - null, - null, - null, - null, - null - ] - }, - "hash": "05845fdb39cec480cfa34441c591594827f4b38fa1cc1b81d2974fc8141fa7b5" -} diff --git a/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json b/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json deleted file mode 100644 index 5f3a590..0000000 --- a/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH tiers AS (\n SELECT DISTINCT ON (map_id, track) map_id, track, tier FROM map_tiers\n WHERE $1 ORDER BY map_id, track, assigned_at DESC\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT b.map_id, b.style, b.track, b.best, t.tier\n FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b\n LEFT JOIN tiers t ON t.map_id = b.map_id AND t.track = b.track\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Bool" - ] - }, - "nullable": [] - }, - "hash": "07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df" -} diff --git a/api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json b/api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json similarity index 86% rename from api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json rename to api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json index baccabe..3cb673f 100644 --- a/api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json +++ b/api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT DISTINCT ON (pb.track, pb.style)\n pb.track, pb.style, pb.time, pb.run_id, r.finished_at,\n count(*) OVER (PARTITION BY pb.track, pb.style) AS \"players!\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n (SELECT tier FROM map_tiers WHERE map_id = pb.map_id AND track = pb.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier\n FROM personal_bests pb\n JOIN runs r ON r.id = pb.run_id\n JOIN players p ON p.steamid64 = pb.player_steamid64\n WHERE pb.map_id = $1\n ORDER BY pb.track, pb.style, pb.time, r.finished_at\n ", + "query": "\n SELECT DISTINCT ON (pb.track, pb.style)\n pb.track, pb.style, pb.time, pb.run_id, r.finished_at,\n count(*) OVER (PARTITION BY pb.track, pb.style) AS \"players!\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n (SELECT tier FROM current_map_tiers WHERE map_id = pb.map_id AND track = pb.track) AS tier\n FROM personal_bests pb\n JOIN runs r ON r.id = pb.run_id\n JOIN players p ON p.steamid64 = pb.player_steamid64\n WHERE pb.map_id = $1\n ORDER BY pb.track, pb.style, pb.time, r.finished_at\n ", "describe": { "columns": [ { @@ -129,5 +129,5 @@ null ] }, - "hash": "5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d" + "hash": "1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed" } diff --git a/api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json b/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json similarity index 89% rename from api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json rename to api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json index b3e15ca..f132edf 100644 --- a/api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json +++ b/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", + "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", "describe": { "columns": [ { @@ -324,11 +324,11 @@ null, null, null, - false, - false, - false, + true, + true, + true, null ] }, - "hash": "1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6" + "hash": "2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d" } diff --git a/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json b/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json deleted file mode 100644 index 1186ab4..0000000 --- a/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT max(tier) FROM (\n SELECT DISTINCT ON (map_id, track) tier FROM map_tiers ORDER BY map_id, track, assigned_at DESC\n ) in_force\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "max", - "type_info": "Int2", - "origin": "Expression" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c" -} diff --git a/api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json b/api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json deleted file mode 100644 index 551cd91..0000000 --- a/api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name)\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1))", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "count!", - "type_info": "Int8", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Int8", - "Bool", - "Text", - "Int2" - ] - }, - "nullable": [ - null - ] - }, - "hash": "2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316" -} diff --git a/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json new file mode 100644 index 0000000..81b821c --- /dev/null +++ b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json @@ -0,0 +1,91 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT shown.map AS \"map!\", shown.track AS \"track!\", shown.time AS \"time!\",\n CASE WHEN NOT shown.legacy THEN 1 + (\n SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = shown.map_id AND faster.style = $2 AND faster.track = shown.track\n AND faster.time < shown.time) END AS rank,\n CASE WHEN NOT shown.legacy THEN (\n SELECT min(best.time) FROM personal_bests best\n WHERE best.map_id = shown.map_id AND best.style = $2 AND best.track = shown.track)\n END AS world_record_time,\n shown.legacy AS \"legacy!\", shown.id AS \"id!\", shown.finished_at, tier.tier AS \"tier?\"\n FROM (\n SELECT DISTINCT ON (both_kinds.map, both_kinds.track) both_kinds.*\n FROM (\n SELECT m.name AS map, pb.map_id, pb.track, pb.time, false AS legacy, pb.run_id AS id,\n pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE $3 AND pb.player_steamid64 = $1 AND pb.style = $2 AND pb.track = $4\n UNION ALL\n SELECT lm.name, NULL::bigint, $4::smallint, l.time, true, l.id::bigint, l.finished_at\n FROM legacy_personal_bests l\n JOIN legacy_maps lm ON lm.id = l.map_id\n WHERE l.player_steamid64 = $1 AND NOT EXISTS (SELECT 1 FROM records_bans b WHERE b.player_steamid64 = $1)\n ) both_kinds\n WHERE $5::text IS NULL OR (both_kinds.map, both_kinds.track) > ($5, $6::smallint)\n ORDER BY both_kinds.map, both_kinds.track, both_kinds.time, both_kinds.legacy\n LIMIT $7\n ) shown\n -- A legacy row's map_id is NULL, so it finds no tier.\n LEFT JOIN current_map_tiers tier ON $8 AND tier.map_id = shown.map_id AND tier.track = shown.track\n ORDER BY shown.map, shown.track\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "map!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "track!", + "type_info": "Int2", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "time!", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "rank", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "world_record_time", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 5, + "name": "legacy!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "id!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": "Expression" + }, + { + "ordinal": 8, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + } + ], + "parameters": { + "Left": [ + "Int8", + "Text", + "Bool", + "Int2", + "Text", + "Int2", + "Int8", + "Bool" + ] + }, + "nullable": [ + null, + null, + null, + null, + null, + null, + null, + null, + true + ] + }, + "hash": "2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0" +} diff --git a/api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json b/api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json similarity index 51% rename from api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json rename to api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json index 4efb421..94cb7c5 100644 --- a/api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json +++ b/api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT m.name, week.players AS \"players!\",\n (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 ORDER BY assigned_at DESC LIMIT 1)\n AS tier\n FROM (SELECT map_id, count(DISTINCT player_steamid64) AS players FROM runs\n WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'\n GROUP BY map_id) week\n JOIN maps m ON m.id = week.map_id\n ORDER BY week.players DESC, m.name LIMIT $1", + "query": "SELECT m.name, week.players AS \"players!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM (SELECT map_id, count(DISTINCT player_steamid64) AS players FROM runs\n WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'\n GROUP BY map_id) week\n JOIN maps m ON m.id = week.map_id\n WHERE $2::smallint IS NULL OR $2 =\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0)\n ORDER BY week.players DESC, m.name LIMIT $1", "describe": { "columns": [ { @@ -29,7 +29,8 @@ ], "parameters": { "Left": [ - "Int8" + "Int8", + "Int2" ] }, "nullable": [ @@ -38,5 +39,5 @@ null ] }, - "hash": "f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2" + "hash": "4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf" } diff --git a/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json b/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json new file mode 100644 index 0000000..281c45c --- /dev/null +++ b/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET\n country_chosen = $2::text IS NOT NULL,\n country_from_server = country_from_server AND $2::text IS NULL,\n country_code = CASE WHEN $2::text IS NOT NULL THEN $2\n WHEN country_chosen THEN NULL ELSE country_code END,\n steam_profile_fetched_at = CASE WHEN $2::text IS NULL AND country_chosen THEN NULL\n ELSE steam_profile_fetched_at END\n WHERE steamid64 = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [] + }, + "hash": "4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1" +} diff --git a/api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json b/api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json similarity index 57% rename from api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json rename to api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json index d5c0a59..135dfe0 100644 --- a/api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json +++ b/api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT tier.tier AS \"tier?\", count(*) AS \"maps!\" FROM maps m\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1) tier ON true\n WHERE m.last_run_at IS NOT NULL\n GROUP BY tier.tier", + "query": "SELECT tier.tier AS \"tier?\", count(*) AS \"maps!\" FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n WHERE m.last_run_at IS NOT NULL\n GROUP BY tier.tier", "describe": { "columns": [ { @@ -9,7 +9,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -25,9 +25,9 @@ "Left": [] }, "nullable": [ - false, + true, null ] }, - "hash": "d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236" + "hash": "59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752" } diff --git a/api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json b/api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json similarity index 84% rename from api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json rename to api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json index 362f45f..53a71f4 100644 --- a/api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json +++ b/api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT r.id, m.name AS map, r.style, r.track, r.time, r.sync, r.strafes, r.jumps, r.finished_at, r.was_record,\n r.player_steamid64::text AS \"steamid64!\", p.name AS player, s.name AS server_name,\n (SELECT st->>'name' FROM rulesets, jsonb_array_elements(document->'styles') st\n WHERE st->>'key' = r.style ORDER BY version DESC LIMIT 1) AS style_name,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_record,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.player_steamid64 = r.player_steamid64\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_personal_best,\n (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM unnest($1::bigint[]) WITH ORDINALITY AS wanted (run_id, place)\n JOIN runs r ON r.id = wanted.run_id\n JOIN maps m ON m.id = r.map_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n JOIN servers s ON s.id = r.server_id\n ORDER BY wanted.place\n ", + "query": "\n SELECT r.id, m.name AS map, r.style, r.track, r.time, r.sync, r.strafes, r.jumps, r.finished_at, r.was_record,\n r.player_steamid64::text AS \"steamid64!\", p.name AS player, s.name AS server_name,\n (SELECT st->>'name' FROM rulesets, jsonb_array_elements(document->'styles') st\n WHERE st->>'key' = r.style ORDER BY version DESC LIMIT 1) AS style_name,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_record,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.player_steamid64 = r.player_steamid64\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_personal_best,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM unnest($1::bigint[]) WITH ORDINALITY AS wanted (run_id, place)\n JOIN runs r ON r.id = wanted.run_id\n JOIN maps m ON m.id = r.map_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n JOIN servers s ON s.id = r.server_id\n ORDER BY wanted.place\n ", "describe": { "columns": [ { @@ -205,5 +205,5 @@ null ] }, - "hash": "0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c" + "hash": "5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941" } diff --git a/api/.sqlx/query-5b6cb1e375d768e19f444b9f407d80ab686ec4309e28f33e98af9653e0510e43.json b/api/.sqlx/query-5b6cb1e375d768e19f444b9f407d80ab686ec4309e28f33e98af9653e0510e43.json deleted file mode 100644 index 777adfb..0000000 --- a/api/.sqlx/query-5b6cb1e375d768e19f444b9f407d80ab686ec4309e28f33e98af9653e0510e43.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH bounds AS (\n SELECT make_interval(mins => $1) AS bucket,\n date_bin(make_interval(mins => $1), now(), TIMESTAMPTZ '2000-01-01') AS current\n ), buckets AS (\n SELECT generate_series(current - $2 * bucket, current - bucket, bucket) AS at FROM bounds\n ), per_server AS (\n SELECT date_bin(bounds.bucket, h.received_at, TIMESTAMPTZ '2000-01-01') AS at,\n h.ip, h.port, avg(h.players) AS players\n FROM server_heartbeat_log h\n CROSS JOIN bounds\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at >= bounds.current - $2 * bounds.bucket AND h.received_at < bounds.current\n GROUP BY 1, 2, 3\n )\n SELECT b.at AS \"at!\", count(p.ip)::int AS \"servers!\", coalesce(round(sum(p.players)), 0)::int AS \"players!\"\n FROM buckets b\n LEFT JOIN per_server p ON p.at = b.at\n GROUP BY b.at\n ORDER BY b.at\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "at!", - "type_info": "Timestamptz", - "origin": "Expression" - }, - { - "ordinal": 1, - "name": "servers!", - "type_info": "Int4", - "origin": "Expression" - }, - { - "ordinal": 2, - "name": "players!", - "type_info": "Int4", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Int4", - "Float8" - ] - }, - "nullable": [ - null, - null, - null - ] - }, - "hash": "5b6cb1e375d768e19f444b9f407d80ab686ec4309e28f33e98af9653e0510e43" -} diff --git a/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json b/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json new file mode 100644 index 0000000..4b5be87 --- /dev/null +++ b/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH now AS MATERIALIZED (\n SELECT b.map_id, b.style, b.track,\n (SELECT min(pb.time) FROM personal_bests pb\n WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best,\n CASE WHEN $5 THEN (SELECT t.tier FROM current_map_tiers t\n WHERE t.map_id = b.map_id AND t.track = b.track) END AS tier\n FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track)\n ), runners AS MATERIALIZED (\n SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4)\n ), moved AS (\n SELECT now.*, stored.best AS stored_best, stored.tier AS stored_tier\n FROM now JOIN standings_boards stored USING (map_id, style, track)\n WHERE now.best IS NOT NULL AND (now.best, now.tier) IS DISTINCT FROM (stored.best, stored.tier)\n ), changes AS (\n SELECT pb.style, pb.track > 0 AS bonus, pb.player_steamid64,\n sum(coalesce(points_for(m.tier, pb.time, m.best, pb.track > 0, $6, $7, $8, $9, $10), 0)\n - coalesce(points_for(m.stored_tier, pb.time, m.stored_best, pb.track > 0,\n $6, $7, $8, $9, $10), 0)) AS change\n FROM moved m\n JOIN personal_bests pb ON pb.map_id = m.map_id AND pb.style = m.style AND pb.track = m.track\n -- The runs' players are summed again below.\n WHERE NOT EXISTS (\n SELECT 1 FROM runners r\n WHERE r.player_steamid64 = pb.player_steamid64 AND r.style = pb.style AND r.bonus = (pb.track > 0)\n )\n GROUP BY 1, 2, 3\n ), moved_totals AS (\n UPDATE standings s SET points = s.points + c.change FROM changes c\n WHERE s.style = c.style AND s.bonus = c.bonus AND s.player_steamid64 = c.player_steamid64\n AND c.change <> 0\n ), emptied AS (\n DELETE FROM standings_boards stored USING now\n WHERE stored.map_id = now.map_id AND stored.style = now.style AND stored.track = now.track\n AND now.best IS NULL\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT map_id, style, track, best, tier FROM now WHERE best IS NOT NULL\n ON CONFLICT (map_id, style, track) DO UPDATE SET best = excluded.best, tier = excluded.tier\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8Array", + "TextArray", + "Int2Array", + "Int8Array", + "Bool", + "Float8", + "Float8", + "Float8", + "Float8", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5" +} diff --git a/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json b/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json new file mode 100644 index 0000000..fbf1f26 --- /dev/null +++ b/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url FROM legacy_players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "legacy_players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "legacy_players", + "name": "avatar_url" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c" +} diff --git a/api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json b/api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json similarity index 76% rename from api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json rename to api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json index dcda92c..9854c93 100644 --- a/api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json +++ b/api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT m.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", m.last_run_at,\n (SELECT tier FROM map_tiers t WHERE t.map_id = m.id AND t.track = 0\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version\n FROM maps m\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n WHERE m.name ILIKE $1 ESCAPE '\\' AND (NOT $4 OR m.last_run_at IS NULL)\n ORDER BY m.name\n LIMIT $2 OFFSET $3\n ", + "query": "\n SELECT m.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", m.last_run_at,\n (SELECT tier FROM current_map_tiers t WHERE t.map_id = m.id AND t.track = 0) AS tier,\n (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version\n FROM maps m\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n WHERE m.name ILIKE $1 ESCAPE '\\' AND (NOT $4 OR m.last_run_at IS NULL)\n ORDER BY m.name\n LIMIT $2 OFFSET $3\n ", "describe": { "columns": [ { @@ -89,5 +89,5 @@ null ] }, - "hash": "8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4" + "hash": "724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b" } diff --git a/api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json b/api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json deleted file mode 100644 index 2f81701..0000000 --- a/api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json +++ /dev/null @@ -1,190 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2 ELSE 3 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1) tier ON true\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\' OR $7 <% m.name)\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "name", - "type_info": "Text", - "origin": { - "Table": { - "table": "maps", - "name": "name" - } - } - }, - { - "ordinal": 1, - "name": "image_id?", - "type_info": "Int8", - "origin": { - "Table": { - "table": "map_images", - "name": "id" - } - } - }, - { - "ordinal": 2, - "name": "image_key?", - "type_info": "Text", - "origin": { - "Table": { - "table": "map_images", - "name": "key" - } - } - }, - { - "ordinal": 3, - "name": "image_focus?", - "type_info": "Int2", - "origin": { - "Table": { - "table": "map_images", - "name": "focus" - } - } - }, - { - "ordinal": 4, - "name": "last_run_at!", - "type_info": "Timestamptz", - "origin": { - "Table": { - "table": "maps", - "name": "last_run_at" - } - } - }, - { - "ordinal": 5, - "name": "players!", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "bonuses!", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 7, - "name": "tier?", - "type_info": "Int2", - "origin": { - "Table": { - "table": "map_tiers", - "name": "tier" - } - } - }, - { - "ordinal": 8, - "name": "wr_time?", - "type_info": "Float8", - "origin": { - "Table": { - "table": "personal_bests", - "name": "time" - } - } - }, - { - "ordinal": 9, - "name": "wr_run_id?", - "type_info": "Int8", - "origin": { - "Table": { - "table": "personal_bests", - "name": "run_id" - } - } - }, - { - "ordinal": 10, - "name": "wr_finished_at?", - "type_info": "Timestamptz", - "origin": { - "Table": { - "table": "runs", - "name": "finished_at" - } - } - }, - { - "ordinal": 11, - "name": "wr_steamid64?", - "type_info": "Text", - "origin": "Expression" - }, - { - "ordinal": 12, - "name": "wr_name?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "name" - } - } - }, - { - "ordinal": 13, - "name": "wr_avatar_url?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "avatar_url" - } - } - }, - { - "ordinal": 14, - "name": "wr_country_code?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "country_code" - } - } - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Int8", - "Int8", - "Text", - "Text", - "Text", - "Int8", - "Bool", - "Int2" - ] - }, - "nullable": [ - false, - false, - false, - false, - true, - null, - null, - false, - true, - true, - true, - null, - true, - true, - true - ] - }, - "hash": "74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845" -} diff --git a/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json b/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json new file mode 100644 index 0000000..1d2e98d --- /dev/null +++ b/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM sessions WHERE player_steamid64 = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020" +} diff --git a/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json new file mode 100644 index 0000000..6db845f --- /dev/null +++ b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name\n OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\\'))\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Bool", + "Text", + "Int2", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28" +} diff --git a/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json b/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json index e34ab12..f6017d1 100644 --- a/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json +++ b/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json @@ -99,7 +99,7 @@ false, true, null, - true, + false, true, true ] diff --git a/api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json b/api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json similarity index 62% rename from api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json rename to api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json index 0a1eb8e..859f51a 100644 --- a/api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json +++ b/api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT m.name, m.listed_at AS \"listed_at!\",\n (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 ORDER BY assigned_at DESC LIMIT 1)\n AS tier\n FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL\n ORDER BY m.listed_at DESC, m.name LIMIT $1", + "query": "SELECT m.name, m.listed_at AS \"listed_at!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL\n AND ($2::smallint IS NULL OR $2 =\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))\n ORDER BY m.listed_at DESC, m.name LIMIT $1", "describe": { "columns": [ { @@ -34,7 +34,8 @@ ], "parameters": { "Left": [ - "Int8" + "Int8", + "Int2" ] }, "nullable": [ @@ -43,5 +44,5 @@ null ] }, - "hash": "6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852" + "hash": "8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3" } diff --git a/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json b/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json new file mode 100644 index 0000000..90db3ff --- /dev/null +++ b/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT coalesce(max(players), 0) AS \"players!\" FROM server_activity_peaks\n WHERE day >= (now() AT TIME ZONE 'UTC')::date - $1::int", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "players!", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4" + ] + }, + "nullable": [ + null + ] + }, + "hash": "93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003" +} diff --git a/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json b/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json new file mode 100644 index 0000000..f5d4034 --- /dev/null +++ b/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT count(*) AS \"total!\"\n FROM runs r\n LEFT JOIN current_map_tiers tier ON $5 AND tier.map_id = r.map_id AND tier.track = r.track\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "total!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int2", + "Bool", + "Bool" + ] + }, + "nullable": [ + null + ] + }, + "hash": "98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a" +} diff --git a/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json b/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json new file mode 100644 index 0000000..e45a363 --- /dev/null +++ b/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM server_activity_peaks WHERE day < current_date - 400", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017" +} diff --git a/api/.sqlx/query-a9c1668c23595148dae099063553e60c7876573fdcdb78c49deb9fe758dcbba5.json b/api/.sqlx/query-a9c1668c23595148dae099063553e60c7876573fdcdb78c49deb9fe758dcbba5.json deleted file mode 100644 index 803009b..0000000 --- a/api/.sqlx/query-a9c1668c23595148dae099063553e60c7876573fdcdb78c49deb9fe758dcbba5.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE players SET\n country_chosen = $2::text IS NOT NULL,\n country_code = CASE WHEN $2::text IS NOT NULL THEN $2\n WHEN country_chosen THEN NULL ELSE country_code END,\n steam_profile_fetched_at = CASE WHEN $2::text IS NULL AND country_chosen THEN NULL\n ELSE steam_profile_fetched_at END\n WHERE steamid64 = $1\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "a9c1668c23595148dae099063553e60c7876573fdcdb78c49deb9fe758dcbba5" -} diff --git a/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json b/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json new file mode 100644 index 0000000..b4055b4 --- /dev/null +++ b/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url FROM players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840" +} diff --git a/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json b/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json new file mode 100644 index 0000000..10e8bf2 --- /dev/null +++ b/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT max(tier) FROM current_map_tiers\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "max", + "type_info": "Int2", + "origin": "Expression" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8" +} diff --git a/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json b/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json new file mode 100644 index 0000000..26d5f71 --- /dev/null +++ b/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url, steam_profile_fetched_at FROM players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 2, + "name": "steam_profile_fetched_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "players", + "name": "steam_profile_fetched_at" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820" +} diff --git a/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json b/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json deleted file mode 100644 index ecdd558..0000000 --- a/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH now AS MATERIALIZED (\n SELECT b.map_id, b.style, b.track,\n (SELECT min(pb.time) FROM personal_bests pb\n WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best,\n CASE WHEN $5 THEN (SELECT t.tier FROM map_tiers t WHERE t.map_id = b.map_id AND t.track = b.track\n ORDER BY t.assigned_at DESC LIMIT 1) END AS tier\n FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track)\n ), runners AS MATERIALIZED (\n SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4)\n ), moved AS (\n SELECT now.*, stored.best AS stored_best, stored.tier AS stored_tier\n FROM now JOIN standings_boards stored USING (map_id, style, track)\n WHERE now.best IS NOT NULL AND (now.best, now.tier) IS DISTINCT FROM (stored.best, stored.tier)\n ), changes AS (\n SELECT pb.style, pb.track > 0 AS bonus, pb.player_steamid64,\n sum(coalesce(points_for(m.tier, pb.time, m.best, pb.track > 0, $6, $7, $8, $9, $10), 0)\n - coalesce(points_for(m.stored_tier, pb.time, m.stored_best, pb.track > 0,\n $6, $7, $8, $9, $10), 0)) AS change\n FROM moved m\n JOIN personal_bests pb ON pb.map_id = m.map_id AND pb.style = m.style AND pb.track = m.track\n -- The runs' players are summed again below.\n WHERE NOT EXISTS (\n SELECT 1 FROM runners r\n WHERE r.player_steamid64 = pb.player_steamid64 AND r.style = pb.style AND r.bonus = (pb.track > 0)\n )\n GROUP BY 1, 2, 3\n ), moved_totals AS (\n UPDATE standings s SET points = s.points + c.change FROM changes c\n WHERE s.style = c.style AND s.bonus = c.bonus AND s.player_steamid64 = c.player_steamid64\n AND c.change <> 0\n ), emptied AS (\n DELETE FROM standings_boards stored USING now\n WHERE stored.map_id = now.map_id AND stored.style = now.style AND stored.track = now.track\n AND now.best IS NULL\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT map_id, style, track, best, tier FROM now WHERE best IS NOT NULL\n ON CONFLICT (map_id, style, track) DO UPDATE SET best = excluded.best, tier = excluded.tier\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8Array", - "TextArray", - "Int2Array", - "Int8Array", - "Bool", - "Float8", - "Float8", - "Float8", - "Float8", - "Float8" - ] - }, - "nullable": [] - }, - "hash": "bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670" -} diff --git a/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json new file mode 100644 index 0000000..0d333b9 --- /dev/null +++ b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json @@ -0,0 +1,191 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH holder_maps AS (\n SELECT h.map_id FROM world_record_holders h\n JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE $11::text IS NOT NULL AND h.style = $5 AND h.track = 0\n AND p.name ILIKE $11 ESCAPE '\\'\n ), listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2\n WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' AND $7 <% m.name\n THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\'\n OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps))\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "image_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "map_images", + "name": "id" + } + } + }, + { + "ordinal": 2, + "name": "image_key?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 3, + "name": "image_focus?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "map_images", + "name": "focus" + } + } + }, + { + "ordinal": 4, + "name": "last_run_at!", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "last_run_at" + } + } + }, + { + "ordinal": 5, + "name": "players!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "bonuses!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 8, + "name": "wr_time?", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 9, + "name": "wr_run_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 10, + "name": "wr_finished_at?", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "runs", + "name": "finished_at" + } + } + }, + { + "ordinal": 11, + "name": "wr_steamid64?", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 12, + "name": "wr_name?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 13, + "name": "wr_avatar_url?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 14, + "name": "wr_country_code?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "country_code" + } + } + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Int8", + "Text", + "Text", + "Text", + "Int8", + "Bool", + "Int2", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null, + null, + true, + true, + true, + true, + null, + true, + true, + true + ] + }, + "hash": "bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7" +} diff --git a/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json b/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json new file mode 100644 index 0000000..33b215e --- /dev/null +++ b/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json @@ -0,0 +1,54 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH bounds AS (\n SELECT make_interval(mins => $1) AS bucket,\n date_bin(make_interval(mins => $1), now(), TIMESTAMPTZ '2000-01-01') AS current,\n date_bin(make_interval(mins => $3), now(), TIMESTAMPTZ '2000-01-01') AS latest\n ), buckets AS (\n SELECT generate_series(current - $2 * bucket, current - bucket, bucket) AS at FROM bounds\n ), per_server AS (\n SELECT date_bin(bounds.bucket, h.received_at, TIMESTAMPTZ '2000-01-01') AS at,\n h.ip, h.port, avg(h.players) AS players\n FROM server_heartbeat_log h\n CROSS JOIN bounds\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at >= bounds.current - $2 * bounds.bucket AND h.received_at < bounds.current\n GROUP BY 1, 2, 3\n ), online AS (\n SELECT m.at, sum(latest.players) AS players\n FROM bounds\n CROSS JOIN generate_series(\n bounds.current - $2 * bounds.bucket,\n bounds.latest,\n make_interval(mins => $3)\n ) AS m(at)\n CROSS JOIN LATERAL (\n SELECT DISTINCT ON (h.ip, h.port) h.players\n FROM server_heartbeat_log h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at > m.at - make_interval(mins => $4) AND h.received_at <= m.at\n ORDER BY h.ip, h.port, h.received_at DESC\n ) latest\n GROUP BY m.at\n ), peaks AS (\n SELECT date_bin(bounds.bucket, online.at, TIMESTAMPTZ '2000-01-01') AS at, max(online.players) AS players\n FROM online CROSS JOIN bounds\n GROUP BY 1\n ), whole AS (\n SELECT coalesce(max(online.players), 0)::int AS players\n FROM online CROSS JOIN bounds\n WHERE online.at >= bounds.current - $2 * bounds.bucket\n )\n SELECT b.at AS \"at!\", count(p.ip)::int AS \"servers!\", coalesce(round(sum(p.players)), 0)::int AS \"players!\",\n coalesce(pk.players, 0)::int AS \"peak_players!\", whole.players AS \"range_peak!\"\n FROM buckets b\n CROSS JOIN whole\n LEFT JOIN per_server p ON p.at = b.at\n LEFT JOIN peaks pk ON pk.at = b.at\n GROUP BY b.at, pk.players, whole.players\n ORDER BY b.at\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "at!", + "type_info": "Timestamptz", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "servers!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "players!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "peak_players!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "range_peak!", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4", + "Float8", + "Int4", + "Int4" + ] + }, + "nullable": [ + null, + null, + null, + null, + null + ] + }, + "hash": "c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3" +} diff --git a/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json b/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json new file mode 100644 index 0000000..5a8cd7c --- /dev/null +++ b/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT b.map_id, b.style, b.track, b.best, t.tier\n FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b\n LEFT JOIN current_map_tiers t ON $1 AND t.map_id = b.map_id AND t.track = b.track\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bool" + ] + }, + "nullable": [] + }, + "hash": "cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333" +} diff --git a/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json b/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json new file mode 100644 index 0000000..4c70ab6 --- /dev/null +++ b/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json @@ -0,0 +1,91 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT pb.player_steamid64::text AS \"steamid64!\", pb.style, pb.track, pb.time, pb.run_id,\n pb.finished_at,\n 1 + (SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = pb.map_id AND faster.style = pb.style AND faster.track = pb.track\n AND faster.time < pb.time) AS \"rank!\"\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE m.name = $1 AND pb.player_steamid64 = ANY($2)\n ORDER BY pb.player_steamid64, pb.style, pb.track\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "steamid64!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "style", + "type_info": "Text", + "origin": { + "Table": { + "table": "personal_bests", + "name": "style" + } + } + }, + { + "ordinal": 2, + "name": "track", + "type_info": "Int2", + "origin": { + "Table": { + "table": "personal_bests", + "name": "track" + } + } + }, + { + "ordinal": 3, + "name": "time", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 4, + "name": "run_id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 5, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "personal_bests", + "name": "finished_at" + } + } + }, + { + "ordinal": 6, + "name": "rank!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8Array" + ] + }, + "nullable": [ + null, + false, + false, + false, + false, + false, + null + ] + }, + "hash": "d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b" +} diff --git a/api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json b/api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json similarity index 60% rename from api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json rename to api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json index 186b6c9..fed768d 100644 --- a/api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json +++ b/api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record,\n tier.tier\n FROM runs r\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $7\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", + "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record,\n tier.tier\n FROM runs r\n LEFT JOIN current_map_tiers tier ON $7 AND tier.map_id = r.map_id AND tier.track = r.track\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8 OFFSET $9\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", "describe": { "columns": [ { @@ -75,7 +75,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -152,6 +152,7 @@ "Timestamptz", "Int8", "Bool", + "Int8", "Int8" ] }, @@ -162,7 +163,7 @@ false, false, false, - false, + true, null, false, null, @@ -172,5 +173,5 @@ true ] }, - "hash": "79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19" + "hash": "d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8" } diff --git a/api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json b/api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json similarity index 57% rename from api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json rename to api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json index 9c9760e..36105bc 100644 --- a/api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json +++ b/api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json @@ -1,15 +1,15 @@ { "db_name": "PostgreSQL", - "query": "SELECT tier FROM map_tiers WHERE map_id = $1 AND track = $2 ORDER BY assigned_at DESC LIMIT 1", + "query": "SELECT tier AS \"tier!\" FROM current_map_tiers WHERE map_id = $1 AND track = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "tier", + "name": "tier!", "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -22,8 +22,8 @@ ] }, "nullable": [ - false + true ] }, - "hash": "193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f" + "hash": "e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed" } diff --git a/api/.sqlx/query-e8461c94cdc9a070ad92f8775d49ddddfd4e6a2d3d2e60667fc8bd7bf1720dc1.json b/api/.sqlx/query-e8461c94cdc9a070ad92f8775d49ddddfd4e6a2d3d2e60667fc8bd7bf1720dc1.json deleted file mode 100644 index 5f39239..0000000 --- a/api/.sqlx/query-e8461c94cdc9a070ad92f8775d49ddddfd4e6a2d3d2e60667fc8bd7bf1720dc1.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE players SET\n avatar_url = $2,\n -- A country the player picked on their profile stays.\n country_code = CASE WHEN country_chosen THEN country_code ELSE $3 END,\n steam_profile_fetched_at = now(),\n name = CASE WHEN name_seen_at = '-infinity' AND $4::text IS NOT NULL THEN $4 ELSE name END\n WHERE steamid64 = $1\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text", - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "e8461c94cdc9a070ad92f8775d49ddddfd4e6a2d3d2e60667fc8bd7bf1720dc1" -} diff --git a/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json b/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json new file mode 100644 index 0000000..56c3130 --- /dev/null +++ b/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO server_activity_peaks AS p (day, players)\n SELECT (now() AT TIME ZONE 'UTC')::date, coalesce(sum(latest.players), 0)\n FROM (\n SELECT DISTINCT ON (h.ip, h.port) h.players\n FROM server_heartbeat_log h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at > now() - make_interval(mins => $1)\n ORDER BY h.ip, h.port, h.received_at DESC\n ) latest\n ON CONFLICT (day) DO UPDATE SET players = greatest(p.players, excluded.players)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int4" + ] + }, + "nullable": [] + }, + "hash": "e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597" +} diff --git a/api/.sqlx/query-5d5552b38e89f4ba65a4739c79d3902426a3541c08ea94eb96efc73cfdd91d28.json b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json similarity index 50% rename from api/.sqlx/query-5d5552b38e89f4ba65a4739c79d3902426a3541c08ea94eb96efc73cfdd91d28.json rename to api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json index fe7f77d..4ce9614 100644 --- a/api/.sqlx/query-5d5552b38e89f4ba65a4739c79d3902426a3541c08ea94eb96efc73cfdd91d28.json +++ b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT own.style AS \"style!\", own.map AS \"map!\", own.track AS \"track!\", own.time AS \"time!\",\n 1 + (SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = own.map_id AND faster.style = own.style\n AND faster.track = own.track AND faster.time < own.time) AS \"rank!\",\n own.run_id AS \"run_id!\", own.finished_at AS \"finished_at!\"\n FROM (\n SELECT pb.style, pb.map_id, m.name AS map, pb.track, pb.time, pb.run_id, pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE pb.player_steamid64 = $1\n AND ($2::text IS NULL OR pb.style = $2)\n AND ($3::text IS NULL OR (m.name, pb.track) > ($3, $4::smallint))\n AND ($6::bool IS NULL OR (pb.track > 0) = $6)\n AND (NOT $7 OR EXISTS (\n SELECT 1 FROM world_record_holders h\n WHERE h.player_steamid64 = $1 AND h.map_id = pb.map_id AND h.style = pb.style\n AND h.track = pb.track))\n AND ($9::timestamptz IS NULL OR (pb.finished_at, pb.run_id) < ($9, $10::int8))\n ORDER BY CASE WHEN $8 THEN pb.finished_at END DESC, CASE WHEN $8 THEN pb.run_id END DESC,\n pb.style, m.name, pb.track\n LIMIT $5\n ) own\n ORDER BY CASE WHEN $8 THEN own.finished_at END DESC, CASE WHEN $8 THEN own.run_id END DESC,\n own.style, own.map, own.track\n ", + "query": "\n SELECT own.style AS \"style!\", own.map AS \"map!\", own.track AS \"track!\", own.time AS \"time!\",\n 1 + (SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = own.map_id AND faster.style = own.style\n AND faster.track = own.track AND faster.time < own.time) AS \"rank!\",\n (SELECT min(best.time) FROM personal_bests best\n WHERE best.map_id = own.map_id AND best.style = own.style\n AND best.track = own.track) AS \"world_record_time!\",\n own.run_id AS \"run_id!\", own.finished_at AS \"finished_at!\", tier.tier AS \"tier?\"\n FROM (\n SELECT pb.style, pb.map_id, m.name AS map, pb.track, pb.time, pb.run_id, pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE pb.player_steamid64 = $1\n AND ($2::text IS NULL OR pb.style = $2)\n AND ($3::text IS NULL OR (m.name, pb.track) > ($3, $4::smallint))\n AND ($6::bool IS NULL OR (pb.track > 0) = $6)\n AND (NOT $7 OR EXISTS (\n SELECT 1 FROM world_record_holders h\n WHERE h.player_steamid64 = $1 AND h.map_id = pb.map_id AND h.style = pb.style\n AND h.track = pb.track))\n AND ($9::timestamptz IS NULL OR (pb.finished_at, pb.run_id) < ($9, $10::int8))\n ORDER BY CASE WHEN $8 THEN pb.finished_at END DESC, CASE WHEN $8 THEN pb.run_id END DESC,\n pb.style, m.name, pb.track\n LIMIT $5\n ) own\n LEFT JOIN current_map_tiers tier ON $11 AND tier.map_id = own.map_id AND tier.track = own.track\n ORDER BY CASE WHEN $8 THEN own.finished_at END DESC, CASE WHEN $8 THEN own.run_id END DESC,\n own.style, own.map, own.track\n ", "describe": { "columns": [ { @@ -55,6 +55,12 @@ }, { "ordinal": 5, + "name": "world_record_time!", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 6, "name": "run_id!", "type_info": "Int8", "origin": { @@ -65,7 +71,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "finished_at!", "type_info": "Timestamptz", "origin": { @@ -74,6 +80,17 @@ "name": "finished_at" } } + }, + { + "ordinal": 8, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } } ], "parameters": { @@ -87,7 +104,8 @@ "Bool", "Bool", "Timestamptz", - "Int8" + "Int8", + "Bool" ] }, "nullable": [ @@ -96,9 +114,11 @@ false, false, null, + null, + false, false, - false + true ] }, - "hash": "5d5552b38e89f4ba65a4739c79d3902426a3541c08ea94eb96efc73cfdd91d28" + "hash": "e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212" } diff --git a/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json b/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json new file mode 100644 index 0000000..00c8f4a --- /dev/null +++ b/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET country_code = $2, country_from_server = true, country_chosen = false\n WHERE steamid64 = $1 AND name_seen_at <= $3\n AND (country_code IS DISTINCT FROM $2 OR NOT country_from_server)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Timestamptz" + ] + }, + "nullable": [] + }, + "hash": "edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869" +} diff --git a/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json b/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json new file mode 100644 index 0000000..88c2c6b --- /dev/null +++ b/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET\n avatar_url = $2,\n -- Steam's country comes last: one a game server found or the player picked stays.\n country_code = CASE WHEN country_chosen OR country_from_server THEN country_code ELSE $3 END,\n steam_profile_fetched_at = now(),\n name = CASE WHEN name_seen_at = '-infinity' AND $4::text IS NOT NULL THEN $4 ELSE name END\n WHERE steamid64 = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8" +} diff --git a/api/.sqlx/query-acb722e75d97bd75a675a6e0153070345c0ef081f30d9e5efd1307f4b74008b4.json b/api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json similarity index 62% rename from api/.sqlx/query-acb722e75d97bd75a675a6e0153070345c0ef081f30d9e5efd1307f4b74008b4.json rename to api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json index 3fabd8b..8bf4ecc 100644 --- a/api/.sqlx/query-acb722e75d97bd75a675a6e0153070345c0ef081f30d9e5efd1307f4b74008b4.json +++ b/api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH days AS (\n SELECT generate_series((today - $1::int)::timestamp, (today - 1)::timestamp, interval '1 day')::date AS day\n FROM (SELECT (now() AT TIME ZONE 'UTC')::date AS today) t\n )\n SELECT days.day::timestamp AT TIME ZONE 'UTC' AS \"at!\",\n count(d.ip)::int AS \"servers!\",\n coalesce(round(sum(d.players_sum::float8 / d.heartbeats)), 0)::int AS \"players!\"\n FROM days\n LEFT JOIN server_activity_daily d ON d.day = days.day\n AND EXISTS (SELECT 1 FROM server_listings l WHERE l.ip = d.ip AND l.port = d.port)\n GROUP BY days.day\n ORDER BY days.day\n ", + "query": "\n WITH days AS (\n SELECT generate_series((today - $1::int)::timestamp, (today - 1)::timestamp, interval '1 day')::date AS day\n FROM (SELECT (now() AT TIME ZONE 'UTC')::date AS today) t\n )\n SELECT days.day::timestamp AT TIME ZONE 'UTC' AS \"at!\",\n count(d.ip)::int AS \"servers!\",\n coalesce(round(sum(d.players_sum::float8 / d.heartbeats)), 0)::int AS \"players!\",\n coalesce(pk.players, 0) AS \"peak_players!\"\n FROM days\n LEFT JOIN server_activity_daily d ON d.day = days.day\n AND EXISTS (SELECT 1 FROM server_listings l WHERE l.ip = d.ip AND l.port = d.port)\n LEFT JOIN server_activity_peaks pk ON pk.day = days.day\n GROUP BY days.day, pk.players\n ORDER BY days.day\n ", "describe": { "columns": [ { @@ -20,6 +20,12 @@ "name": "players!", "type_info": "Int4", "origin": "Expression" + }, + { + "ordinal": 3, + "name": "peak_players!", + "type_info": "Int4", + "origin": "Expression" } ], "parameters": { @@ -28,10 +34,11 @@ ] }, "nullable": [ + null, null, null, null ] }, - "hash": "acb722e75d97bd75a675a6e0153070345c0ef081f30d9e5efd1307f4b74008b4" + "hash": "fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d" } diff --git a/api/contract/maps-personal-bests.json b/api/contract/maps-personal-bests.json new file mode 100644 index 0000000..7b05fda --- /dev/null +++ b/api/contract/maps-personal-bests.json @@ -0,0 +1,28 @@ +{ + "method": "GET", + "path": "/v1/maps/bhop_badges/personal-bests?players=76561197960287930,76561197960287931", + "status": 200, + "response": { + "map": "bhop_badges", + "personal_bests": [ + { + "steamid64": "76561197960287930", + "style": "normal", + "track": 0, + "time": 42.42, + "rank": 1, + "run_id": 1, + "finished_at": "2026-10-19T08:53:20Z" + }, + { + "steamid64": "76561197960287930", + "style": "normal", + "track": 1, + "time": 12.5, + "rank": 3, + "run_id": 2, + "finished_at": "2026-10-19T08:55:00Z" + } + ] + } +} diff --git a/api/contract/runs.json b/api/contract/runs.json index 8e5b7e3..1253420 100644 --- a/api/contract/runs.json +++ b/api/contract/runs.json @@ -6,7 +6,8 @@ "server_run_id": "9b2f6a1e-4c1d-4e7a-9a51-3f0f6f1c2d10", "player": { "steamid64": "76561197960287930", - "name": "gabe" + "name": "gabe", + "country_code": "SE" }, "map": "bhop_badges", "style": "normal", diff --git a/api/crates/api/migrations/0052_players_country_from_server.sql b/api/crates/api/migrations/0052_players_country_from_server.sql new file mode 100644 index 0000000..9faf57b --- /dev/null +++ b/api/crates/api/migrations/0052_players_country_from_server.sql @@ -0,0 +1,6 @@ +-- Whether `players.country_code` came from a game server: its GeoIP lookup of the player's address, sent with a +-- run. A player's country has one source at a time, so this and `country_chosen` are never both true. Which +-- source wins is in `docs/site-api.md`. +ALTER TABLE players + ADD COLUMN country_from_server boolean NOT NULL DEFAULT false, + ADD CONSTRAINT players_one_country_source CHECK (NOT (country_chosen AND country_from_server)); diff --git a/api/crates/api/migrations/0053_server_activity_peaks.sql b/api/crates/api/migrations/0053_server_activity_peaks.sql new file mode 100644 index 0000000..44ee529 --- /dev/null +++ b/api/crates/api/migrations/0053_server_activity_peaks.sql @@ -0,0 +1,29 @@ +-- The most players online at once across listed servers per UTC day, for the activity chart's year view. +-- Per-server daily averages can't give a cross-server "at once" peak, so heartbeats keep this (see +-- `servers/heartbeat.rs`), and it's kept for 400 days like `server_activity_daily`. +CREATE TABLE server_activity_peaks ( + day date PRIMARY KEY, + players integer NOT NULL CHECK (players >= 0) +); + +-- Back-filled from the 30-day log by the rule `servers/activity.rs` uses up to a month: every 5 minutes, each +-- listed server's latest heartbeat within the last 15 minutes, summed; the day's highest sum. +INSERT INTO server_activity_peaks (day, players) +SELECT (online.at AT TIME ZONE 'UTC')::date, max(online.players) +FROM ( + SELECT m.at, sum(latest.players) AS players + FROM generate_series( + date_bin(interval '5 minutes', (SELECT min(received_at) FROM server_heartbeat_log), TIMESTAMPTZ '2000-01-01'), + now(), + interval '5 minutes' + ) AS m(at) + CROSS JOIN LATERAL ( + SELECT DISTINCT ON (h.ip, h.port) h.players + FROM server_heartbeat_log h + JOIN server_listings l ON l.ip = h.ip AND l.port = h.port + WHERE h.received_at > m.at - interval '15 minutes' AND h.received_at <= m.at + ORDER BY h.ip, h.port, h.received_at DESC + ) latest + GROUP BY m.at +) online +GROUP BY 1; diff --git a/api/crates/api/migrations/0054_current_map_tiers.sql b/api/crates/api/migrations/0054_current_map_tiers.sql new file mode 100644 index 0000000..e7b613d --- /dev/null +++ b/api/crates/api/migrations/0054_current_map_tiers.sql @@ -0,0 +1,8 @@ +-- The tier in force per map and track: the newest assignment in `map_tiers`, which is append-only history. +-- Queries read this instead of each repeating "newest first, take one" (14 copies before it). Conditions on +-- map_id and track reach the primary key through the view, so one map's or track's lookup still reads only its +-- own rows. It says nothing of whether tiers are in force yet (the `tiers` policy); callers still decide that. +CREATE VIEW current_map_tiers AS +SELECT DISTINCT ON (map_id, track) map_id, track, tier, assigned_at, assigned_by +FROM map_tiers +ORDER BY map_id, track, assigned_at DESC; diff --git a/api/crates/api/src/auth.rs b/api/crates/api/src/auth.rs index cda6ca2..df8b1a4 100644 --- a/api/crates/api/src/auth.rs +++ b/api/crates/api/src/auth.rs @@ -75,6 +75,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(start)) .routes(routes!(callback)) .routes(routes!(sign_out)) + .routes(routes!(sign_out_everywhere)) .routes(routes!(me)) } @@ -189,6 +190,38 @@ async fn sign_out( )) } +/// Ends every session of the signed-in player, in every browser, and signs this one out. A form on the +/// website posts here. Unlike signing out, it needs a live session: answering a request without one as if it +/// had worked would tell the player their other browsers were signed out when nothing was ended. +#[utoipa::path( + post, + path = "/v1/auth/sign-out-everywhere", + tag = "auth", + params(ReturnQuery), + responses( + (status = SEE_OTHER, description = "Back to the page the player came from, signed out everywhere"), + (status = UNAUTHORIZED, description = "Not signed in; no session was ended", body = ErrorBody), + (status = FORBIDDEN, description = "Not sent from SourceJump's own pages", body = ErrorBody), + ), +)] +async fn sign_out_everywhere( + State(state): State, + headers: HeaderMap, + jar: CookieJar, + signed_in: Option, + Query(query): Query, +) -> Result<(CookieJar, Redirect), ApiError> { + sessions::require_same_origin(&headers, &state.public_url)?; + let signed_in = signed_in.ok_or(ApiError::SignInRequired)?; + sessions::end_all(&state.db, signed_in.steamid64).await?; + tracing::info!(steamid64 = %signed_in.steamid64, "signed out everywhere"); + let return_to = ReturnTo::new(query.return_to.as_deref()); + Ok(( + jar.remove(sessions::removal_cookie()), + Redirect::to(return_to.as_str()), + )) +} + /// The signed-in player, from the session cookie. #[utoipa::path( get, @@ -405,6 +438,49 @@ mod tests { assert_eq!(me_with(&state, &token).await.status, 401); } + #[sqlx::test] + async fn signing_out_everywhere_ends_every_session_of_the_player_only(db: PgPool) { + let state = state(&db, fake_steam(true).await); + let token = session_from(&sign_in(&state).await); + let player = players::SteamId64::try_from(openid::tests::PLAYER.to_owned()).unwrap(); + // The same player signed in on another computer, and someone else signed in. + let elsewhere = sessions::create(&db, player).await.unwrap(); + let other = players::SteamId64::try_from("76561197960287931".to_owned()).unwrap(); + players::ensure_exists(&db, other).await.unwrap(); + let someone_else = sessions::create(&db, other).await.unwrap(); + let sign_out_everywhere = |origin: &'static str| { + test_client::send_to( + state.clone(), + Request::post("/v1/auth/sign-out-everywhere?return_to=/maps") + .header(header::COOKIE, format!("sj_session={token}")) + .header(header::ORIGIN, origin) + .body(Body::empty()) + .unwrap(), + ) + }; + + assert_eq!( + sign_out_everywhere("https://evil.example").await.status, + 403 + ); + assert_eq!(me_with(&state, &elsewhere).await.status, 200); + + let response = sign_out_everywhere("https://sourcejump.test").await; + assert_eq!(response.status, 303); + assert_eq!(response.headers[header::LOCATION], "/maps"); + let removed = set_cookie(&response, "sj_session").expect("the session cookie is removed"); + assert!(removed.starts_with("sj_session=;"), "{removed}"); + assert_eq!(me_with(&state, &token).await.status, 401); + assert_eq!(me_with(&state, &elsewhere).await.status, 401); + assert_eq!(me_with(&state, &someone_else).await.status, 200); + + // Again without a live session: refused, so it never looks like it ended something. + let again = sign_out_everywhere("https://sourcejump.test").await; + assert_eq!(again.status, 401); + assert!(!again.headers.contains_key(header::LOCATION)); + let _: ErrorBody = again.json(); + } + #[sqlx::test] async fn start_sends_the_browser_to_steam(db: PgPool) { let response = test_client::get(&db, "/v1/auth/steam?return_to=//evil.example").await; diff --git a/api/crates/api/src/auth/sessions.rs b/api/crates/api/src/auth/sessions.rs index f7e99f2..cc5b484 100644 --- a/api/crates/api/src/auth/sessions.rs +++ b/api/crates/api/src/auth/sessions.rs @@ -40,6 +40,17 @@ pub async fn create(db: &PgPool, steamid64: SteamId64) -> Result Result<(), sqlx::Error> { + sqlx::query!( + "DELETE FROM sessions WHERE player_steamid64 = $1", + steamid64.get() + ) + .execute(db) + .await?; + Ok(()) +} + pub async fn end(db: &PgPool, token: &str) -> Result<(), sqlx::Error> { sqlx::query!("DELETE FROM sessions WHERE hash = $1", &hash(token)[..]) .execute(db) diff --git a/api/crates/api/src/contract.rs b/api/crates/api/src/contract.rs index a64446c..0e7697c 100644 --- a/api/crates/api/src/contract.rs +++ b/api/crates/api/src/contract.rs @@ -9,13 +9,14 @@ use sqlx::PgPool; use crate::{ anticheat::DetectionAccepted, error::ErrorBody, plugin_releases::PluginRelease, - record_events::RecordEvents, records::MapRecords, ruleset::Ruleset, runs::RunAccepted, + record_events::RecordEvents, records::MapRecords, + records::personal_bests::PlayersPersonalBests, ruleset::Ruleset, runs::RunAccepted, servers::heartbeat::HeartbeatResponse, servers::keys, test_client, zones::Zone, }; type ResponseCheck = fn(&str, &Value); -const EXAMPLES: [(&str, &str, ResponseCheck); 9] = [ +const EXAMPLES: [(&str, &str, ResponseCheck); 10] = [ ( "ruleset", include_str!("../../../contract/ruleset.json"), @@ -41,6 +42,11 @@ const EXAMPLES: [(&str, &str, ResponseCheck); 9] = [ include_str!("../../../contract/maps-records.json"), round_trips::, ), + ( + "maps-personal-bests", + include_str!("../../../contract/maps-personal-bests.json"), + round_trips::, + ), ( "records-events", include_str!("../../../contract/records-events.json"), diff --git a/api/crates/api/src/leaderboards/standings.rs b/api/crates/api/src/leaderboards/standings.rs index ae609f5..92e2d72 100644 --- a/api/crates/api/src/leaderboards/standings.rs +++ b/api/crates/api/src/leaderboards/standings.rs @@ -150,8 +150,8 @@ async fn refresh( SELECT b.map_id, b.style, b.track, (SELECT min(pb.time) FROM personal_bests pb WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best, - CASE WHEN $5 THEN (SELECT t.tier FROM map_tiers t WHERE t.map_id = b.map_id AND t.track = b.track - ORDER BY t.assigned_at DESC LIMIT 1) END AS tier + CASE WHEN $5 THEN (SELECT t.tier FROM current_map_tiers t + WHERE t.map_id = b.map_id AND t.track = b.track) END AS tier FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track) ), runners AS MATERIALIZED ( SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4) @@ -262,14 +262,10 @@ pub async fn refresh_all(conn: &mut PgConnection) -> Result<(), sqlx::Error> { .await?; sqlx::query!( r#" - WITH tiers AS ( - SELECT DISTINCT ON (map_id, track) map_id, track, tier FROM map_tiers - WHERE $1 ORDER BY map_id, track, assigned_at DESC - ) INSERT INTO standings_boards (map_id, style, track, best, tier) SELECT b.map_id, b.style, b.track, b.best, t.tier FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b - LEFT JOIN tiers t ON t.map_id = b.map_id AND t.track = b.track + LEFT JOIN current_map_tiers t ON $1 AND t.map_id = b.map_id AND t.track = b.track "#, formula.tiers ) diff --git a/api/crates/api/src/legacy.rs b/api/crates/api/src/legacy.rs index a37842f..4eca276 100644 --- a/api/crates/api/src/legacy.rs +++ b/api/crates/api/src/legacy.rs @@ -176,8 +176,10 @@ mod tests { use sqlx::PgPool; use crate::{ + maps::MapName, + policies::{Policy, TiersPolicy}, runs::tests::{run, setup}, - test_client, + staff, test_client, }; const GABE: &str = "76561197960287930"; @@ -362,6 +364,19 @@ mod tests { 0 ); + staff::policies::publish_policy( + &db, + None, + None, + &Policy::Tiers(TiersPolicy { count: 5 }), + None, + ) + .await + .unwrap(); + let badges = MapName::try_from("bhop_badges".to_owned()).unwrap(); + staff::maps::set_tier(&db, None, &badges, 0, 3) + .await + .unwrap(); let pbs = get( &db, &format!("/v1/players/{ALICE}/personal-bests?style=normal&view=legacy"), @@ -374,6 +389,14 @@ mod tests { .map(|pb| (pb["map"].as_str().unwrap(), pb["time"].as_f64().unwrap())) .collect(); assert_eq!(maps, [("bhop_badges", 25.0), ("bhop_oldonly", 40.0)]); + // Legacy runs have no tier or record time, even on a map whose board has both. + assert!( + pbs["personal_bests"] + .as_array() + .unwrap() + .iter() + .all(|pb| pb["tier"].is_null() && pb["world_record_time"].is_null()) + ); let gabe = get( &db, @@ -386,6 +409,8 @@ mod tests { (Some(30.0), Some(false)) ); assert_eq!(pb["rank"], 1); + assert_eq!(pb["tier"], 3); + assert_eq!(pb["world_record_time"], 30.0); let found = get(&db, "/v1/players?q=alic").await; assert_eq!(found["players"][0]["steamid64"], ALICE); diff --git a/api/crates/api/src/main.rs b/api/crates/api/src/main.rs index 0d66454..7a069bf 100644 --- a/api/crates/api/src/main.rs +++ b/api/crates/api/src/main.rs @@ -477,6 +477,8 @@ async fn shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.ok(); }; + // SIGTERM exists only on Unix; elsewhere (a contributor's Windows machine) Ctrl+C is the only way to stop. + #[cfg(unix)] let terminate = async { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) @@ -484,6 +486,8 @@ async fn shutdown_signal() { sig.recv().await; } }; + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); tokio::select! { () = ctrl_c => {}, () = terminate => {}, diff --git a/api/crates/api/src/maps/detail.rs b/api/crates/api/src/maps/detail.rs index 9b638ae..6e3f3ae 100644 --- a/api/crates/api/src/maps/detail.rs +++ b/api/crates/api/src/maps/detail.rs @@ -178,8 +178,7 @@ async fn tracks( pb.track, pb.style, pb.time, pb.run_id, r.finished_at, count(*) OVER (PARTITION BY pb.track, pb.style) AS "players!", p.steamid64::text AS "steamid64!", p.name, p.avatar_url, p.country_code, - (SELECT tier FROM map_tiers WHERE map_id = pb.map_id AND track = pb.track - ORDER BY assigned_at DESC LIMIT 1) AS tier + (SELECT tier FROM current_map_tiers WHERE map_id = pb.map_id AND track = pb.track) AS tier FROM personal_bests pb JOIN runs r ON r.id = pb.run_id JOIN players p ON p.steamid64 = pb.player_steamid64 diff --git a/api/crates/api/src/maps/list.rs b/api/crates/api/src/maps/list.rs index ad52592..beb6771 100644 --- a/api/crates/api/src/maps/list.rs +++ b/api/crates/api/src/maps/list.rs @@ -24,9 +24,9 @@ const MAX_LIMIT: i64 = 100; #[derive(Debug, Deserialize, IntoParams)] pub struct MapsQuery { - /// Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - /// name comes first, then maps with a word starting with it, then other matches, each in the chosen - /// sort; near misses for a typo come last, closest first. + /// Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + /// matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + /// other map matches and record holders, each in the chosen sort; near misses come last. q: Option, /// Default `name`. #[param(inline)] @@ -114,7 +114,7 @@ pub struct MapList { pub stats: MapStats, } -/// The whole list at a glance, whatever the search or filter. +/// Global totals and tier-scoped newest and weekly lists. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct MapStats { /// Maps with at least one run. @@ -122,6 +122,8 @@ pub struct MapStats { /// Of those, the maps whose main track has each tier, tier 1 first. Empty until a tier count is /// published. pub by_tier: Vec, + /// The tier the newest and weekly lists describe; None describes all tiers. Totals remain global. + pub tier: Option, /// The maps that joined the list last, newest first. pub newest: Vec, /// The maps the most players finished a run on in the last 7 days, most first. @@ -191,6 +193,12 @@ pub async fn list_maps( let sort = query.sort.unwrap_or(MapSort::Name).key(); let search = query.q.as_deref().and_then(search_name); let pattern = search.as_deref().map(name_search::contains_pattern); + let holder_pattern = query + .q + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + .map(name_search::contains_pattern); // Most map names start with "bhop_", which would make every map a near miss of every search. let near = search .as_deref() @@ -203,6 +211,7 @@ pub async fn list_maps( }; let filter = Filter { pattern: pattern.as_deref(), + holder_pattern: holder_pattern.as_deref(), near, style: style.as_deref(), completed_by: query.completed.and(player).map(SteamId64::get), @@ -218,7 +227,7 @@ pub async fn list_maps( tx.commit().await?; let tier_count = tiers::tier_count(&state.db).await?; - let list_stats = map_stats(&state.db, tier_count).await?; + let list_stats = map_stats(&state.db, tier_count, query.tier).await?; let (player, completed) = match player { Some(player) => ( known_player(&state.db, player).await?, @@ -244,11 +253,14 @@ pub async fn list_maps( /// Maps with a run, how many hold each main-track tier once tiers are in force, the newest of them and the /// week's most played. -async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result { +async fn map_stats( + db: &sqlx::PgPool, + tier_count: Option, + tier: Option, +) -> Result { let rows = sqlx::query!( r#"SELECT tier.tier AS "tier?", count(*) AS "maps!" FROM maps m - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1) tier ON true + LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0 WHERE m.last_run_at IS NOT NULL GROUP BY tier.tier"# ) @@ -266,11 +278,13 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result) -> Result now() - interval '7 days' GROUP BY map_id) week JOIN maps m ON m.id = week.map_id + WHERE $2::smallint IS NULL OR $2 = + (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) ORDER BY week.players DESC, m.name LIMIT $1"#, - PLAYED_THIS_WEEK + PLAYED_THIS_WEEK, + tier ) .fetch_all(db) .await? @@ -306,6 +322,7 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result 0 THEN 1 - WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 ELSE 3 END, - CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' THEN word_similarity($7, m.name) END DESC NULLS LAST, + WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 + WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END, + CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' AND $7 <% m.name + THEN word_similarity($7, m.name) END DESC NULLS LAST, CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC, CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST, CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END, @@ -395,8 +419,7 @@ async fn listed_page( m.name ) AS position FROM maps m - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1) tier ON true + LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0 -- Every map's record, read only for the sorts that need it: the page below reads the page's own. LEFT JOIN LATERAL ( SELECT pb.time, r.finished_at @@ -405,7 +428,8 @@ async fn listed_page( ORDER BY pb.time, r.finished_at LIMIT 1 ) record ON true - WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' OR $7 <% m.name) + WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' + OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps)) AND ($8::bigint IS NULL OR $9 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0)) AND ($10::smallint IS NULL OR tier.tier = $10) @@ -442,7 +466,8 @@ async fn listed_page( filter.near, filter.completed_by, filter.completed, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_all(tx) .await @@ -499,6 +524,8 @@ impl ListedMap { struct Filter<'a> { /// The search as an `ILIKE` pattern. pattern: Option<&'a str>, + /// The original search, preserving spaces in player names. + holder_pattern: Option<&'a str>, /// The search's term for near misses. near: Option<&'a str>, style: Option<&'a str>, @@ -513,17 +540,19 @@ struct Filter<'a> { async fn count_maps(tx: &mut sqlx::PgConnection, filter: &Filter<'_>) -> Result { sqlx::query_scalar!( r#"SELECT count(*) AS "count!" FROM maps m - WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name) + WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name + OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64 + WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\')) AND ($3::bigint IS NULL OR $4 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0)) - AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1))"#, + AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))"#, filter.pattern, filter.near, filter.completed_by, filter.completed, filter.style, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_one(tx) .await @@ -628,6 +657,73 @@ mod tests { ); } + #[sqlx::test] + async fn searches_current_main_track_record_holders_in_the_selected_style(db: PgPool) { + let key = setup(&db).await; + sqlx::query( + r#"INSERT INTO rulesets (version, document) + SELECT 2, jsonb_set(document, '{styles}', + (document->'styles') || '[{"key":"sw","name":"Sideways","settings":{}}]'::jsonb) + FROM rulesets WHERE version = 1"#, + ) + .execute(&db) + .await + .unwrap(); + for (id, map, player, name, time, style, track) in [ + ( + "holder-main", + "bhop_badges", + 0, + "Speed Runner", + 30.0, + "normal", + 0, + ), + ( + "holder-second", + "bhop_arcane", + 0, + "Speed Runner", + 15.0, + "normal", + 0, + ), + ("slower", "bhop_badges", 1, "Bonus Hero", 40.0, "normal", 0), + ("bonus", "bhop_badges", 1, "Bonus Hero", 10.0, "normal", 1), + ("sideways", "bhop_badges", 1, "Bonus Hero", 20.0, "sw", 0), + ("tied", "bhop_badges", 2, "Co Holder", 30.0, "normal", 0), + ] { + let mut body = run(id, time); + body["map"] = json!(map); + body["player"] = json!({ + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), + "name": name, + }); + body["style"] = json!(style); + body["track"] = json!(track); + body["ruleset_version"] = json!(2); + assert_eq!( + test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status, + 201 + ); + } + let page: MapList = test_client::get(&db, "/v1/maps?q=SPEED%20RUNNER&limit=1&offset=1") + .await + .json(); + assert_eq!(page.total, 2); + assert_eq!(page.maps.len(), 1); + assert_eq!(page.maps[0].name, "bhop_badges"); + assert_eq!(names(&db, "/v1/maps?q=Co%20Holder").await, ["bhop_badges"]); + assert_eq!(names(&db, "/v1/maps?q=Bonus%20Hero").await.len(), 0); + assert_eq!( + names(&db, "/v1/maps?q=Bonus%20Hero&style=sw").await, + ["bhop_badges"] + ); + assert_eq!(names(&db, "/v1/maps?q=%25").await.len(), 0); + } + /// `bhop_badges`' stored player count, and the count its personal bests give. async fn badges_players(db: &PgPool) -> (i32, i64) { sqlx::query_as( @@ -719,6 +815,79 @@ mod tests { assert_eq!(week, [("bhop_badges", 2), ("bhop_arcane", 1)]); } + #[sqlx::test] + async fn stats_rank_within_a_tier_before_taking_the_top_five(db: PgPool) { + let key = setup(&db).await; + let policy = crate::policies::Policy::Tiers(crate::policies::TiersPolicy { count: 2 }); + crate::policies::publish(&mut db.acquire().await.unwrap(), &policy) + .await + .unwrap(); + for index in 0..12 { + let name = format!("bhop_tier_{index:02}"); + let players = if index < 5 { 2 } else { 1 }; + for player in 0..players { + let mut body = run(&format!("tier-{index}-{player}"), 30.0); + body["map"] = json!(name); + body["player"] = json!({ + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), + "name": format!("player-{player}"), + }); + assert_eq!( + test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status, + 201 + ); + } + let map = crate::maps::MapName::try_from(name.clone()).unwrap(); + crate::staff::maps::set_tier(&db, None, &map, 0, if index < 5 { 1 } else { 2 }) + .await + .unwrap(); + sqlx::query( + "UPDATE maps SET listed_at = now() - $1 * interval '1 minute' WHERE name = $2", + ) + .bind(f64::from(index)) + .bind(name) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("UPDATE runs SET finished_at = now() - interval '1 day'") + .execute(&db) + .await + .unwrap(); + + let all: MapList = test_client::get(&db, "/v1/maps").await.json(); + assert_eq!(all.stats.tier, None); + assert!( + all.stats + .played_this_week + .iter() + .all(|map| map.tier == Some(1)) + ); + assert!(all.stats.newest.iter().all(|map| map.tier == Some(1))); + + let filtered: MapList = test_client::get(&db, "/v1/maps?tier=2").await.json(); + let expected: Vec<_> = (5..10) + .map(|index| format!("bhop_tier_{index:02}")) + .collect(); + assert_eq!(filtered.stats.tier, Some(2)); + assert_eq!( + (filtered.stats.maps, filtered.stats.by_tier), + (12, vec![5, 7]) + ); + assert_eq!(filtered.stats.played_this_week.len(), 5); + assert_eq!(filtered.stats.newest.len(), 5); + for (index, map) in filtered.stats.played_this_week.iter().enumerate() { + assert_eq!(map.name, expected[index]); + assert_eq!((map.tier, map.players), (Some(2), 1)); + } + for (index, map) in filtered.stats.newest.iter().enumerate() { + assert_eq!(map.name, expected[index]); + assert_eq!(map.tier, Some(2)); + } + } + #[sqlx::test] async fn sorts_by_record_and_filters_by_completion(db: PgPool) { let key = setup(&db).await; diff --git a/api/crates/api/src/players.rs b/api/crates/api/src/players.rs index 90af67c..72cd93f 100644 --- a/api/crates/api/src/players.rs +++ b/api/crates/api/src/players.rs @@ -1,5 +1,6 @@ //! Players, identified by SteamID64. +mod avatar; pub mod countries; mod details; mod list; @@ -23,6 +24,7 @@ pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(list::list_players)) .routes(routes!(profile::player_profile)) + .routes(routes!(avatar::player_avatar)) .routes(routes!(personal_bests::player_personal_bests)) .routes(routes!(details::update_player_details)) .routes(routes!(countries::list_countries)) @@ -162,6 +164,31 @@ pub async fn record_name( Ok(()) } +/// Makes `code`, found by a game server from the player's address, their country, replacing one they picked or +/// Steam's (the order is in `docs/site-api.md`). Only from their latest run, as for names: `record_name` has +/// already moved `name_seen_at` to the newest time a server saw them, so a run sent late from a queue can't roll +/// the country back. +pub async fn record_server_country( + conn: &mut PgConnection, + steamid64: SteamId64, + code: &str, + finished_at: DateTime, +) -> Result<(), sqlx::Error> { + sqlx::query!( + r#" + UPDATE players SET country_code = $2, country_from_server = true, country_chosen = false + WHERE steamid64 = $1 AND name_seen_at <= $3 + AND (country_code IS DISTINCT FROM $2 OR NOT country_from_server) + "#, + steamid64.get(), + code, + finished_at + ) + .execute(conn) + .await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::SteamId64; diff --git a/api/crates/api/src/players/avatar.rs b/api/crates/api/src/players/avatar.rs new file mode 100644 index 0000000..f746f08 --- /dev/null +++ b/api/crates/api/src/players/avatar.rs @@ -0,0 +1,369 @@ +//! A player's picture, `GET /v1/players/{player}/avatar`: a redirect to their Steam avatar, fetched on the spot +//! when we have none yet, or a lettered placeholder. Pages point `` here for players whose `avatar_url` is +//! empty, so everyone shown gets a picture without having signed in or opened their profile. + +use axum::{ + extract::{Path, State}, + http::{StatusCode, header}, + response::{IntoResponse, Response}, +}; +use url::Url; + +use super::{SteamId64, steam_profile}; +use crate::{ + app::AppState, + error::{ApiError, ErrorBody}, +}; + +/// Steam avatar URLs don't change for the same picture, so a day in caches costs nothing. +const AVATAR_CACHE: &str = "public, max-age=86400"; +/// Short, so the real picture replaces the placeholder soon after a background refresh finds it. +const PLACEHOLDER_CACHE: &str = "public, max-age=300"; + +/// Redirects to the player's Steam avatar. Takes a `SteamID64`, `SteamID2` or `SteamID3`. Only players +/// SourceJump knows are looked up on Steam; a player known only from the old site gets the avatar it had. +#[utoipa::path( + get, + path = "/v1/players/{player}/avatar", + tag = "players", + params(("player" = String, Path, description = "SteamID64, SteamID2 (STEAM_0:1:2) or SteamID3 ([U:1:4])")), + responses( + (status = FOUND, description = "To the avatar on Steam's CDN; cached a day", + headers(("Location" = String, description = "The avatar's URL"))), + (status = OK, description = "No avatar yet: a placeholder with the player's initials, cached five minutes", + content_type = "image/svg+xml", body = String), + (status = NOT_FOUND, description = "SourceJump has no such player", body = ErrorBody), + (status = UNPROCESSABLE_ENTITY, description = "Not a SteamID", body = ErrorBody), + ), +)] +pub async fn player_avatar( + State(state): State, + Path(player): Path, +) -> Result { + let steamid64 = SteamId64::parse_any(&player) + .ok_or_else(|| ApiError::Invalid(format!("{player:?} is not a SteamID")))?; + + let player = sqlx::query!( + "SELECT name, avatar_url, steam_profile_fetched_at FROM players WHERE steamid64 = $1", + steamid64.get() + ) + .fetch_optional(&state.db) + .await?; + let Some(player) = player else { + // Never fetched: with no `players` row there is nowhere to store the profile or a failure, so every + // request would ask Steam again. Making a row here would turn their legacy profile into a 2.0 one. + let legacy = sqlx::query!( + "SELECT name, avatar_url FROM legacy_players WHERE steamid64 = $1", + steamid64.get() + ) + .fetch_optional(&state.db) + .await? + .ok_or(ApiError::NotFound("SourceJump has no such player"))?; + return Ok(picture(legacy.avatar_url.as_deref(), &legacy.name)); + }; + + if player.avatar_url.is_some() || steam_profile::is_fresh(player.steam_profile_fetched_at) { + // The picture we have, or a placeholder while Steam recently had none or failed (`RETRY_AFTER`). + steam_profile::refresh_if_stale( + state.db.clone(), + state.steam.clone(), + steamid64, + player.steam_profile_fetched_at, + ); + return Ok(picture(player.avatar_url.as_deref(), &player.name)); + } + if !steam_profile::refresh_now(&state.db, &state.steam, steamid64).await? { + // Every slot is busy: the placeholder now, and the paced queue fetches it for the next request. + steam_profile::refresh_if_stale( + state.db.clone(), + state.steam.clone(), + steamid64, + player.steam_profile_fetched_at, + ); + return Ok(picture(None, &player.name)); + } + let stored = sqlx::query!( + "SELECT name, avatar_url FROM players WHERE steamid64 = $1", + steamid64.get() + ) + .fetch_one(&state.db) + .await?; + Ok(picture(stored.avatar_url.as_deref(), &stored.name)) +} + +/// A redirect to `avatar_url` if it's on Steam's CDN, else the placeholder. +fn picture(avatar_url: Option<&str>, name: &str) -> Response { + match avatar_url.and_then(steam_cdn_url) { + Some(url) => ( + StatusCode::FOUND, + [ + (header::LOCATION, url.to_string()), + (header::CACHE_CONTROL, AVATAR_CACHE.to_owned()), + ], + ) + .into_response(), + None => ( + [ + (header::CONTENT_TYPE, "image/svg+xml"), + (header::CACHE_CONTROL, PLACEHOLDER_CACHE), + ], + placeholder(name), + ) + .into_response(), + } +} + +/// The URL, if it's an `https` address on Steam's avatar CDN. Stored URLs come from Steam's XML, which has no +/// contract, and from the old site's data; checking keeps this route from redirecting anywhere else. +fn steam_cdn_url(text: &str) -> Option { + let url = Url::parse(text).ok()?; + let host = url.host_str()?; + let on_cdn = host == "steamcdn-a.akamaihd.net" + || host == "steamstatic.com" + || host.ends_with(".steamstatic.com"); + let plain = url.username().is_empty() && url.password().is_none() && url.port().is_none(); + (url.scheme() == "https" && on_cdn && plain).then_some(url) +} + +/// A square with the player's initials, in the site's raised-surface and muted-text colours (`web/src/ui/tokens.css`), +/// matching the web's `Avatar` fallback. +fn placeholder(name: &str) -> String { + format!( + r##"{}"##, + initials(name) + ) +} + +/// The first letter or digit of the first two words, as the web's `Avatar` does: "strafe cat" is "SC". Letters +/// and digits only, so the player's name can't put markup in the SVG. +fn initials(name: &str) -> String { + let letters: String = name + .split(|c: char| c.is_whitespace() || matches!(c, '_' | '.' | '-')) + .filter_map(|word| word.chars().find(|c| c.is_alphanumeric())) + .take(2) + .flat_map(char::to_uppercase) + .collect(); + if letters.is_empty() { + "?".to_owned() + } else { + letters + } +} + +#[cfg(test)] +mod tests { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + + use axum::{body::Body, http::Request}; + use sqlx::PgPool; + + use super::*; + use crate::{ + players::steam_profile::tests::stand_in_steam, + test_client::{self, TestResponse}, + }; + + const PLAYER: &str = "76561197960287930"; + const AVATAR: &str = "https://avatars.steamstatic.com/abc_full.jpg"; + const PROFILE: &str = r" + "; + + async fn add_player(db: &PgPool, avatar_url: Option<&str>, fetched_hours_ago: Option) { + sqlx::query( + "INSERT INTO players (steamid64, name, name_seen_at, avatar_url, steam_profile_fetched_at) + VALUES ($1, 'strafe cat', now(), $2, now() - make_interval(hours => $3::int))", + ) + .bind(SteamId64::parse_any(PLAYER).unwrap().get()) + .bind(avatar_url) + .bind(fetched_hours_ago.map(|hours| i32::try_from(hours).unwrap())) + .execute(db) + .await + .unwrap(); + } + + async fn avatar(state: &AppState, player: &str) -> TestResponse { + let request = Request::get(format!("/v1/players/{player}/avatar")) + .body(Body::empty()) + .unwrap(); + test_client::send_to(state.clone(), request).await + } + + fn with_steam(db: &PgPool, steam: crate::steam::Steam) -> AppState { + AppState { + steam, + ..AppState::for_tests(db.clone()) + } + } + + fn assert_placeholder(response: &TestResponse) { + assert_eq!(response.status, 200); + assert_eq!(response.headers[header::CONTENT_TYPE], "image/svg+xml"); + assert_eq!(response.headers[header::CACHE_CONTROL], PLACEHOLDER_CACHE); + assert!(String::from_utf8_lossy(&response.body).contains(">SC")); + } + + #[sqlx::test] + async fn a_fresh_avatar_is_a_redirect(db: PgPool) { + add_player(&db, Some(AVATAR), Some(1)).await; + let (steam, requests) = stand_in_steam(StatusCode::OK, PROFILE).await; + + let response = avatar(&with_steam(&db, steam), "[U:1:22202]").await; + assert_eq!(response.status, 302); + assert_eq!(response.headers[header::LOCATION], AVATAR); + assert_eq!(response.headers[header::CACHE_CONTROL], AVATAR_CACHE); + assert_eq!( + requests.load(Ordering::SeqCst), + 0, + "fresh: Steam isn't asked" + ); + } + + #[sqlx::test] + async fn an_unknown_player_is_never_looked_up(db: PgPool) { + let (steam, requests) = stand_in_steam(StatusCode::OK, PROFILE).await; + + let response = avatar(&with_steam(&db, steam), PLAYER).await; + assert_eq!(response.status, 404); + assert_eq!(requests.load(Ordering::SeqCst), 0); + assert_eq!(avatar(&AppState::for_tests(db), "nova").await.status, 422); + } + + #[sqlx::test] + async fn a_missing_avatar_is_fetched_and_stored(db: PgPool) { + add_player(&db, None, None).await; + let (steam, requests) = stand_in_steam(StatusCode::OK, PROFILE).await; + + let response = avatar(&with_steam(&db, steam), PLAYER).await; + assert_eq!(response.status, 302); + assert_eq!(response.headers[header::LOCATION], AVATAR); + assert_eq!(requests.load(Ordering::SeqCst), 1); + let stored: Option = + sqlx::query_scalar("SELECT avatar_url FROM players WHERE steamid64 = $1") + .bind(SteamId64::parse_any(PLAYER).unwrap().get()) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored.as_deref(), Some(AVATAR)); + } + + #[sqlx::test] + async fn a_failed_fetch_shows_the_placeholder_and_waits(db: PgPool) { + add_player(&db, None, None).await; + let (steam, requests) = stand_in_steam(StatusCode::SERVICE_UNAVAILABLE, "busy").await; + let state = with_steam(&db, steam); + + assert_placeholder(&avatar(&state, PLAYER).await); + assert_placeholder(&avatar(&state, PLAYER).await); + assert_eq!( + requests.load(Ordering::SeqCst), + 1, + "no second fetch within the hour" + ); + } + + #[sqlx::test] + async fn a_stored_url_off_steams_cdn_is_never_followed(db: PgPool) { + // The column only insists on https, so a bad import could hold any host. + add_player(&db, Some("https://example.com/a.jpg"), Some(1)).await; + + assert_placeholder(&avatar(&AppState::for_tests(db), PLAYER).await); + } + + #[sqlx::test] + async fn a_legacy_player_gets_the_old_sites_avatar(db: PgPool) { + sqlx::query( + "INSERT INTO legacy_players (steamid64, name, avatar_url) VALUES ($1, 'strafe cat', $2)", + ) + .bind(SteamId64::parse_any(PLAYER).unwrap().get()) + .bind(AVATAR) + .execute(&db) + .await + .unwrap(); + + let response = avatar(&AppState::for_tests(db), PLAYER).await; + assert_eq!(response.status, 302); + assert_eq!(response.headers[header::LOCATION], AVATAR); + } + + #[sqlx::test] + async fn a_page_of_new_players_fills_in_without_flooding_steam(db: PgPool) { + // A slow stand-in Steam that remembers the most requests it had at once. + let (in_flight, peak) = (Arc::::default(), Arc::::default()); + let (now, most) = (in_flight.clone(), peak.clone()); + let app = axum::Router::new().route( + "/profiles/{id}/", + axum::routing::get(move || async move { + most.fetch_max(now.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + now.fetch_sub(1, Ordering::SeqCst); + PROFILE + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let steam = + crate::steam::Steam::with_base(&Url::parse(&format!("http://{address}/")).unwrap()); + let state = with_steam(&db, steam); + + let mut pictures = tokio::task::JoinSet::new(); + for account in 1..=12 { + let player = SteamId64::parse_any(&format!("[U:1:{account}]")).unwrap(); + sqlx::query( + "INSERT INTO players (steamid64, name, name_seen_at) VALUES ($1, 'nova', now())", + ) + .bind(player.get()) + .execute(&db) + .await + .unwrap(); + let state = state.clone(); + pictures.spawn(async move { avatar(&state, &player.to_string()).await.status }); + } + while let Some(status) = pictures.join_next().await { + assert_eq!( + status.unwrap(), + 302, + "every picture fills in on the first load" + ); + } + let peak = peak.load(Ordering::SeqCst); + assert!( + (1..=steam_profile::INLINE_FETCHES).contains(&peak), + "at most 4 at once: {peak}" + ); + } + + #[test] + fn only_steams_cdn_over_https() { + for allowed in [ + AVATAR, + "https://avatars.akamai.steamstatic.com/a_full.jpg", + "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/a.jpg", + ] { + assert!(steam_cdn_url(allowed).is_some(), "{allowed}"); + } + for refused in [ + "http://avatars.steamstatic.com/a.jpg", + "https://evilsteamstatic.com/a.jpg", + "https://avatars.steamstatic.com.evil.net/a.jpg", + "https://x@avatars.steamstatic.com/a.jpg", + "https://avatars.steamstatic.com:8443/a.jpg", + "javascript:alert(1)", + "", + ] { + assert!(steam_cdn_url(refused).is_none(), "{refused}"); + } + } + + #[test] + fn initials_are_letters_and_digits_only() { + assert_eq!(initials("strafe cat"), "SC"); + assert_eq!(initials("nova"), "N"); + assert_eq!(initials("[SJ] x"), "SB"); + assert_eq!(initials("<>&\"'"), "?"); + assert_eq!(initials(""), "?"); + } +} diff --git a/api/crates/api/src/players/details.rs b/api/crates/api/src/players/details.rs index 56deff8..a793d37 100644 --- a/api/crates/api/src/players/details.rs +++ b/api/crates/api/src/players/details.rs @@ -1,5 +1,5 @@ //! What players say about themselves on their profile, `PUT /v1/players/{player}/details`: their setup (mouse, -//! DPI, sensitivity, mouse pad, keyboard, monitor, aspect ratio) and a country to show instead of Steam's. +//! DPI, sensitivity, mouse pad, keyboard, monitor, aspect ratio) and a country to show (order: `docs/site-api.md`). //! //! Anyone can type anything here, so every field is checked once, at this boundary: short single lines of //! text with no links or invisible characters, numbers in a sensible range, a ratio from a fixed list and a @@ -216,7 +216,8 @@ pub struct DetailsInput { pub monitor: Option, #[serde(default)] pub aspect: Option, - /// An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's. + /// An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one; + /// null to stop showing the player's pick. #[serde(default)] pub country_code: Option, /// Required when staff change someone else's details: why, for the staff log. @@ -346,12 +347,13 @@ async fn store( ) .execute(&mut *tx) .await?; - // Going back to Steam's country clears ours and marks the Steam profile stale, so the next view of the - // profile fetches it again. + // A pick replaces a game server's country. Dropping a pick clears it and marks the Steam profile stale, so + // the next view of the profile fetches Steam's again; dropping a pick the player doesn't have changes nothing. sqlx::query!( r#" UPDATE players SET country_chosen = $2::text IS NOT NULL, + country_from_server = country_from_server AND $2::text IS NULL, country_code = CASE WHEN $2::text IS NOT NULL THEN $2 WHEN country_chosen THEN NULL ELSE country_code END, steam_profile_fetched_at = CASE WHEN $2::text IS NULL AND country_chosen THEN NULL @@ -539,6 +541,37 @@ mod tests { ); } + #[sqlx::test] + async fn a_pick_replaces_a_servers_country_and_saving_without_one_keeps_it(db: PgPool) { + let token = player(&db, GABE, &[]).await; + sqlx::query("UPDATE players SET country_code = 'SE', country_from_server = true") + .execute(&db) + .await + .unwrap(); + let country = || async { + sqlx::query_as::<_, (Option, bool, bool)>( + "SELECT country_code, country_from_server, country_chosen FROM players", + ) + .fetch_one(&db) + .await + .unwrap() + }; + + assert_eq!( + save(&db, &token, GABE, json!({ "dpi": 800 })).await.status, + 204 + ); + assert_eq!(country().await, (Some("SE".into()), true, false)); + + sqlx::query("UPDATE player_details SET updated_at = now() - interval '1 minute'") + .execute(&db) + .await + .unwrap(); + let body = json!({ "country_code": "fi" }); + assert_eq!(save(&db, &token, GABE, body).await.status, 204); + assert_eq!(country().await, (Some("FI".into()), false, true)); + } + #[sqlx::test] async fn bad_values_are_refused(db: PgPool) { let token = player(&db, GABE, &[]).await; diff --git a/api/crates/api/src/players/personal_bests.rs b/api/crates/api/src/players/personal_bests.rs index 5fc38aa..1f19bed 100644 --- a/api/crates/api/src/players/personal_bests.rs +++ b/api/crates/api/src/players/personal_bests.rs @@ -16,6 +16,7 @@ use crate::{ app::AppState, error::{ApiError, ErrorBody}, legacy::{self, View}, + maps::tiers, }; pub const DEFAULT_LIMIT: i64 = 50; @@ -66,8 +67,14 @@ pub struct PersonalBest { pub map: String, /// 0 is the main track, 1 and up are bonuses. pub track: i16, + /// The board's tier. None while tiers aren't in force or staff haven't set this board's, and for a legacy + /// run. + pub tier: Option, /// Seconds. pub time: f64, + /// The board's 2.0 record time, as on its map leaderboard, so a client can show the gap to it. None for a + /// legacy run. + pub world_record_time: Option, /// Placement on the map's 2.0 leaderboard for this style and track. Equal times share a placement. None /// for a legacy run, which has no 2.0 placement. pub rank: Option, @@ -99,13 +106,14 @@ pub(super) struct Selection<'a> { } /// The player's personal bests with placements, as `selection` asks; `after` continues after a position, and -/// `limit` caps the count (None for all of them). +/// `limit` caps the count (None for all of them). `tiers_in_force` is whether a tier count is published. pub(super) async fn personal_bests( db: &PgPool, steamid64: SteamId64, selection: Selection<'_>, after: Option<&Position>, limit: Option, + tiers_in_force: bool, ) -> Result, sqlx::Error> { let (after_map, after_time) = match after { Some(Position::ByMap(map, track)) => (Some((map.as_str(), *track)), None), @@ -114,14 +122,18 @@ pub(super) async fn personal_bests( }; // The player's own rows are picked and paged first; each one's placement is then one more than the // personal bests faster than it on its board, an index range on `personal_bests_board`. Ranking whole - // boards and keeping the player's rows read every board they're on. + // boards and keeping the player's rows read every board they're on. Record times and tiers too are + // looked up for the page's rows alone. let rows = sqlx::query!( r#" SELECT own.style AS "style!", own.map AS "map!", own.track AS "track!", own.time AS "time!", 1 + (SELECT count(*) FROM personal_bests faster WHERE faster.map_id = own.map_id AND faster.style = own.style AND faster.track = own.track AND faster.time < own.time) AS "rank!", - own.run_id AS "run_id!", own.finished_at AS "finished_at!" + (SELECT min(best.time) FROM personal_bests best + WHERE best.map_id = own.map_id AND best.style = own.style + AND best.track = own.track) AS "world_record_time!", + own.run_id AS "run_id!", own.finished_at AS "finished_at!", tier.tier AS "tier?" FROM ( SELECT pb.style, pb.map_id, m.name AS map, pb.track, pb.time, pb.run_id, pb.finished_at FROM personal_bests pb @@ -139,6 +151,7 @@ pub(super) async fn personal_bests( pb.style, m.name, pb.track LIMIT $5 ) own + LEFT JOIN current_map_tiers tier ON $11 AND tier.map_id = own.map_id AND tier.track = own.track ORDER BY CASE WHEN $8 THEN own.finished_at END DESC, CASE WHEN $8 THEN own.run_id END DESC, own.style, own.map, own.track "#, @@ -151,7 +164,8 @@ pub(super) async fn personal_bests( selection.records_only, selection.recent_first, after_time.map(|(finished_at, _)| finished_at), - after_time.map(|(_, run_id)| run_id) + after_time.map(|(_, run_id)| run_id), + tiers_in_force ) .fetch_all(db) .await?; @@ -162,7 +176,9 @@ pub(super) async fn personal_bests( style: row.style, map: row.map, track: row.track, + tier: row.tier, time: row.time, + world_record_time: Some(row.world_record_time), rank: Some(row.rank), legacy: false, run_id: row.run_id, @@ -174,13 +190,14 @@ pub(super) async fn personal_bests( /// The player's main-track personal bests in the legacy board's style for the "2.0 + pre-2.0" or "Pre-2.0" /// view, sorted by map. With both, each map shows the faster of their 2.0 and legacy runs (the 2.0 one on /// equal times). A player banned from records shows no legacy runs, as on the -/// old site. +/// old site. Only the 2.0 runs can have a tier and a record time. async fn view_personal_bests( db: &PgPool, steamid64: SteamId64, view: View, after: Option<(&str, i16)>, limit: i64, + tiers_in_force: bool, ) -> Result, sqlx::Error> { let rows = sqlx::query!( r#" @@ -189,7 +206,11 @@ async fn view_personal_bests( SELECT count(*) FROM personal_bests faster WHERE faster.map_id = shown.map_id AND faster.style = $2 AND faster.track = shown.track AND faster.time < shown.time) END AS rank, - shown.legacy AS "legacy!", shown.id AS "id!", shown.finished_at + CASE WHEN NOT shown.legacy THEN ( + SELECT min(best.time) FROM personal_bests best + WHERE best.map_id = shown.map_id AND best.style = $2 AND best.track = shown.track) + END AS world_record_time, + shown.legacy AS "legacy!", shown.id AS "id!", shown.finished_at, tier.tier AS "tier?" FROM ( SELECT DISTINCT ON (both_kinds.map, both_kinds.track) both_kinds.* FROM ( @@ -208,6 +229,8 @@ async fn view_personal_bests( ORDER BY both_kinds.map, both_kinds.track, both_kinds.time, both_kinds.legacy LIMIT $7 ) shown + -- A legacy row's map_id is NULL, so it finds no tier. + LEFT JOIN current_map_tiers tier ON $8 AND tier.map_id = shown.map_id AND tier.track = shown.track ORDER BY shown.map, shown.track "#, steamid64.get(), @@ -216,7 +239,8 @@ async fn view_personal_bests( legacy::TRACK, after.map(|(map, _)| map), after.map(|(_, track)| track), - limit + limit, + tiers_in_force ) .fetch_all(db) .await?; @@ -227,7 +251,9 @@ async fn view_personal_bests( style: legacy::STYLE.to_owned(), map: row.map, track: row.track, + tier: row.tier, time: row.time, + world_record_time: row.world_record_time, rank: row.rank, legacy: row.legacy, run_id: row.id, @@ -333,6 +359,7 @@ pub async fn player_personal_bests( return Err(ApiError::NotFound("SourceJump has no such player")); } + let tiers_in_force = tiers::tier_count(&state.db).await?.is_some(); let rows = if view == View::Current { let selection = Selection { style: query.style.as_deref(), @@ -346,6 +373,7 @@ pub async fn player_personal_bests( selection, after.as_ref(), Some(limit + 1), + tiers_in_force, ) .await? } else { @@ -358,7 +386,7 @@ pub async fn player_personal_bests( } None => None, }; - view_personal_bests(&state.db, steamid64, view, after, limit + 1).await? + view_personal_bests(&state.db, steamid64, view, after, limit + 1, tiers_in_force).await? }; let (personal_bests, next_cursor) = split_page( rows, diff --git a/api/crates/api/src/players/profile.rs b/api/crates/api/src/players/profile.rs index 3dd23fa..ea97b13 100644 --- a/api/crates/api/src/players/profile.rs +++ b/api/crates/api/src/players/profile.rs @@ -20,6 +20,7 @@ use crate::{ app::AppState, error::{ApiError, ErrorBody}, leaderboards::standings, + maps::tiers, }; #[derive(Debug, Serialize, Deserialize, ToSchema)] @@ -29,9 +30,10 @@ pub struct PlayerProfile { /// The name from their latest run, or from Steam if they haven't played yet. pub name: String, pub avatar_url: Option, - /// ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one. + /// ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it + /// since, or else their Steam profile's. None if none has one. pub country_code: Option, - /// Whether the player picked `country_code` themselves, rather than it coming from Steam. + /// Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam. pub country_chosen: bool, /// Their setup, as they describe it. None when they've said nothing. pub details: Option, @@ -52,6 +54,9 @@ pub struct PlayerProfile { /// Maps they have a legacy run on, none for a player banned from records. When there are any, the /// normal style's personal bests have the "2.0 + pre-2.0" and "Pre-2.0" views. pub legacy_maps: i64, + /// Number of tiers in force; None while the community hasn't set tiers, and personal bests then have no + /// tier. + pub tier_count: Option, } #[derive(Debug, Default, Serialize, Deserialize, ToSchema)] @@ -133,6 +138,7 @@ pub async fn player_profile( let map_count = crate::maps::played_count(&state.db).await?; let legacy_maps = legacy.as_ref().map_or(0, |legacy| legacy.maps); let shown = details::shown(&mut *state.db.acquire().await?, steamid64).await?; + let tier_count = tiers::tier_count(&state.db).await?; let Some(player) = player else { // Known only from the old site: its name, avatar and country as it last had them. @@ -154,6 +160,7 @@ pub async fn player_profile( .await? .draft, legacy_maps, + tier_count, })); }; @@ -165,7 +172,7 @@ pub async fn player_profile( ); let all_styles = totals(&state.db, steamid64).await?; - let mut styles = styles_of(&state.db, steamid64).await?; + let mut styles = styles_of(&state.db, steamid64, tier_count.is_some()).await?; for standing in standings_of(&state.db, steamid64).await? { if let Some(style) = styles.iter_mut().find(|s| s.style == standing.style) { let place = Some(StyleStanding { @@ -198,6 +205,7 @@ pub async fn player_profile( all_styles, points_draft, legacy_maps, + tier_count, })) } @@ -251,6 +259,7 @@ async fn totals(db: &sqlx::PgPool, steamid64: SteamId64) -> Result Result, sqlx::Error> { let counts = sqlx::query!( r#" @@ -275,9 +284,15 @@ async fn styles_of( tracks: Some(Tracks::Main), ..Selection::default() }; - let first_page = - personal_bests::personal_bests(db, steamid64, selection, None, Some(DEFAULT_LIMIT + 1)) - .await?; + let first_page = personal_bests::personal_bests( + db, + steamid64, + selection, + None, + Some(DEFAULT_LIMIT + 1), + tiers_in_force, + ) + .await?; let (personal_bests, next_cursor) = personal_bests::split_page(first_page, page_size, false); styles.push(PlayerStyle { @@ -416,6 +431,8 @@ mod tests { .await .json(); assert_eq!(main_standing(&profile), None, "no points without tiers"); + assert_eq!(profile.tier_count, None); + assert_eq!(profile.styles[0].personal_bests[0].tier, None); staff::policies::publish_policy( &db, @@ -434,6 +451,13 @@ mod tests { .await .json(); assert_eq!(main_standing(&profile), Some(rank), "{player}"); + assert_eq!(profile.tier_count, Some(5)); + assert_eq!(profile.styles[0].personal_bests[0].tier, Some(1)); + // The record holder's own time, the faster time for the player behind. + assert_eq!( + profile.styles[0].personal_bests[0].world_record_time, + Some(20.0) + ); assert!(profile.styles[0].bonus_standing.is_none()); assert!(profile.points_draft); } diff --git a/api/crates/api/src/players/steam_profile.rs b/api/crates/api/src/players/steam_profile.rs index e4a1b35..593794e 100644 --- a/api/crates/api/src/players/steam_profile.rs +++ b/api/crates/api/src/players/steam_profile.rs @@ -22,6 +22,12 @@ const MIN_GAP: StdDuration = StdDuration::from_secs(2); /// At most this many refreshes wait their turn; more are dropped, and a later view asks again. With `MIN_GAP`, /// the last in line waits under two minutes however many profiles are viewed. const MAX_QUEUED: usize = 50; +/// Fetches a waiting page may make at once, process-wide (`refresh_now`), and how long each may take: a picture +/// that isn't there within seconds shows the placeholder instead. +pub(crate) const INLINE_FETCHES: usize = 4; +const INLINE_TIMEOUT: StdDuration = StdDuration::from_secs(4); +/// How long a page's request waits for a free slot before showing the placeholder. +const SLOT_WAIT: StdDuration = StdDuration::from_secs(4); #[derive(Debug, Default, PartialEq, Eq)] pub struct SteamProfile { @@ -97,13 +103,21 @@ fn read_field(path: &[String], text: String, profile: &mut SteamProfile) { } } +/// Waits for Steam's pacing (`MIN_GAP`), then asks for the profile. pub async fn fetch(steam: &Steam, steamid64: SteamId64) -> Result { steam.wait_for_turn(MIN_GAP).await; - let url = steam + request(steam.http.get(profile_url(steam, steamid64))).await +} + +fn profile_url(steam: &Steam, steamid64: SteamId64) -> url::Url { + steam .community .join(&format!("profiles/{steamid64}/?xml=1")) - .expect("a valid path"); - let response = steam.http.get(url).send().await.map_err(FetchError::Http)?; + .expect("a valid path") +} + +async fn request(request: reqwest::RequestBuilder) -> Result { + let response = request.send().await.map_err(FetchError::Http)?; if !response.status().is_success() { return Err(FetchError::Status(response.status().as_u16())); } @@ -113,7 +127,81 @@ pub async fn fetch(steam: &Steam, steamid64: SteamId64) -> Result Result<(), sqlx::Error> { - let profile = match fetch(steam, steamid64).await { + store(db, steamid64, fetch(steam, steamid64).await).await +} + +/// Fetches the profile now, for a page waiting on it (`players/avatar.rs`), and stores it as `refresh` does. +/// False, without asking Steam, when no `INLINE_FETCHES` slot frees up within `SLOT_WAIT`, or the player's +/// refresh is already queued or running. +/// +/// Skips `MIN_GAP`: waiting behind up to `MAX_QUEUED` paced refreshes (100 s) would leave a list of 50 +/// never-seen players without pictures. With 4 at once and Steam answering in well under a second, those 50 +/// take a few seconds. Steam still sees little: a player is fetched inline only while we have no avatar for +/// them and no fetch in the last day (an hour after a failed one), so each is asked about once, never more +/// than `INLINE_FETCHES` at a time, as ok-website does against the same pages. +pub async fn refresh_now( + db: &PgPool, + steam: &Steam, + steamid64: SteamId64, +) -> Result { + let slot = steam.inline_fetches.clone().acquire_owned(); + let Ok(Ok(slot)) = tokio::time::timeout(SLOT_WAIT, slot).await else { + return Ok(false); + }; + // No cap here, unlike `queue`: the slots bound it. Holding the player's place keeps a background refresh, + // or the same picture requested twice at once, from asking Steam a second time. + if !lock_queue(steam).insert(steamid64) { + return Ok(false); + } + let (db, steam) = (db.clone(), steam.clone()); + // Its own task, so a browser giving up on the picture can't cut this short and leave the player's place + // taken, or a failure unrecorded. The timeout is on the request, not around this, for the same reason. + tokio::spawn(async move { + let fetched = fetch_now_if_stale(&db, &steam, steamid64).await; + lock_queue(&steam).remove(&steamid64); + drop(slot); + fetched + }) + .await + .expect("the fetch doesn't panic") +} + +/// True once the stored profile is as fresh as it gets for now. A request that waited for its slot may find +/// the profile fetched meanwhile, and asks Steam only if it's still stale. +async fn fetch_now_if_stale( + db: &PgPool, + steam: &Steam, + steamid64: SteamId64, +) -> Result { + let Some(fetched_at) = sqlx::query_scalar!( + "SELECT steam_profile_fetched_at FROM players WHERE steamid64 = $1", + steamid64.get() + ) + .fetch_optional(db) + .await? + else { + return Ok(false); + }; + if !is_fresh(fetched_at) { + let url = profile_url(steam, steamid64); + let fetched = request(steam.http.get(url).timeout(INLINE_TIMEOUT)).await; + store(db, steamid64, fetched).await?; + } + Ok(true) +} + +/// Whether a profile fetched at `fetched_at` is recent enough to leave alone. A failed fetch counts as fresh +/// for `RETRY_AFTER`. +pub fn is_fresh(fetched_at: Option>) -> bool { + fetched_at.is_some_and(|fetched| Utc::now() - fetched < FRESH_FOR) +} + +async fn store( + db: &PgPool, + steamid64: SteamId64, + fetched: Result, +) -> Result<(), sqlx::Error> { + let profile = match fetched { Ok(profile) => profile, Err(error) => { tracing::warn!(%steamid64, %error, "couldn't fetch a Steam profile"); @@ -132,8 +220,8 @@ pub async fn refresh(db: &PgPool, steam: &Steam, steamid64: SteamId64) -> Result r#" UPDATE players SET avatar_url = $2, - -- A country the player picked on their profile stays. - country_code = CASE WHEN country_chosen THEN country_code ELSE $3 END, + -- Steam's country comes last: one a game server found or the player picked stays. + country_code = CASE WHEN country_chosen OR country_from_server THEN country_code ELSE $3 END, steam_profile_fetched_at = now(), name = CASE WHEN name_seen_at = '-infinity' AND $4::text IS NOT NULL THEN $4 ELSE name END WHERE steamid64 = $1 @@ -156,7 +244,7 @@ pub fn refresh_if_stale( steamid64: SteamId64, fetched_at: Option>, ) { - if fetched_at.is_some_and(|fetched| Utc::now() - fetched < FRESH_FOR) { + if is_fresh(fetched_at) { return; } if !queue(&steam, steamid64) { @@ -183,7 +271,7 @@ fn lock_queue(steam: &Steam) -> std::sync::MutexGuard<'_, std::collections::Hash } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; // Shaped like Steam's response, with invented values. @@ -220,6 +308,67 @@ mod tests { assert!(queue(&steam, first), "a finished refresh frees its place"); } + /// A stand-in for Steam that answers every profile with `PUBLIC`. + async fn fake_steam() -> Steam { + stand_in_steam(axum::http::StatusCode::OK, PUBLIC).await.0 + } + + /// A stand-in for Steam that answers every profile with `status` and `body`, and counts the requests. + pub(crate) async fn stand_in_steam( + status: axum::http::StatusCode, + body: &'static str, + ) -> (Steam, std::sync::Arc) { + let requests = std::sync::Arc::::default(); + let counted = requests.clone(); + let app = axum::Router::new().route( + "/profiles/{id}/", + axum::routing::get(move || async move { + counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + (status, body) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let steam = Steam::with_base(&url::Url::parse(&format!("http://{address}/")).unwrap()); + (steam, requests) + } + + #[sqlx::test] + async fn steams_country_comes_after_a_servers_and_the_players_own(db: PgPool) { + // Steam's own (none yet), a game server's, and the player's pick. + let players = [ + ("[U:1:1]", None, false, false, Some("NO")), + ("[U:1:2]", Some("SE"), true, false, Some("SE")), + ("[U:1:3]", Some("FI"), false, true, Some("FI")), + ]; + for (id, code, from_server, chosen, expected) in players { + let steamid64 = SteamId64::parse_any(id).unwrap(); + sqlx::query( + "INSERT INTO players (steamid64, name, name_seen_at, country_code, country_from_server, country_chosen) + VALUES ($1, 'nova', now(), $2, $3, $4)", + ) + .bind(steamid64.get()) + .bind(code) + .bind(from_server) + .bind(chosen) + .execute(&db) + .await + .unwrap(); + // A Steam each, so no refresh waits its turn behind another. + refresh(&db, &fake_steam().await, steamid64).await.unwrap(); + + let (country, avatar): (Option, Option) = + sqlx::query_as("SELECT country_code, avatar_url FROM players WHERE steamid64 = $1") + .bind(steamid64.get()) + .fetch_one(&db) + .await + .unwrap(); + assert!(avatar.is_some(), "{id}: the profile was stored"); + assert_eq!(country.as_deref(), expected, "{id}"); + } + } + #[sqlx::test] async fn a_failed_fetch_waits_before_trying_again(db: PgPool) { let steamid64 = SteamId64::parse_any("76561197960287930").unwrap(); diff --git a/api/crates/api/src/record_events/discord/post.rs b/api/crates/api/src/record_events/discord/post.rs index fb56fc9..7d66f27 100644 --- a/api/crates/api/src/record_events/discord/post.rs +++ b/api/crates/api/src/record_events/discord/post.rs @@ -133,8 +133,7 @@ async fn records( AND o.player_steamid64 = r.player_steamid64 AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id)) AS previous_personal_best, - (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier, (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key, (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h JOIN server_listings l ON l.ip = h.ip AND l.port = h.port diff --git a/api/crates/api/src/records.rs b/api/crates/api/src/records.rs index 166f0bb..f738e8f 100644 --- a/api/crates/api/src/records.rs +++ b/api/crates/api/src/records.rs @@ -1,5 +1,7 @@ //! A map's records, `GET /v1/maps/{map}/records`: the top personal bests per style and track, for the -//! plugin's in-game records display. +//! plugin's in-game records display. Connected players' own bests on the map are in `records/personal_bests.rs`. + +pub mod personal_bests; use axum::{ Json, @@ -54,9 +56,11 @@ pub struct Record { } pub fn routes() -> OpenApiRouter { - // Servers check a map's records on every map change; most of the time nothing's new. + // Servers check a map's records and their players' personal bests on every map change; most of the time + // nothing's new. OpenApiRouter::new() .routes(routes!(map_records)) + .routes(routes!(personal_bests::players_personal_bests)) .layer(axum::middleware::from_fn(crate::etag::conditional)) } diff --git a/api/crates/api/src/records/personal_bests.rs b/api/crates/api/src/records/personal_bests.rs new file mode 100644 index 0000000..88b40d4 --- /dev/null +++ b/api/crates/api/src/records/personal_bests.rs @@ -0,0 +1,243 @@ +//! Players' personal bests on one map, `GET /v1/maps/{map}/personal-bests?players=`: what a game server reads +//! on map change for everyone connected, so it skips submitting runs that aren't faster than the player's +//! SourceJump PB (`docs/domain.md`). One request covers every player, style and track, instead of one per +//! leaderboard. Keyed, unlike `…/records`: its only reader is a server deciding what to submit, which takes a key +//! anyway, and a key keeps a bulk lookup of 64 players at a time to servers we know. + +use axum::{ + Json, + extract::{Path, Query, State}, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; + +use crate::{ + app::AppState, + error::{ApiError, ErrorBody}, + maps::MapName, + players::SteamId64, + servers::keys::ServerKey, +}; + +/// A server holds at most 64 players, so one request covers everyone on it. +const MAX_PLAYERS: usize = 64; + +#[derive(Debug, Deserialize, IntoParams)] +pub struct PersonalBestsQuery { + /// Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once. + players: String, +} + +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct PlayersPersonalBests { + pub map: String, + /// Sorted by player, style and track. A player with no personal best on the map has no entries. One flat + /// list keeps it simple to read in SourcePawn. + pub personal_bests: Vec, +} + +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct PlayerPersonalBest { + /// SteamID64, as a string. + pub steamid64: String, + pub style: String, + /// 0 is the main track, 1 and up are bonuses. + pub track: i16, + /// Seconds. + pub time: f64, + /// Place on the leaderboard; equal times share a place, as in `…/records`. + pub rank: i64, + pub run_id: i64, + pub finished_at: DateTime, +} + +/// These players' SourceJump personal bests on the map, every style and track. An unknown map, or players +/// without runs on it, give an empty list. +#[utoipa::path( + get, + path = "/v1/maps/{map}/personal-bests", + tag = "maps", + params(("map" = String, Path, description = "Map name"), PersonalBestsQuery), + responses( + (status = OK, body = PlayersPersonalBests), + (status = UNAUTHORIZED, description = "Missing, unknown or revoked API key", body = ErrorBody), + (status = UNPROCESSABLE_ENTITY, description = "Not a valid map name, or `players` isn't 1 to 64 SteamID64s", body = ErrorBody), + ), + security(("server_key" = [])), +)] +pub async fn players_personal_bests( + State(state): State, + _key: ServerKey, + Path(map): Path, + Query(query): Query, +) -> Result, ApiError> { + let map = MapName::try_from(map).map_err(ApiError::Invalid)?; + let players = parse_players(&query.players).map_err(ApiError::Invalid)?; + + // A place is one more than the faster personal bests on the board, read from its index; a slow player on a + // big board counts more entries, but never more than the board holds. + let personal_bests = sqlx::query_as!( + PlayerPersonalBest, + r#" + SELECT pb.player_steamid64::text AS "steamid64!", pb.style, pb.track, pb.time, pb.run_id, + pb.finished_at, + 1 + (SELECT count(*) FROM personal_bests faster + WHERE faster.map_id = pb.map_id AND faster.style = pb.style AND faster.track = pb.track + AND faster.time < pb.time) AS "rank!" + FROM personal_bests pb + JOIN maps m ON m.id = pb.map_id + WHERE m.name = $1 AND pb.player_steamid64 = ANY($2) + ORDER BY pb.player_steamid64, pb.style, pb.track + "#, + map.as_str(), + &players + ) + .fetch_all(&state.db) + .await?; + + Ok(Json(PlayersPersonalBests { + map: map.into(), + personal_bests, + })) +} + +/// Each player named in `players`, once. +fn parse_players(players: &str) -> Result, String> { + let mut parsed = Vec::new(); + for text in players.split(',') { + let steamid64 = SteamId64::try_from(text.trim().to_owned())?.get(); + if !parsed.contains(&steamid64) { + parsed.push(steamid64); + } + // Checked as it goes, so a huge list is refused without being read to the end. + if parsed.len() > MAX_PLAYERS { + return Err(format!("players takes at most {MAX_PLAYERS} SteamID64s")); + } + } + Ok(parsed) +} + +#[cfg(test)] +mod tests { + use axum::{body::Body, http::Request}; + use serde_json::json; + use sqlx::PgPool; + + use super::{MAX_PLAYERS, PlayersPersonalBests, parse_players}; + use crate::{ + error::ErrorBody, + runs::tests::{run, setup}, + test_client::{self, TestResponse}, + }; + + async fn get(db: &PgPool, path: &str, key: Option<&str>) -> TestResponse { + let mut request = Request::get(path); + if let Some(key) = key { + request = request.header("authorization", format!("Bearer {key}")); + } + test_client::send(db, request.body(Body::empty()).unwrap()).await + } + + const GABE: &str = "76561197960287930"; + const SECOND: &str = "76561197960287931"; + const THIRD: &str = "76561197960287932"; + + #[sqlx::test] + async fn lists_each_players_bests_with_their_place(db: PgPool) { + let key = setup(&db).await; + let mut second = run("b", 29.0); + second["player"] = json!({ "steamid64": SECOND, "name": "second" }); + let mut third = run("c", 29.0); + third["player"] = json!({ "steamid64": THIRD, "name": "third" }); + let mut bonus = run("d", 50.0); + bonus["track"] = json!(1); + let mut elsewhere = run("e", 10.0); + elsewhere["map"] = json!("bhop_other"); + for body in [run("a", 30.0), second, third, bonus, elsewhere] { + let status = test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status; + assert_eq!(status, 201); + } + + let answer: PlayersPersonalBests = get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={GABE},{THIRD},{GABE}"), + Some(&key), + ) + .await + .json(); + + assert_eq!(answer.map, "bhop_badges"); + let summary: Vec<_> = answer + .personal_bests + .iter() + .map(|pb| (pb.steamid64.as_str(), pb.track, pb.time, pb.rank)) + .collect(); + // The two 29s share first place; the 30 is third. The run on another map isn't listed. + assert_eq!( + summary, + [(GABE, 0, 30.0, 3), (GABE, 1, 50.0, 1), (THIRD, 0, 29.0, 1)] + ); + } + + #[sqlx::test] + async fn an_unknown_map_or_a_player_without_runs_gives_an_empty_list(db: PgPool) { + let key = setup(&db).await; + test_client::post(&db, "/v1/runs", Some(&key), &run("a", 30.0)).await; + + for path in [ + format!("/v1/maps/bhop_none/personal-bests?players={GABE}"), + format!("/v1/maps/bhop_badges/personal-bests?players={SECOND}"), + ] { + let answer: PlayersPersonalBests = get(&db, &path, Some(&key)).await.json(); + assert!(answer.personal_bests.is_empty(), "{path}"); + } + } + + #[sqlx::test] + async fn refuses_anything_but_1_to_64_steamid64s(db: PgPool) { + let key = setup(&db).await; + let too_many = (0..=MAX_PLAYERS as u64) + .map(|n| (76_561_197_960_287_930 + n).to_string()) + .collect::>() + .join(","); + for players in ["", "STEAM_0:0:1", "76561197960287930,,", too_many.as_str()] { + let response = get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={players}"), + Some(&key), + ) + .await; + assert_eq!(response.status, 422, "{players}"); + let _: ErrorBody = response.json(); + } + assert_eq!( + get(&db, "/v1/maps/bhop_badges/personal-bests", Some(&key)) + .await + .status, + 400, + "players is required" + ); + } + + #[sqlx::test] + async fn refuses_a_request_without_a_valid_key(db: PgPool) { + setup(&db).await; + let path = format!("/v1/maps/bhop_badges/personal-bests?players={GABE}"); + for key in [None, Some("sj_not_a_key")] { + let response = get(&db, &path, key).await; + assert_eq!(response.status, 401, "{key:?}"); + let _: ErrorBody = response.json(); + } + } + + #[test] + fn repeats_count_once() { + assert_eq!( + parse_players("76561197960287930, 76561197960287930").unwrap(), + [76_561_197_960_287_930] + ); + } +} diff --git a/api/crates/api/src/runs.rs b/api/crates/api/src/runs.rs index dc2460e..93103f3 100644 --- a/api/crates/api/src/runs.rs +++ b/api/crates/api/src/runs.rs @@ -78,6 +78,13 @@ pub struct RunPlayer { #[schema(value_type = String, example = "76561197960287930")] pub steamid64: SteamId64, pub name: String, + /// The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO + /// 3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It + /// becomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored + /// anyway. Runs only: detections ignore it. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schema(example = "SE")] + pub country_code: Option, } /// SourceJump's answer to a run. A resend gets the same answer, with a fresh upload link if one applies. @@ -130,6 +137,24 @@ async fn submit_run( let stored = store(&mut tx, key, &run).await?; tx.commit().await?; + // A player is otherwise fetched from Steam only when they sign in or their profile is opened, so one who just + // plays would show initials everywhere they're listed. Their runs keep the copy fresh instead; the queue's + // spacing and cap keep this to Steam's pace however busy the servers are. + if stored.created { + let fetched_at = sqlx::query_scalar!( + "SELECT steam_profile_fetched_at FROM players WHERE steamid64 = $1", + run.player.steamid64.get() + ) + .fetch_one(&state.db) + .await?; + players::steam_profile::refresh_if_stale( + state.db.clone(), + state.steam.clone(), + run.player.steamid64, + fetched_at, + ); + } + let status = if stored.created { StatusCode::CREATED } else { @@ -206,6 +231,15 @@ async fn store( let finished_at = DateTime::from_timestamp(run.finished_at, 0).expect("checked before storing"); players::record_name(conn, run.player.steamid64, &run.player.name, finished_at).await?; + // An unknown code costs the player a flag, never their run. + if let Some(code) = run + .player + .country_code + .as_deref() + .and_then(players::countries::known_code) + { + players::record_server_country(conn, run.player.steamid64, code, finished_at).await?; + } let ban = restrictions::records_ban(conn, run.player.steamid64).await?; let map_id = maps::id_for(conn, &run.map).await?; @@ -592,6 +626,82 @@ pub(crate) mod tests { assert_eq!(submit(&db, &key, &any).await.status, 201); } + /// The run player's `country_code`, `country_from_server` and `country_chosen`. + async fn country(db: &PgPool) -> (Option, bool, bool) { + sqlx::query_as( + "SELECT country_code, country_from_server, country_chosen FROM players WHERE steamid64 = 76561197960287930", + ) + .fetch_one(db) + .await + .unwrap() + } + + fn with_country(server_run_id: &str, code: &str) -> Value { + let mut body = run(server_run_id, 30.0); + body["player"]["country_code"] = json!(code); + body + } + + #[sqlx::test] + async fn the_country_a_server_found_replaces_a_pick_and_steams(db: PgPool) { + let key = setup(&db).await; + + assert_eq!( + submit(&db, &key, &with_country("a", "se")).await.status, + 201 + ); + assert_eq!(country(&db).await, (Some("SE".into()), true, false)); + + // The player picks their own; a run without a country leaves it, the next one with a country replaces it. + sqlx::query("UPDATE players SET country_code = 'NO', country_chosen = true, country_from_server = false") + .execute(&db) + .await + .unwrap(); + assert_eq!(submit(&db, &key, &run("b", 31.0)).await.status, 201); + assert_eq!(country(&db).await, (Some("NO".into()), false, true)); + assert_eq!( + submit(&db, &key, &with_country("c", "SE")).await.status, + 201 + ); + assert_eq!(country(&db).await, (Some("SE".into()), true, false)); + + // A resend changes nothing, whatever country it carries. + assert_eq!( + submit(&db, &key, &with_country("a", "fi")).await.status, + 200 + ); + assert_eq!(country(&db).await, (Some("SE".into()), true, false)); + } + + #[sqlx::test] + async fn a_country_sourcejump_doesnt_know_is_ignored_and_the_run_stored(db: PgPool) { + let key = setup(&db).await; + + for (id, code) in [("a", "XX"), ("b", "A1"), ("c", "EU"), ("d", "Sweden")] { + assert_eq!( + submit(&db, &key, &with_country(id, code)).await.status, + 201, + "{code}" + ); + } + + assert_eq!(count(&db, "runs").await, 4); + assert_eq!(country(&db).await, (None, false, false)); + } + + #[sqlx::test] + async fn a_run_sent_late_cant_roll_the_country_back(db: PgPool) { + let key = setup(&db).await; + let mut newer = with_country("a", "SE"); + newer["finished_at"] = json!(1_792_400_100); + + submit(&db, &key, &newer).await; + submit(&db, &key, &with_country("b", "FI")).await; + + assert_eq!(count(&db, "runs").await, 2); + assert_eq!(country(&db).await, (Some("SE".into()), true, false)); + } + #[sqlx::test] async fn runs_need_a_valid_key(db: PgPool) { setup(&db).await; diff --git a/api/crates/api/src/runs/detail.rs b/api/crates/api/src/runs/detail.rs index 138ce95..ae70313 100644 --- a/api/crates/api/src/runs/detail.rs +++ b/api/crates/api/src/runs/detail.rs @@ -93,8 +93,7 @@ pub async fn run_detail( EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS "personal_best!", (SELECT min(time) FROM personal_bests WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time, - (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier, ci.id AS "image_id?", ci.key AS "image_key?", ci.focus AS "image_focus?", (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h JOIN server_listings l ON l.ip = h.ip AND l.port = h.port diff --git a/api/crates/api/src/runs/recent.rs b/api/crates/api/src/runs/recent.rs index 00d0416..13ff302 100644 --- a/api/crates/api/src/runs/recent.rs +++ b/api/crates/api/src/runs/recent.rs @@ -33,6 +33,8 @@ pub struct RecentRunsQuery { records: Option, /// 1 to 100. Default 50. limit: Option, + /// Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given. + offset: Option, /// Continue after this point: a `next_cursor` from an earlier page with the same filters. cursor: Option, } @@ -52,6 +54,8 @@ pub struct RecentRuns { pub runs: Vec, /// Pass as `cursor` for the runs before these. None at the end. pub next_cursor: Option, + /// How many runs match the filters, across all pages. + pub total: i64, /// Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier. pub tier_count: Option, } @@ -88,7 +92,7 @@ pub struct RecentRun { params(RecentRunsQuery), responses( (status = OK, body = RecentRuns), - (status = UNPROCESSABLE_ENTITY, description = "Not a valid tier, limit or cursor", body = ErrorBody), + (status = UNPROCESSABLE_ENTITY, description = "Not a valid tier, limit, offset or cursor", body = ErrorBody), ), )] pub async fn recent_runs( @@ -96,7 +100,8 @@ pub async fn recent_runs( Query(query): Query, ) -> Result, ApiError> { let limit = query.limit.unwrap_or(DEFAULT_LIMIT); - check_page(limit, 0, MAX_LIMIT).map_err(ApiError::Invalid)?; + let offset = query.offset.unwrap_or(0); + check_page(limit, offset, MAX_LIMIT).map_err(ApiError::Invalid)?; if query.min_tier.is_some_and(|tier| tier < 1) { return Err(ApiError::Invalid("min_tier must be 1 or more".to_owned())); } @@ -110,11 +115,16 @@ pub async fn recent_runs( return Ok(Json(RecentRuns { runs: Vec::new(), next_cursor: None, + total: 0, tier_count, })); } - let mut runs = page(&state.db, &query, after, limit + 1, tier_count.is_some()).await?; + let tiers_in_force = tier_count.is_some(); + let (mut runs, total) = tokio::try_join!( + page(&state.db, &query, after, limit + 1, offset, tiers_in_force), + count(&state.db, &query, tiers_in_force), + )?; let limit = usize::try_from(limit).expect("checked to be positive"); let next_cursor = (runs.len() > limit).then(|| { runs.truncate(limit); @@ -123,6 +133,7 @@ pub async fn recent_runs( Ok(Json(RecentRuns { runs, next_cursor: next_cursor.flatten(), + total, tier_count, })) } @@ -140,17 +151,49 @@ async fn position(db: &PgPool, cursor: &str) -> Result { Ok((finished_at, run_id)) } +fn track_key(query: &RecentRunsQuery) -> Option<&'static str> { + query.track.map(|track| match track { + TrackKind::Main => "main", + TrackKind::Bonus => "bonus", + }) +} + +/// Every run the filters match, ignoring `cursor`, `offset` and `limit`. The same conditions as `page`'s. +async fn count( + db: &PgPool, + query: &RecentRunsQuery, + tiers_in_force: bool, +) -> Result { + sqlx::query_scalar!( + r#" + SELECT count(*) AS "total!" + FROM runs r + LEFT JOIN current_map_tiers tier ON $5 AND tier.map_id = r.map_id AND tier.track = r.track + WHERE r.invalidated_at IS NULL + AND (NOT $4 OR r.was_record) + AND ($1::text IS NULL OR r.style = $1) + AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0)) + AND ($3::smallint IS NULL OR tier.tier >= $3) + "#, + query.style, + track_key(query), + query.min_tier, + query.records.unwrap_or(false), + tiers_in_force, + ) + .fetch_one(db) + .await +} + async fn page( db: &PgPool, query: &RecentRunsQuery, after: Option, limit: i64, + offset: i64, tiers_in_force: bool, ) -> Result, sqlx::Error> { - let track = query.track.map(|track| match track { - TrackKind::Main => "main", - TrackKind::Bonus => "bonus", - }); + let track = track_key(query); // "Before" a run means earlier on its board in WR history's order: finish time, then ID. Whether a run // was a record is the stored `was_record` (`leaderboards/world_records.rs`), which the records filter reads // through its own index. `prior`, the @@ -162,8 +205,7 @@ async fn page( SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record, tier.tier FROM runs r - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) tier ON $7 + LEFT JOIN current_map_tiers tier ON $7 AND tier.map_id = r.map_id AND tier.track = r.track WHERE r.invalidated_at IS NULL AND (NOT $4 OR r.was_record) AND ($1::text IS NULL OR r.style = $1) @@ -171,7 +213,7 @@ async fn page( AND ($3::smallint IS NULL OR tier.tier >= $3) AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint)) ORDER BY r.finished_at DESC, r.id DESC - LIMIT $8 + LIMIT $8 OFFSET $9 ) SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS "tier?", prior.best AS "best?", m.name AS map, place.placement AS "placement?", @@ -208,7 +250,8 @@ async fn page( after.map(|(finished_at, _)| finished_at), after.map(|(_, run_id)| run_id), tiers_in_force, - limit + limit, + offset ) .fetch_all(db) .await?; @@ -361,6 +404,29 @@ mod tests { assert_eq!(test_client::get(&db, "/v1/runs?cursor=x").await.status, 422); assert_eq!(test_client::get(&db, "/v1/runs?limit=0").await.status, 422); + // An offset goes straight to a page, and the total counts the whole filtered list, not the page. + let third = list(&db, "?limit=2&offset=2").await; + assert_eq!( + third, + [ + row("ricochet", "bhop_badges", 0, 28.0, Some(1), true), + row("ricochet", "bhop_badges", 0, 33.0, Some(2), false), + ] + ); + let last: RecentRuns = test_client::get(&db, "/v1/runs?limit=2&offset=4") + .await + .json(); + assert_eq!((last.runs.len(), last.total), (1, 5)); + assert_eq!(last.next_cursor, None); + let main: RecentRuns = test_client::get(&db, "/v1/runs?track=main&limit=1") + .await + .json(); + assert_eq!(main.total, 4); + assert_eq!( + test_client::get(&db, "/v1/runs?offset=-1").await.status, + 422 + ); + // An invalidated record leaves the list, and the record it had beaten is the board's best again. let run_id: i64 = sqlx::query_scalar("SELECT id FROM runs WHERE server_run_id = 'c'") .fetch_one(&db) @@ -388,7 +454,8 @@ mod tests { ] { test_client::post(&db, "/v1/runs", Some(&key), &body).await; } - assert_eq!(list(&db, "?min_tier=1").await.len(), 0); + let none: RecentRuns = test_client::get(&db, "/v1/runs?min_tier=1").await.json(); + assert_eq!((none.runs.len(), none.total), (0, 0)); assert_eq!( test_client::get(&db, "/v1/runs?min_tier=0").await.status, 422 diff --git a/api/crates/api/src/servers/activity.rs b/api/crates/api/src/servers/activity.rs index 6095e0b..3967d4c 100644 --- a/api/crates/api/src/servers/activity.rs +++ b/api/crates/api/src/servers/activity.rs @@ -1,6 +1,6 @@ //! `GET /v1/servers/activity`: players and servers online over time, across listed servers, for the chart on //! the Servers page. Up to a month is built from `server_heartbeat_log`, which keeps 30 days; a year from -//! `server_activity_daily`. +//! `server_activity_daily` and `server_activity_peaks`. use axum::{ Json, @@ -14,6 +14,16 @@ use sqlx::PgPool; use crate::{app::AppState, error::ApiError}; +/// A listed server counts as online at a moment if it beat within this long before it: the heartbeat interval +/// plus five minutes of grace, so a late or missed beat doesn't drop it from the count. Also used where +/// heartbeats keep `server_activity_peaks`, and written out in its migration (0053). +pub const ONLINE_WINDOW_MINUTES: i32 = 15; +/// How often "online at once" is sampled for a peak up to a month. Half the heartbeat interval, so every +/// regular beat is seen at least once; month (30 days) is 8640 samples, each one short index range scan. The +/// grid is anchored like the buckets, so a shorter range's samples are a subset of a longer range's, and its +/// `peak_players` can never exceed a longer one's. +const SAMPLE_MINUTES: i32 = 5; + #[derive(Debug, Clone, Copy, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ActivityRange { @@ -46,6 +56,10 @@ pub struct ActivityQuery { pub struct ServerActivity { pub range: ActivityRange, pub bucket_minutes: i32, + /// The most players online at once across listed servers over the whole range, from the start of its + /// first point up to now, the bucket in progress included: no point reads higher, and a shorter range never + /// reads higher than a longer one. + pub peak_players: i32, /// Oldest first, one per bucket, empty buckets included. The bucket still in progress is left out, so the /// last point isn't a partial count. pub points: Vec, @@ -59,6 +73,10 @@ pub struct ActivityPoint { pub servers: i32, /// The average player count of each of those servers during the bucket, summed. pub players: i32, + /// The most players online at once during the bucket, across listed servers: each server's latest + /// heartbeat count, summed at the same moment. Up to a month, sampled every 5 minutes; for a year, the + /// day's highest total at any heartbeat. + pub peak_players: i32, } /// Players and servers online over the last day, week, month or year. @@ -75,30 +93,37 @@ pub async fn server_activity( ) -> Result, ApiError> { let range = query.range.unwrap_or(ActivityRange::Day); let (bucket_minutes, count) = range.buckets(); - let points = if let ActivityRange::Year = range { - by_day(&state.db, count).await? + let (points, peak_players) = if let ActivityRange::Year = range { + let (points, peak) = by_day(&state.db, count).await?; + // The daily peaks are kept at every beat and the month at 5-minute samples, so either can read higher + // (a spike between samples, or a server since unlisted); taking both keeps the year at least the month. + let (month_minutes, month_count) = ActivityRange::Month.buckets(); + let (_, month_peak) = by_bucket(&state.db, month_minutes, month_count).await?; + (points, peak.max(month_peak)) } else { by_bucket(&state.db, bucket_minutes, count).await? }; Ok(Json(ServerActivity { range, bucket_minutes, + peak_players, points, })) } -/// Buckets of `minutes` from the heartbeat log. +/// Buckets of `minutes` from the heartbeat log, and the range's peak: samples run on through the bucket in +/// progress to the latest whole sample moment, and the peak takes those from `count` buckets' length ago. async fn by_bucket( db: &PgPool, minutes: i32, count: i32, -) -> Result, sqlx::Error> { - sqlx::query_as!( - ActivityPoint, +) -> Result<(Vec, i32), sqlx::Error> { + let rows = sqlx::query!( r#" WITH bounds AS ( SELECT make_interval(mins => $1) AS bucket, - date_bin(make_interval(mins => $1), now(), TIMESTAMPTZ '2000-01-01') AS current + date_bin(make_interval(mins => $1), now(), TIMESTAMPTZ '2000-01-01') AS current, + date_bin(make_interval(mins => $3), now(), TIMESTAMPTZ '2000-01-01') AS latest ), buckets AS ( SELECT generate_series(current - $2 * bucket, current - bucket, bucket) AS at FROM bounds ), per_server AS ( @@ -109,23 +134,72 @@ async fn by_bucket( JOIN server_listings l ON l.ip = h.ip AND l.port = h.port WHERE h.received_at >= bounds.current - $2 * bounds.bucket AND h.received_at < bounds.current GROUP BY 1, 2, 3 + ), online AS ( + SELECT m.at, sum(latest.players) AS players + FROM bounds + CROSS JOIN generate_series( + bounds.current - $2 * bounds.bucket, + bounds.latest, + make_interval(mins => $3) + ) AS m(at) + CROSS JOIN LATERAL ( + SELECT DISTINCT ON (h.ip, h.port) h.players + FROM server_heartbeat_log h + JOIN server_listings l ON l.ip = h.ip AND l.port = h.port + WHERE h.received_at > m.at - make_interval(mins => $4) AND h.received_at <= m.at + ORDER BY h.ip, h.port, h.received_at DESC + ) latest + GROUP BY m.at + ), peaks AS ( + SELECT date_bin(bounds.bucket, online.at, TIMESTAMPTZ '2000-01-01') AS at, max(online.players) AS players + FROM online CROSS JOIN bounds + GROUP BY 1 + ), whole AS ( + SELECT coalesce(max(online.players), 0)::int AS players + FROM online CROSS JOIN bounds + WHERE online.at >= bounds.current - $2 * bounds.bucket ) - SELECT b.at AS "at!", count(p.ip)::int AS "servers!", coalesce(round(sum(p.players)), 0)::int AS "players!" + SELECT b.at AS "at!", count(p.ip)::int AS "servers!", coalesce(round(sum(p.players)), 0)::int AS "players!", + coalesce(pk.players, 0)::int AS "peak_players!", whole.players AS "range_peak!" FROM buckets b + CROSS JOIN whole LEFT JOIN per_server p ON p.at = b.at - GROUP BY b.at + LEFT JOIN peaks pk ON pk.at = b.at + GROUP BY b.at, pk.players, whole.players ORDER BY b.at "#, minutes, - f64::from(count) + f64::from(count), + SAMPLE_MINUTES, + ONLINE_WINDOW_MINUTES ) .fetch_all(db) - .await + .await?; + let peak = rows.first().map_or(0, |r| r.range_peak); + let points = rows + .into_iter() + .map(|r| ActivityPoint { + at: r.at, + servers: r.servers, + players: r.players, + peak_players: r.peak_players, + }) + .collect(); + Ok((points, peak)) } -/// The last `count` whole UTC days from the daily totals; today is still in progress, so it's left out. -async fn by_day(db: &PgPool, count: i32) -> Result, sqlx::Error> { - sqlx::query_as!( +/// The last `count` whole UTC days from the daily totals and peaks; today is still in progress, so it's left +/// out. And the highest daily peak from the first of those days through today, so the range's peak is never +/// below a day the chart shows, nor misses today. +async fn by_day(db: &PgPool, count: i32) -> Result<(Vec, i32), sqlx::Error> { + let peak = sqlx::query_scalar!( + r#"SELECT coalesce(max(players), 0) AS "players!" FROM server_activity_peaks + WHERE day >= (now() AT TIME ZONE 'UTC')::date - $1::int"#, + count + ) + .fetch_one(db) + .await?; + let points = sqlx::query_as!( ActivityPoint, r#" WITH days AS ( @@ -134,17 +208,20 @@ async fn by_day(db: &PgPool, count: i32) -> Result, sqlx::Err ) SELECT days.day::timestamp AT TIME ZONE 'UTC' AS "at!", count(d.ip)::int AS "servers!", - coalesce(round(sum(d.players_sum::float8 / d.heartbeats)), 0)::int AS "players!" + coalesce(round(sum(d.players_sum::float8 / d.heartbeats)), 0)::int AS "players!", + coalesce(pk.players, 0) AS "peak_players!" FROM days LEFT JOIN server_activity_daily d ON d.day = days.day AND EXISTS (SELECT 1 FROM server_listings l WHERE l.ip = d.ip AND l.port = d.port) - GROUP BY days.day + LEFT JOIN server_activity_peaks pk ON pk.day = days.day + GROUP BY days.day, pk.players ORDER BY days.day "#, count ) .fetch_all(db) - .await + .await?; + Ok((points, peak)) } #[cfg(test)] @@ -179,6 +256,10 @@ mod tests { .execute(&db) .await .unwrap(); + sqlx::query("UPDATE server_heartbeat_log SET received_at = received_at + interval '1 minute' WHERE players = 20") + .execute(&db) + .await + .unwrap(); let activity: ServerActivity = test_client::get(&db, "/v1/servers/activity").await.json(); @@ -188,10 +269,179 @@ mod tests { .points .iter() .filter(|p| p.servers > 0) - .map(|p| (p.servers, p.players)) + .map(|p| (p.servers, p.players, p.peak_players)) .collect(); - // .1 averaged (12 + 20) / 2 = 16, .2 had 12; .3 isn't listed. - assert_eq!(busy, [(2, 28)]); + // .1 averaged (12 + 20) / 2 = 16, .2 had 12; .3 isn't listed. At once: .1's latest 20, and .2's 12. + assert_eq!(busy, [(2, 28, 32)]); + } + + /// Lists the servers, then has each send a beat of `players` at `minutes` before the start of the + /// current 8-hour bin: a finished bucket for the day, week and month, and within the last day. + async fn beats_at(db: &PgPool, beats: &[(&str, i64, i64)]) { + for (ip, players, minutes) in beats { + listing::list(db, format!("{ip}:27015").parse().unwrap(), None) + .await + .unwrap(); + let mut body = report(27015); + body["players"] = serde_json::json!(players); + beat(db, ip, None, &body).await; + sqlx::query( + "UPDATE server_heartbeat_log SET received_at = date_bin('8 hours', now(), '2000-01-01') - make_interval(mins => $1::int) + WHERE received_at > now() - interval '1 minute'", + ) + .bind(minutes) + .execute(db) + .await + .unwrap(); + } + } + + async fn activity(db: &PgPool, range: &str) -> ServerActivity { + test_client::get(db, &format!("/v1/servers/activity?range={range}")) + .await + .json() + } + + fn peak(activity: &ServerActivity) -> i32 { + activity + .points + .iter() + .map(|p| p.peak_players) + .max() + .unwrap() + } + + #[sqlx::test] + async fn the_peak_is_players_online_at_the_same_moment(db: PgPool) { + // .1 has 10, then 2; .2 joins with 6 five minutes after .1's first beat, while .1 still counts. + beats_at( + &db, + &[ + ("203.0.113.1", 10, 180), + ("203.0.113.2", 6, 175), + ("203.0.113.1", 2, 170), + ], + ) + .await; + + let day = activity(&db, "day").await; + let busy: Vec<_> = day.points.iter().filter(|p| p.servers > 0).collect(); + // One 20-minute bucket: averages (10 + 2) / 2 + 6 = 12, but 10 + 6 were online at once. + assert_eq!(busy.len(), 1); + assert_eq!((busy[0].players, busy[0].peak_players), (12, 16)); + } + + #[sqlx::test] + async fn a_spike_the_average_flattens_still_peaks_and_longer_ranges_keep_it(db: PgPool) { + // One 2-hour bucket of beats every 10 minutes with 2 players, and one with 30 between them. + let quiet: Vec<_> = (0..11).map(|i| ("203.0.113.1", 2, 119 - i * 10)).collect(); + beats_at(&db, &quiet).await; + beats_at(&db, &[("203.0.113.1", 30, 64)]).await; + + let (day, week, month) = ( + activity(&db, "day").await, + activity(&db, "week").await, + activity(&db, "month").await, + ); + assert_eq!(peak(&day), 30); + // The 2-hour bucket's average is (11 × 2 + 30) / 12 = 4, but the spike is its peak. + let bucket = week.points.iter().find(|p| p.servers > 0).unwrap(); + assert_eq!((bucket.players, bucket.peak_players), (4, 30)); + // Longer ranges sample the same moments and more, so they never peak lower. + assert!(peak(&week) >= peak(&day) && peak(&month) >= peak(&day)); + } + + /// Has a listed server beat with `players` at the latest 5-minute moment: within every range's bucket in + /// progress, and its last sample. + async fn beat_now(db: &PgPool, ip: &str, players: i64) { + listing::list(db, format!("{ip}:27015").parse().unwrap(), None) + .await + .unwrap(); + let mut body = report(27015); + body["players"] = serde_json::json!(players); + beat(db, ip, None, &body).await; + sqlx::query( + "UPDATE server_heartbeat_log SET received_at = date_bin('5 minutes', now(), '2000-01-01') + WHERE received_at > now() - interval '1 minute'", + ) + .execute(db) + .await + .unwrap(); + } + + #[sqlx::test] + async fn the_range_peak_includes_the_bucket_in_progress(db: PgPool) { + beats_at(&db, &[("203.0.113.1", 2, 60)]).await; + beat_now(&db, "203.0.113.1", 30).await; + + let mut left_out = false; + for range in ["day", "week", "month", "year"] { + let activity = activity(&db, range).await; + assert_eq!(activity.peak_players, 30, "{range}"); + left_out |= peak(&activity) < 30; + } + // The points leave the bucket in progress out, so they can't show the spike yet. + assert!(left_out); + } + + #[sqlx::test] + async fn a_longer_range_never_peaks_lower(db: PgPool) { + // 50 at once 20 days ago, 30 three days ago, 10 now; 70 on a day 100 days ago. + beats_at( + &db, + &[ + ("203.0.113.1", 25, 20 * 1440), + ("203.0.113.2", 25, 20 * 1440), + ("203.0.113.1", 30, 3 * 1440), + ], + ) + .await; + beat_now(&db, "203.0.113.2", 10).await; + // Beats kept today's peak as sent, all at once; clear it to test the windows alone. + sqlx::query("DELETE FROM server_activity_peaks") + .execute(&db) + .await + .unwrap(); + let peaks = || async { + let mut peaks = vec![]; + for range in ["day", "week", "month", "year"] { + peaks.push(activity(&db, range).await.peak_players); + } + peaks + }; + + // With no daily peaks, a year is still at least the month. + assert_eq!(peaks().await, [10, 30, 50, 50]); + sqlx::query( + "INSERT INTO server_activity_peaks (day, players) VALUES (current_date - 100, 70)", + ) + .execute(&db) + .await + .unwrap(); + assert_eq!(peaks().await, [10, 30, 50, 70]); + } + + #[sqlx::test] + async fn heartbeats_keep_the_days_peak(db: PgPool) { + listing::list(&db, "203.0.113.1:27015".parse().unwrap(), None) + .await + .unwrap(); + listing::list(&db, "203.0.113.2:27015".parse().unwrap(), None) + .await + .unwrap(); + let mut quiet = report(27015); + quiet["players"] = serde_json::json!(4); + beat(&db, "203.0.113.1", None, &report(27015)).await; + beat(&db, "203.0.113.2", None, &report(27015)).await; + beat(&db, "203.0.113.1", None, &quiet).await; + // An unlisted server doesn't count. + beat(&db, "203.0.113.3", None, &report(27015)).await; + let today: i32 = sqlx::query_scalar("SELECT players FROM server_activity_peaks") + .fetch_one(&db) + .await + .unwrap(); + // 12 + 12 at the second beat; .1 dropping to 4 doesn't lower the day's peak. + assert_eq!(today, 24); } #[sqlx::test] @@ -205,10 +455,12 @@ mod tests { beat(&db, "203.0.113.1", None, &quiet).await; beat(&db, "203.0.113.2", None, &report(27015)).await; // Today is left out of the year, so move today's totals to yesterday. - sqlx::query("UPDATE server_activity_daily SET day = day - 1") - .execute(&db) - .await - .unwrap(); + for sql in [ + "UPDATE server_activity_daily SET day = day - 1", + "UPDATE server_activity_peaks SET day = day - 1", + ] { + sqlx::query(sql).execute(&db).await.unwrap(); + } let year: ServerActivity = test_client::get(&db, "/v1/servers/activity?range=year") .await @@ -216,8 +468,15 @@ mod tests { assert_eq!((year.bucket_minutes, year.points.len()), (1440, 365)); let last = year.points.last().unwrap(); - // (12 + 4) / 2 players on average, on the one listed server. - assert_eq!((last.servers, last.players), (1, 8)); + // (12 + 4) / 2 players on average, on the one listed server; at most 12 at once. + assert_eq!((last.servers, last.players, last.peak_players), (1, 8, 12)); + assert!( + year.points + .iter() + .rev() + .skip(1) + .all(|p| p.peak_players == 0) + ); } #[sqlx::test] @@ -226,7 +485,11 @@ mod tests { .await .json(); assert_eq!((week.bucket_minutes, week.points.len()), (120, 84)); - assert!(week.points.iter().all(|p| p.servers == 0 && p.players == 0)); + assert!( + week.points + .iter() + .all(|p| p.servers == 0 && p.players == 0 && p.peak_players == 0) + ); let status = test_client::get(&db, "/v1/servers/activity?range=decade") .await .status; diff --git a/api/crates/api/src/servers/heartbeat.rs b/api/crates/api/src/servers/heartbeat.rs index 1d9cd6b..c570811 100644 --- a/api/crates/api/src/servers/heartbeat.rs +++ b/api/crates/api/src/servers/heartbeat.rs @@ -18,7 +18,10 @@ use sqlx::{PgPool, types::Json as JsonColumn}; use utoipa::ToSchema; use utoipa_axum::{router::OpenApiRouter, routes}; -use super::keys::{self, KeyLookup}; +use super::{ + activity, + keys::{self, KeyLookup}, +}; use crate::{ app::AppState, client_address::{ClientAddress, ClientCountry}, @@ -174,7 +177,7 @@ async fn heartbeat( // Only listed servers feed the activity chart, which is all it shows; it also keeps unlisted // senders, which anyone can be, from growing the log. The log serves up to a month, the daily totals // a year. - sqlx::query!( + let logged = sqlx::query!( r#" WITH listed AS ( SELECT ip, port FROM server_listings WHERE ip = $1::inet AND port = $2 @@ -192,6 +195,27 @@ async fn heartbeat( ) .execute(&state.db) .await?; + // A beat is the only time the total online can rise, so the day's peak is kept here. Its own statement: + // within the one above, the log row it just wrote wouldn't be visible yet. + if logged.rows_affected() > 0 { + sqlx::query!( + r#" + INSERT INTO server_activity_peaks AS p (day, players) + SELECT (now() AT TIME ZONE 'UTC')::date, coalesce(sum(latest.players), 0) + FROM ( + SELECT DISTINCT ON (h.ip, h.port) h.players + FROM server_heartbeat_log h + JOIN server_listings l ON l.ip = h.ip AND l.port = h.port + WHERE h.received_at > now() - make_interval(mins => $1) + ORDER BY h.ip, h.port, h.received_at DESC + ) latest + ON CONFLICT (day) DO UPDATE SET players = greatest(p.players, excluded.players) + "#, + activity::ONLINE_WINDOW_MINUTES + ) + .execute(&state.db) + .await?; + } Ok(Json(HeartbeatResponse { key, @@ -211,7 +235,7 @@ fn clean_hostname(hostname: &str) -> String { } /// Prunes every hour, for as long as the API runs. Not on each heartbeat: anyone can send those, and each -/// would cost three deletes. +/// would cost four deletes. pub async fn run(db: PgPool) { let mut ticks = tokio::time::interval(PRUNE_INTERVAL); ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); @@ -223,8 +247,8 @@ pub async fn run(db: PgPool) { } } -/// Forgets unlisted servers silent for a week, logged heartbeats after 30 days and daily totals after 400 -/// days. +/// Forgets unlisted servers silent for a week, logged heartbeats after 30 days and daily totals and peaks +/// after 400 days. async fn prune(db: &PgPool) -> Result<(), sqlx::Error> { sqlx::query!("DELETE FROM server_heartbeat_log WHERE received_at < now() - interval '30 days'") .execute(db) @@ -232,6 +256,9 @@ async fn prune(db: &PgPool) -> Result<(), sqlx::Error> { sqlx::query!("DELETE FROM server_activity_daily WHERE day < current_date - 400") .execute(db) .await?; + sqlx::query!("DELETE FROM server_activity_peaks WHERE day < current_date - 400") + .execute(db) + .await?; sqlx::query!( r#" DELETE FROM server_heartbeats h diff --git a/api/crates/api/src/staff/maps.rs b/api/crates/api/src/staff/maps.rs index d8beadf..b6ac38d 100644 --- a/api/crates/api/src/staff/maps.rs +++ b/api/crates/api/src/staff/maps.rs @@ -69,7 +69,7 @@ pub async fn set_tier( .await? .ok_or(NO_MAP)?; let in_force = sqlx::query_scalar!( - "SELECT tier FROM map_tiers WHERE map_id = $1 AND track = $2 ORDER BY assigned_at DESC LIMIT 1", + r#"SELECT tier AS "tier!" FROM current_map_tiers WHERE map_id = $1 AND track = $2"#, map_id, track ) @@ -309,8 +309,7 @@ pub async fn list_staff_maps( let rows = sqlx::query!( r#" SELECT m.name, ci.id AS "image_id?", ci.key AS "image_key?", ci.focus AS "image_focus?", m.last_run_at, - (SELECT tier FROM map_tiers t WHERE t.map_id = m.id AND t.track = 0 - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers t WHERE t.map_id = m.id AND t.track = 0) AS tier, (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version FROM maps m LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0 diff --git a/api/crates/api/src/staff/policies.rs b/api/crates/api/src/staff/policies.rs index 1699991..1a7ae60 100644 --- a/api/crates/api/src/staff/policies.rs +++ b/api/crates/api/src/staff/policies.rs @@ -43,9 +43,7 @@ pub async fn publish_policy( // A smaller count would leave maps rated above it; staff move those first. let highest = sqlx::query_scalar!( r#" - SELECT max(tier) FROM ( - SELECT DISTINCT ON (map_id, track) tier FROM map_tiers ORDER BY map_id, track, assigned_at DESC - ) in_force + SELECT max(tier) FROM current_map_tiers "# ) .fetch_one(&mut *tx) diff --git a/api/crates/api/src/steam.rs b/api/crates/api/src/steam.rs index 5be7f71..4460692 100644 --- a/api/crates/api/src/steam.rs +++ b/api/crates/api/src/steam.rs @@ -2,10 +2,13 @@ use std::{collections::HashSet, sync::Arc, time::Duration}; -use tokio::{sync::Mutex, time::Instant}; +use tokio::{ + sync::{Mutex, Semaphore}, + time::Instant, +}; use url::Url; -use crate::players::SteamId64; +use crate::players::{SteamId64, steam_profile}; #[derive(Clone, Debug)] pub struct Steam { @@ -17,6 +20,8 @@ pub struct Steam { last_request: Arc>>, /// Players whose profile refresh is waiting or running (`players/steam_profile.rs`). pub(crate) profile_refreshes: Arc>>, + /// Slots for profile fetches a request waits on (`players/steam_profile.rs`, `refresh_now`). + pub(crate) inline_fetches: Arc, } impl Steam { @@ -39,6 +44,7 @@ impl Steam { community: base.clone(), last_request: Arc::new(Mutex::new(None)), profile_refreshes: Arc::default(), + inline_fetches: Arc::new(Semaphore::new(steam_profile::INLINE_FETCHES)), } } diff --git a/api/openapi.json b/api/openapi.json index 91d277d..38076b7 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -134,6 +134,54 @@ } } }, + "/v1/auth/sign-out-everywhere": { + "post": { + "tags": [ + "auth" + ], + "summary": "Ends every session of the signed-in player, in every browser, and signs this one out. A form on the\nwebsite posts here. Unlike signing out, it needs a live session: answering a request without one as if it\nhad worked would tell the player their other browsers were signed out when nothing was ended.", + "operationId": "sign_out_everywhere", + "parameters": [ + { + "name": "return_to", + "in": "query", + "description": "The page to come back to: a path on this site, such as `/maps`. Anything else means `/`.", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + } + ], + "responses": { + "303": { + "description": "Back to the page the player came from, signed out everywhere" + }, + "401": { + "description": "Not signed in; no session was ended", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Not sent from SourceJump's own pages", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, "/v1/auth/steam": { "get": { "tags": [ @@ -540,7 +588,7 @@ { "name": "q", "in": "query", - "description": "Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that\nname comes first, then maps with a word starting with it, then other matches, each in the chosen\nsort; near misses for a typo come last, closest first.", + "description": "Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't\nmatter; spaces in map names stand for underscores. Exact map names come first, then word starts,\nother map matches and record holders, each in the chosen sort; near misses come last.", "required": false, "schema": { "type": [ @@ -861,6 +909,71 @@ } } }, + "/v1/maps/{map}/personal-bests": { + "get": { + "tags": [ + "maps" + ], + "summary": "These players' SourceJump personal bests on the map, every style and track. An unknown map, or players\nwithout runs on it, give an empty list.", + "operationId": "players_personal_bests", + "parameters": [ + { + "name": "map", + "in": "path", + "description": "Map name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "players", + "in": "query", + "description": "Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlayersPersonalBests" + } + } + } + }, + "401": { + "description": "Missing, unknown or revoked API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "422": { + "description": "Not a valid map name, or `players` isn't 1 to 64 SteamID64s", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + }, + "security": [ + { + "server_key": [] + } + ] + } + }, "/v1/maps/{map}/records": { "get": { "tags": [ @@ -1189,6 +1302,69 @@ } } }, + "/v1/players/{player}/avatar": { + "get": { + "tags": [ + "players" + ], + "summary": "Redirects to the player's Steam avatar. Takes a `SteamID64`, `SteamID2` or `SteamID3`. Only players\nSourceJump knows are looked up on Steam; a player known only from the old site gets the avatar it had.", + "operationId": "player_avatar", + "parameters": [ + { + "name": "player", + "in": "path", + "description": "SteamID64, SteamID2 (STEAM_0:1:2) or SteamID3 ([U:1:4])", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "No avatar yet: a placeholder with the player's initials, cached five minutes", + "content": { + "image/svg+xml": { + "schema": { + "type": "string" + } + } + } + }, + "302": { + "description": "To the avatar on Steam's CDN; cached a day", + "headers": { + "Location": { + "schema": { + "type": "string" + }, + "description": "The avatar's URL" + } + } + }, + "404": { + "description": "SourceJump has no such player", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "422": { + "description": "Not a SteamID", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, "/v1/players/{player}/details": { "put": { "tags": [ @@ -2039,6 +2215,19 @@ "format": "int64" } }, + { + "name": "offset", + "in": "query", + "description": "Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given.", + "required": false, + "schema": { + "type": [ + "integer", + "null" + ], + "format": "int64" + } + }, { "name": "cursor", "in": "query", @@ -2063,7 +2252,7 @@ } }, "422": { - "description": "Not a valid tier, limit or cursor", + "description": "Not a valid tier, limit, offset or cursor", "content": { "application/json": { "schema": { @@ -5917,7 +6106,8 @@ "required": [ "at", "servers", - "players" + "players", + "peak_players" ], "properties": { "at": { @@ -5925,6 +6115,11 @@ "format": "date-time", "description": "Where the bucket starts." }, + "peak_players": { + "type": "integer", + "format": "int32", + "description": "The most players online at once during the bucket, across listed servers: each server's latest\nheartbeat count, summed at the same moment. Up to a month, sampled every 5 minutes; for a year, the\nday's highest total at any heartbeat." + }, "players": { "type": "integer", "format": "int32", @@ -6191,7 +6386,7 @@ "string", "null" ], - "description": "An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's." + "description": "An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one;\nnull to stop showing the player's pick." }, "dpi": { "type": [ @@ -7667,7 +7862,7 @@ }, "MapStats": { "type": "object", - "description": "The whole list at a glance, whatever the search or filter.", + "description": "Global totals and tier-scoped newest and weekly lists.", "required": [ "maps", "by_tier", @@ -7701,6 +7896,14 @@ "$ref": "#/components/schemas/PlayedMap" }, "description": "The maps the most players finished a run on in the last 7 days, most first." + }, + "tier": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "The tier the newest and weekly lists describe; None describes all tiers. Totals remain global." } } }, @@ -7945,6 +8148,14 @@ "style": { "type": "string" }, + "tier": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "The board's tier. None while tiers aren't in force or staff haven't set this board's, and for a legacy\nrun." + }, "time": { "type": "number", "format": "double", @@ -7954,6 +8165,14 @@ "type": "integer", "format": "int32", "description": "0 is the main track, 1 and up are bonuses." + }, + "world_record_time": { + "type": [ + "number", + "null" + ], + "format": "double", + "description": "The board's 2.0 record time, as on its map leaderboard, so a client can show the gap to it. None for a\nlegacy run." } } }, @@ -8094,6 +8313,50 @@ } } }, + "PlayerPersonalBest": { + "type": "object", + "required": [ + "steamid64", + "style", + "track", + "time", + "rank", + "run_id", + "finished_at" + ], + "properties": { + "finished_at": { + "type": "string", + "format": "date-time" + }, + "rank": { + "type": "integer", + "format": "int64", + "description": "Place on the leaderboard; equal times share a place, as in `…/records`." + }, + "run_id": { + "type": "integer", + "format": "int64" + }, + "steamid64": { + "type": "string", + "description": "SteamID64, as a string." + }, + "style": { + "type": "string" + }, + "time": { + "type": "number", + "format": "double", + "description": "Seconds." + }, + "track": { + "type": "integer", + "format": "int32", + "description": "0 is the main track, 1 and up are bonuses." + } + } + }, "PlayerPrivileges": { "type": "object", "required": [ @@ -8135,14 +8398,14 @@ }, "country_chosen": { "type": "boolean", - "description": "Whether the player picked `country_code` themselves, rather than it coming from Steam." + "description": "Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam." }, "country_code": { "type": [ "string", "null" ], - "description": "ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one." + "description": "ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it\nsince, or else their Steam profile's. None if none has one." }, "details": { "oneOf": [ @@ -8202,6 +8465,14 @@ "$ref": "#/components/schemas/PlayerStyle" }, "description": "One entry per style they hold a personal best in, sorted by style key. Counts are 2.0 alone." + }, + "tier_count": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "Number of tiers in force; None while the community hasn't set tiers, and personal bests then have no\ntier." } } }, @@ -8383,6 +8654,25 @@ } } }, + "PlayersPersonalBests": { + "type": "object", + "required": [ + "map", + "personal_bests" + ], + "properties": { + "map": { + "type": "string" + }, + "personal_bests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PlayerPersonalBest" + }, + "description": "Sorted by player, style and track. A player with no personal best on the map has no entries. One flat\nlist keeps it simple to read in SourcePawn." + } + } + }, "PluginRelease": { "type": "object", "description": "A published `sourcejump.smx` build.", @@ -8858,7 +9148,8 @@ "RecentRuns": { "type": "object", "required": [ - "runs" + "runs", + "total" ], "properties": { "next_cursor": { @@ -8882,6 +9173,11 @@ ], "format": "int32", "description": "Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier." + }, + "total": { + "type": "integer", + "format": "int64", + "description": "How many runs match the filters, across all pages." } } }, @@ -9677,6 +9973,14 @@ "name" ], "properties": { + "country_code": { + "type": [ + "string", + "null" + ], + "description": "The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO\n3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It\nbecomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored\nanyway. Runs only: detections ignore it.", + "example": "SE" + }, "name": { "type": "string" }, @@ -9899,6 +10203,7 @@ "required": [ "range", "bucket_minutes", + "peak_players", "points" ], "properties": { @@ -9906,6 +10211,11 @@ "type": "integer", "format": "int32" }, + "peak_players": { + "type": "integer", + "format": "int32", + "description": "The most players online at once across listed servers over the whole range, from the start of its\nfirst point up to now, the bucket in progress included: no point reads higher, and a shorter range never\nreads higher than a longer one." + }, "points": { "type": "array", "items": { diff --git a/docs/VISION.md b/docs/VISION.md index 7f62043..9191906 100644 --- a/docs/VISION.md +++ b/docs/VISION.md @@ -31,4 +31,4 @@ **References:** - `docs/design/reference.webp`: the direction for look and feel (dark slate, cyan accent, stat cards, medal rows, map cards). Not a target; see `docs/design-system.md`. - CS:GO KZ community sites: per-tier completions and "% of maps done" on profiles. -- Font: [Play](https://fonts.google.com/specimen/Play), used on the previous site. +- Font: [Geist](https://vercel.com/font). The previous site used [Play](https://fonts.google.com/specimen/Play). diff --git a/docs/api.md b/docs/api.md index 4153656..6ad5e53 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,5 +1,5 @@ # API -How the `/v1/` API behaves for game servers, and rules every client can rely on. The website's own endpoints (sign-in, players, maps, servers, posts): `site-api.md`. The exact schema is `api/openapi.json`. Examples, checked by `cargo test`: `api/contract/`. +How the `/v1/` API behaves for game servers, and rules for every client. The website's own endpoints: `site-api.md`. The exact schema is `api/openapi.json`. Examples, checked by `cargo test`: `api/contract/`. ## Endpoints | Endpoint | Key | Code | @@ -7,7 +7,8 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. | `GET /v1/ruleset` | no | `ruleset.rs` | | `GET /v1/maps/{map}/zones` | no | `zones.rs` | | `GET /v1/maps/{map}/records` | no | `records.rs` | -| `GET /v1/records/events`, `GET /v1/records/stream` | no | `record_events.rs`, `record_events/stream.rs` | +| `GET /v1/maps/{map}/personal-bests` | yes | `records/` | +| `GET /v1/records/events`, `…/stream` | no | `record_events.rs`, `record_events/stream.rs` | | `GET /v1/maps`, `GET /v1/maps/{map}`, `…/leaderboard`, `…/wr-history` | no | `maps/` | | `GET /v1/runs/{id}` | no | `runs/detail.rs` | | `GET /v1/plugin/latest` | no | `plugin_releases.rs` | @@ -16,62 +17,64 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. | `POST /v1/runs` | yes | `runs.rs`, `replays.rs` | | `GET /v1/replays/{run_id}` | no | `replays/download.rs` | | `POST /v1/anticheat/detections` | yes | `anticheat.rs` | -| `GET /v1/players`, `GET /v1/players/{player}`, `…/personal-bests` | no | `players/` | -| `GET /v1/auth/steam`, `GET /v1/auth/steam/callback`, `POST /v1/auth/sign-out` | browser | `auth.rs`, `auth/openid.rs` | -| `GET /v1/me` | session | `auth.rs`, `auth/sessions.rs` | -| `GET /v1/posts`, `GET /v1/posts/{post}`; `POST`, `PUT`, `DELETE` to write | no; session to write | `posts.rs`, `posts/` | +| `GET /v1/players`, `…/{player}`, `…/personal-bests` | no | `players/` | +| `GET /v1/auth/steam`, `…/callback`, `POST /v1/auth/sign-out` | browser | `auth.rs`, `auth/openid.rs` | +| `GET /v1/me`, `POST /v1/auth/sign-out-everywhere` | session | `auth.rs`, `auth/sessions.rs` | +| `GET /v1/posts`, `…/{post}`; `POST`, `PUT`, `DELETE` to write | no; session to write | `posts.rs`, `posts/` | | `/v1/staff/…`: log, keys, servers, listings | staff session | `staff.rs`, `staff/` | ## Rules every client can rely on - **Errors** always have the body `{"error": "..."}`. The message is for people; don't match on it. -- **Retrying:** `2xx` means stored. Network errors, `5xx` and `429` (too many) are temporary: keep the item queued and resend it later. Any other `4xx` is final: the request breaks a rule and resending never works, so the plugin drops it. +- **Retrying:** `2xx` means stored. Network errors, `5xx` and `429` (too many) are temporary: keep the item queued and resend it. Any other `4xx` is final: the request breaks a rule, so the plugin drops it. - **Idempotency:** runs and detections carry an ID from the game server (`server_run_id`, `server_detection_id`), unique per server. A resend gets `200` with the first answer and changes nothing; the first send gets `201`. - **SteamID64s** are JSON strings: too big for a JavaScript number, and SourcePawn has no 64-bit integers. - **Map names** are lowercased; other characters than `a-z 0-9 _ - .`, or only dots, are rejected. -- **Server times** (`finished_at`, `detected_at`) are Unix seconds by the game server's clock. The API also records when it received each item. Times over 5 minutes ahead of the API's clock get `422`. +- **Server times** (`finished_at`, `detected_at`) are Unix seconds by the game server's clock. The API also records when each item arrived. Times over 5 minutes ahead of the API's clock get `422`. ## Keys - One key per server, sent as `Authorization: Bearer sj_…`. Only its SHA-256 is stored, so a lost key is replaced, never recovered. - A missing, unknown or revoked key gets `401` on keyed endpoints (`ServerKey` in `servers/keys.rs`). The heartbeat never rejects for its key; it answers `valid`, `revoked`, `unknown` or `none`. - Every run and detection records the key it came with, so revoking a key can invalidate every run its server sent, with any key (staff choose, `site-api.md`). -- Staff issue, replace and revoke keys on `/staff/keys` (or `sourcejump-api keys issue ""`, `keys revoke `). A server holds one active key at a time (a unique index); a new key revokes its old one in the same step. How servers request keys is still open (`domain.md`). +- Staff issue, replace and revoke keys on `/staff/keys` (or `sourcejump-api keys issue ""`, `keys revoke `). A server holds one active key at a time (a unique index); a new key revokes the old in the same step. How servers request keys is still open (`domain.md`). ## Server heartbeats -- Every plugin server, keyed or not, sends one on map start and then every `next_heartbeat_seconds` (600 now): hostname, port, map, players and slots, versions (`shavit_version` null without shavit), plugins, compliance. +- Every plugin server, keyed or not, sends one on map start, then every `next_heartbeat_seconds` (600 now): hostname, port, map, players and slots, versions (`shavit_version` null without shavit), plugins, compliance. - A server is its address: the IP the heartbeat came from plus its reported port. Behind Caddy the IP is the last `X-Forwarded-For` entry, `country_code` Cloudflare's `CF-IPCountry` (`XX`, `T1`: none), trusted only from this machine (`client_address.rs`). The reported `ip` is for staff, never trusted. - Only the latest heartbeat per address is kept (`server_heartbeats`), at most 32 ports per IP; an hourly job drops unlisted ones silent 7 days. A valid key links the address to its `servers` row. - Over 64 KB gets `413`. Hostnames lose control characters, cut to 64. An IP (IPv6: /64) may send 120 at once, then 30 a minute; more get `429`, before any key check (`heartbeat_limit.rs`). ## Runs -- Accepted only if the run's ruleset version exists, its style is ranked in that version, its tickrate matches the ruleset's `tickrate` if set, and the plugin reports the server as compliant. Field ranges are checked once, at the boundary. +- Accepted only if the run's ruleset version exists, its style is ranked there, its tickrate matches the ruleset's `tickrate` if set, and the plugin reports the server as compliant. +- Optional `player.country_code`: the server's `GeoipCode2` for the player (never their IP) sets their flag; unknown codes are ignored. - `personal_bests` holds each player's fastest run per map, style and track, updated in the same transaction. A tie keeps the earlier run. -- Any keyed server can add a map by submitting a run on it. Which maps are ranked is a separate decision. +- Any keyed server adds a map by submitting a run on it; ranking it is a separate decision. ## Replays - The `replays` policy decides which replays are wanted (`request`: `new_personal_best`, the lead's call on 2026-10-19; `every_run` or `nothing`) and which styles' replays are public (`public_styles`: every ranked style, lead 2026-11-03). A missing policy asks for nothing and makes nothing public. -- A wanted replay gets a presigned `PUT` link, valid for an hour, to `uploads/replays/-.replay` in a private bucket. The server uploads there directly. A resend of the run returns a fresh link, with `last_refusal` (reason, time) if the last upload was refused, or no link once the replay is stored (delete the local copy). -- Every 30 s a job (`replays/processing.rs`) lists the uploads and checks each against its run: shavit format 12 only, frames fill the file exactly, same map (any case), track, player and tickrate, and the time within half a tick. Over 128 MB is refused. A good file is stored as SJR (`replays/sjr.rs`, a fifth the size) at `replays/-.sjr`; the upload is deleted. A bad one is deleted, its reason kept on the `replays` row, and the server may upload again. A stored replay never changes; a failing upload is retried. +- A wanted replay gets a presigned `PUT` link, valid for an hour, to `uploads/replays/-.replay` in a private bucket. A resend returns a fresh link, with `last_refusal` (reason, time) if the last upload was refused, or no link once the replay is stored (delete the local copy). +- Every 30 s a job (`replays/processing.rs`) lists the uploads and checks each against its run: shavit format 12 only, frames fill the file exactly, same map (any case), track, player and tickrate, and the time within half a tick. Over 128 MB is refused. A good file is stored as SJR (`replays/sjr.rs`, a fifth the size) at `replays/-.sjr`; the upload is deleted. A bad one is deleted, its reason kept on the `replays` row; the server may upload again. A stored replay never changes; a failing upload is retried. - The bucket is public; random keys mean only the API reveals files. `GET /v1/runs/{id}` gives the SJR link (`replay.sjr_url`; invalidated runs too, lead 2026-11-03), its route from above (`replay.route`, `replay-viewer.md`), and `GET /v1/replays/{run_id}` the shavit file, rebuilt byte for byte at its first download and kept (own random key), only while the run is valid and its style is public. -- `GET /v1/maps/{map}/records` marks each record `has_replay` by the same rule, so a server only asks for files it will get. +- `…/records` marks each record `has_replay` by the same rule, so servers ask only for files they'll get. ## Map records for `/wr` - `GET /v1/maps/{map}/leaderboard?style=&track=` pages one board (`total`, `next_cursor`); `player=` (any SteamID) adds their best and rank as `player_entry`. Opaque cursors name where a page ended, so paging survives that player improving; old run-ID ones work while the run is a PB. Its rows and `…/records`' carry `points` and `has_replay`. -- Both send an `ETag` (`etag.rs`, a body hash); `If-None-Match` with it gets a bodiless `304` until the answer changes. So do `/v1/ruleset`, `…/zones` and `/v1/plugin/latest`. +- `…/personal-bests?players=` (1–64 SteamID64s): their bests on every board, with `rank`. +- All three send an `ETag` (`etag.rs`, a body hash); `If-None-Match` with it gets a bodiless `304` until it changes. So do `/v1/ruleset`, `…/zones` and `/v1/plugin/latest`. ## Record events -- `GET /v1/records/events` lists what happened to records, for servers announcing them or playing them on their bot: `run` (a new personal best, or a restored run that is one again), `replay` (its replay stored) and `invalidated` (staff took a run off a board; read the map's records again). Events are written with their change and kept a week. `previous_time` is the player's best on the board before that run, as it stood then (null: none; migration 0043). The same events feed the Discord posts of records and personal bests (`record_events/discord.rs`). -- Servers poll every 10 to 30 s with `after`, the `next` of their last answer; without it they get only a `next` from now. Cursors are opaque. `max_rank` (default 1) keeps runs at that rank or better now; `invalidated` events always come. +- `GET /v1/records/events` lists what happened to records, for servers announcing them or playing them on their bot: `run` (a new personal best, or a restored run that is one again), `replay` (its replay stored) and `invalidated` (staff took a run off a board; read the map's records again). Events are written with their change, kept a week. `previous_time` is the player's best on the board before that run, as it stood then (null: none; migration 0043). The same events feed the Discord posts of records and personal bests (`record_events/discord.rs`). +- Servers poll every 10 to 30 s with `after`, the `next` of their last answer; without it, only a `next` from now. Cursors are opaque. `max_rank` (default 1) keeps runs at that rank or better now; `invalidated` events always come. - Pages hold only events from transactions older than every running one, so a late commit is delayed, never skipped. - `GET /v1/records/stream` pushes the same events as server-sent events (`event:` kind, `id:` cursor, `data:` the event), starting from `Last-Event-ID`, `after` or now, with a comment every 15 s. One reader, woken by `NOTIFY`, reads each event once for every stream (`stream.rs`); an IP may hold 40 streams, `429` past that. Streams end at shutdown; clients reconnect with `Last-Event-ID`. - The ruleset's `features.record_events` and `features.record_stream` tell the plugin to follow them (migration 0035). ## Policies and versioned data -Rulesets, zone sets and `policies` (community policy the plugin doesn't need: `servers`, `replays`, `tiers`, typed in `policies.rs`) are append-only: database triggers refuse updates and deletes. A change is a new version, and the newest version is in force. Runs record the ruleset version they were played under. A new version ships as a migration (lead, 2026-10-21); a test checks every ruleset they publish (`RulesetDocument::check`). The CLI's `tiers count` publishes the tier count, logged. +Rulesets, zone sets and `policies` (community policy the plugin doesn't need: `servers`, `replays`, `tiers`, typed in `policies.rs`) are append-only: database triggers refuse updates and deletes. A change is a new version; the newest is in force. Runs record the ruleset version they were played under. A new version ships as a migration (lead, 2026-10-21); a test checks every ruleset they publish (`RulesetDocument::check`). The CLI's `tiers count` publishes the tier count, logged. - Ranked styles carry shavit `settings` and `flags`; `RankedStyle` (`ruleset.rs`) says how they match. Provisional values: migrations 0041–0042 (lead, 2026-11-04). ## Zones -Served in exactly the JSON array `shavit-zones-json` reads, so servers point `shavit_zones_json_url` at `/v1/maps/{map}/zones`. A `404` means SourceJump has no zones for the map, and servers don't submit there. The `SourceJump-Zone-Set-Version` header (on `304` too) names the set served. Staff publish zone sets (`staff-api.md`); everyone sees the set in force at `/maps/{map}/zones`. Runs carry a zone fingerprint, stored as sent; checking it comes with run verification. +Served in exactly the JSON array `shavit-zones-json` reads, so servers point `shavit_zones_json_url` at `/v1/maps/{map}/zones`. A `404`: SourceJump has no zones for the map; servers don't submit there. The `SourceJump-Zone-Set-Version` header (on `304` too) names the set served. Staff publish zone sets (`staff-api.md`); everyone sees the set in force at `/maps/{map}/zones`. Runs carry a zone fingerprint, stored as sent; checking it comes with run verification. ## Not yet decided or built -- Field names can still change: no client uses them yet. Once plugin work starts, the lead approves the contract and it's copied to the plugin repo. -- Whether old plugin endpoints keep working, how zones are submitted and reviewed, and whether keyless servers' queued runs can be imported later. +- Field names can still change: no client uses them yet. Once plugin work starts, the lead approves the contract and it goes to the plugin repo. +- Whether old plugin endpoints keep working, how zones are submitted and reviewed, and whether keyless servers' queued runs can be imported. diff --git a/docs/design-system.md b/docs/design-system.md index ad898a2..5b36de7 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -1,15 +1,15 @@ # Design system -One visual language that every page is built from, so pages can't drift apart. See it all at `/dev/ui` (dev builds only). +One visual language for every page, so pages can't drift apart. See it at `/dev/ui` (dev builds only). ## Direction -"Navy", chosen by the lead on 2026-10-19 (reference: `design/reference.webp`, a direction, not a target). -- Dark blue slate, never pitch black. One cyan accent; at most one primary button per view. +"Classic" (2026-11-07): the old sourcejump.net, updated. Replaced "Navy". +- A slate sheet (`bg`, `shadow-sheet`) with gutters, halfway from 72rem to full width. One cyan accent; at most one primary button per view. - Gamified but professional: medals, tier colors, WR badges, count-ups and small motions. No mascots, confetti, slogans or sales copy. -- Play for everything. Its digits are all the same width, so times line up in columns without a second font. -- Corners: `rounded-sm` (4px) for badges, `rounded-md` (8px) for controls and rows, `rounded-lg` (12px) only for padded cards and dialogs. +- Geist: 450 regular, 700 bold, matched to the old Play; Exo 2 bold (`font-server`) for server names. Times and tables use equal-width digits. +- Corners: `rounded-md` (8px) for every frame, from a panel to a field or button; `rounded-sm` (4px) for badges and rows inside a frame. ## Tokens -`web/src/ui/tokens.css` holds every color, type size, radius, shadow and easing as Tailwind theme variables. Tailwind's own palette, radii, type scale and shadows are cleared, so `bg-red-500` or `rounded-3xl` don't compile. Spacing keeps Tailwind's 4px grid. +`web/src/ui/tokens.css` holds every color, type size, radius, shadow and easing as Tailwind theme variables. Tailwind's own palette, radii, type scale and shadows are cleared, so `bg-red-500` or `rounded-3xl` don't compile. Spacing keeps Tailwind's 4px grid. Breakpoints add `xs` (360px) for the narrowest phones. - Surfaces, darkest to lightest: `bg`, `surface`, `surface-raised`, `surface-overlay`. Borders: `border`, `border-strong`. - Text: `text`, `text-muted`, `text-subtle`. Accent: `accent`, `accent-hover`, `accent-soft`, `on-accent`. - Status: `success`, `warning`, `danger`, each with a `-soft` tint. Medals: `gold`, `silver`, `bronze`, `on-medal`. @@ -21,33 +21,36 @@ One visual language that every page is built from, so pages can't drift apart. S | Component | Use | |---|---| | `Page` | Every page's content area; `width` is `wide`, `narrow` (reading) or `fill` (inside a section layout that sets its own width, such as the staff area). Runs the page fade | +| `Masthead` | Full-width top band, plain or over a map picture, in `Page width="fill"` (Players pages) | | `Link` | Every internal link; never prefetches. Lint blocks importing `next/link` elsewhere | | `Button`, `ButtonLink`, `ButtonAnchor` | `primary` (one per view), `secondary` (default), `ghost`; sizes `sm`, `md`. A `ghost` button with `aria-pressed` or `aria-expanded` shows the accent while on. `ButtonAnchor` is for full page loads, such as sign-in | | `Card`, `Label` | Bordered surface; `interactive` adds the hover lift. `Label` is the small uppercase heading | -| `StatCard` | Headline number with label and icon, counting up, and an optional short detail beside the number (never under it, so cards in a row stay one height). `null` shows a dash | +| `StatCard` | Headline number with label and icon, counting up, and an optional detail beside the number (not under it, so a row of cards stays one height). `null` shows a dash | | `Badge` | Short status: `neutral`, `accent` (WR), `success`, `warning`, `danger` | | `Medal` | Placement; medals for 1–3, a plain number after | | `TierBadge` | `tier` and `tierCount` from the API | | `Avatar` | Steam avatar or initials; `sm` to `xl` | | `Flag` | Country flag from an ISO code, a grey placeholder without one; `hint` replaces its tooltip | -| `Table` + `TableHead`/`TableBody`/`TableRow`/`TableHeaderCell`/`TableCell` | Leaderboards and staff lists; `numeric` cells right-align, `wrap` cells let long names wrap. Scrolls sideways inside its frame when too wide | +| `Table` + `TableHead`/`TableBody`/`TableRow`/`TableHeaderCell`/`TableCell` | `numeric` cells right-align, `centered` heads center on narrow marks, `wrap` cells wrap, `separated` rows start a group. Scrolls sideways if too wide; `phoneLead` + `phoneFill` size a phone's first view to end at a column's edge | | `Tabs` | Panels on one page; `underline` or `segmented` | | `LinkTabs` | Looks like `Tabs`, but each tab is a link: a view the server renders, such as the Maps page's sort | -| `Segmented` | Looks like segmented `Tabs`, for a choice that changes the view in place (a server's activity range, a post's kind). The chosen option is in the accent | -| `ChoiceMenu` | "Label Value ▾": one choice from a list, in a `Menu` of radio items, changing the view in place, or following each option's `href` on a server page. Boards, profiles and the Maps page use a row of them (Style, Track, Runs; Sort, Records in; lead, 2026-10-26); quiet options are dimmed but choosable, disabled ones dimmed and kept in place. On a phone each takes a full row, label left and value right | +| `Segmented` | Looks like segmented `Tabs`, for a choice that changes the view in place, e.g. a chart range. The chosen option is in the accent | +| `ChoiceMenu` | "Label Value ▾": one choice from a list, in a `Menu` of radio items, changing the view in place, or following each option's `href` on a server page. Boards, profiles and the Maps page use a row of them (lead, 2026-10-26); Style lists Autosync after Normal (`menuOrder`); quiet options are dimmed but choosable, disabled ones dimmed and kept in place. Word-width on phones too, so they sit side by side | | `ChoiceBar` | The row those menus sit in, with any tabs beside them. Every page uses it, so the spacing between choices stays the same everywhere | -| `Pager` | Previous and next under a paged list | +| `Pager` | Page links under a paged list; `param`: its address key. Holds its widest row, so turning pages never moves it | | `DividedList`, `DividedSection` | Rows with lines between them, and a part set off by a line above, inside a `Card` or `Dialog`. The lines run to the surface's edges | | `StepChart` | A value that changes in steps over time (WR history). Hover snaps a crosshair to the nearest point; points take focus and open their link | -| `LineChart` | One count over time from zero (players online). Drawn in a fixed box stretched by CSS, so it fills its container before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart | -| `TierSpread` | How many maps hold each tier: a donut in tier colors beside each tier's count and share; each slice and row links to that tier's maps, the others dim, and "All" closes the list (Maps page) | -| `Tooltip` | Hint on hover and focus; the child must be focusable | -| `Menu`, `MenuItem`, `MenuLink`, `MenuSeparator` | Menu button (account, mobile sections) | -| `Dialog` | Controlled modal (`open`, `onClose`). A field marked `data-autofocus` takes focus on each opening (React's `autoFocus` fires only on mount). Closes itself, without calling `onClose`, when its page is hidden for Back | -| `Input`, `Textarea`, `CountUp` | Text field with optional icon; multi-line field; animated number | +| `LineChart` | One count over time from zero (players online). CSS-stretched, so it fills its box before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart | +| `TierSpread` | Tier donut (bar on phones) and count/share legend. Rows and slices filter maps; "All tiers" resets; other slices dim | +| `Dot` | "·" in a wrapping line; hidden on phones, where it could end one | +| `Tooltip` | Hint on hover and focus; child takes focus | +| `Menu`, `MenuItem`, `MenuLink`, `MenuSeparator` | Menu button (account; `sheet`: phone menu) | +| `Dialog` | Controlled modal (`open`, `onClose`). A field marked `data-autofocus` takes focus on each opening, not just the first. Closes itself, without calling `onClose`, when its page is hidden for Back | +| `BrandIcon`, `SteamButton` | Community and Steam logos (`colored`: in their own colors); Steam sign-in | +| `Input`, `SearchField`, `Textarea`, `CountUp` | Text field with optional icon; search, button inside; multi-line field; animated number | | `Prose` | Long-form HTML (a post's body) in the site's type. Only for HTML the API made safe | -The run dialog opens in place: `RunLink` adds `?run=` to the address with `history.pushState`, and `RunDialogHost` (in the root layout) opens at once and loads the run inside. Back or Escape closes it, and the address can be shared. A run link's `href` is `/runs/{id}`, the run's own page, for new tabs. A map page's style and track work the same way, with `replaceState`. +The run dialog opens in place: `RunLink` pushes `?run=` to the address and `RunDialogHost` (root layout) loads the run. Back or Escape closes it; the address can be shared. A run link's `href` is `/runs/{id}`, the run's own page, for new tabs. A map page's style and track work the same way, with `replaceState`. A `className` passed to a primitive is for placement (margin, width, grid), not restyling. Domain components (`RunRow`, `RunDialog`, …) live in `src/features//` and are built from these. @@ -62,21 +65,20 @@ Named utilities, so pages never write their own transitions: - `motion-draw`: an SVG line drawing itself in (a run's route); the shape needs `pathLength="1"`. - `motion-reveal`: a section rising in as it scrolls into view (scroll-driven; browsers without it show it at once). - `motion-settle`: a large picture easing out of a slight zoom as the page opens (the home header). -- `HeaderDepth` (`features/home/`): the home header's picture leans with the mouse, by a depth map of it (`scripts/header-depth.py`; rerun it when the picture changes). Dust drifts in the light shaft, and a click sends cyan traces crawling over the surfaces (`headerTraces.ts`). WebGL, running only while the header is on screen; off on touch screens and with reduced motion. -- `motion-ripple`: a ring spreading and fading from where something landed; re-key it to replay. -- `motion-pop`: a popover menu fading in with a slight drop and grow, and fading out as it closes (`Menu`). +- `HeaderDepth` (`features/home/`): the home header's picture leans with the mouse, by a depth map of it (`scripts/header-depth.py`; rerun it when the picture changes). Dust drifts in the light shaft, and a click sends cyan traces crawling over the surfaces (`headerTraces.ts`). WebGL, only while on screen; off on touch screens and with reduced motion. The buttons above it get their own layer (`will-change-transform`): without it GPU Chromium dropped a hover's color after a frame. +- `motion-pop`: a menu fading in with a slight drop and grow (`Menu`); `motion-fade`: its `sheet`'s dim. - `CountUp`: counts up when scrolled into view, and from the old value when it changes. A number already in view when the page loads stays as it is. - `page-fade`: between pages (see Navigation). All of them respect `prefers-reduced-motion` and show their end state at once. ## Navigation -Pages swap in place with no full page load. The old page fades out quickly and the new one fades in, using React's `` in `Page` and the `page-fade` rules in `motion.css`. The header has its own view-transition name, so it stays still during the fade. Browsers without view transitions swap pages without the fade. A page with views, such as a map and its Manage view, keeps its header in a route layout and wraps each view in `PageView`: switching views fades the old one out and lifts the new one in (`view-flip`), and the header stays. +Pages swap in place: the old page fades out and the new one in (React's `` in `Page`, `page-fade` in `motion.css`); the header has its own transition name, so it stays still. Without view transitions, pages just swap. A page with views (a map and its Manage view) keeps its header in a route layout and wraps each view in `PageView`, which fades one out and lifts the next in (`view-flip`). Links never prefetch, whether in view or hovered (lead's choice, 2026-10-19). A page loads only once it's opened, and the fade covers the wait. `e2e/navigation.e2e.ts` checks that following a link doesn't reload the page. ## Layout shell (`web/src/features/site/`) -Header (wordmark, sections, account corner) and footer, applied in the root layout. On narrow screens the sections collapse into a menu. The account corner (sign-in button, or the player's menu) and the current-section highlight depend on the request, so each sits in `` and every page's shell stays static. Search lives on the Players page. Section pages arrive with their roadmap slices. +Header, page and footer sit on the sheet. The header is one sticky bar: wordmark, sections, search (`/`), Steam sign-in; footer: one line, community logos. Phones: menu, wordmark, search, account. Account and current section sit in ``, so every shell stays static. Search lives on the Players page. ## Screenshot tests `npm run test:ui` (part of `just check`) screenshots `/dev/ui` wide, on a phone, with the menu open and with the dialog open, and fails on any pixel change. After an intended visual change: diff --git a/docs/plans/web-redesign-api.md b/docs/plans/web-redesign-api.md new file mode 100644 index 0000000..5accce0 --- /dev/null +++ b/docs/plans/web-redesign-api.md @@ -0,0 +1,50 @@ +# Web redesign: what the API side needs (plan) + +Temporary. What the November 2026 web redesign (branch `feat/mobile-profile-polish`) leaves for the lead on the API +side, and the shortcuts the web takes until then. Delete each item once it's done, and the file when it's empty. + +## To merge and deploy + +- **PR #16** (`api/profile-and-flags`): player avatars (`GET /v1/players/{player}/avatar`), a player's country from + the game server that saw them (migration `0052`), the true peak of players online (`0053`), and a personal best's + tier. The web already uses all four: against beta, avatars 404 and profile tier badges are missing until it ships. +- **Migration numbers:** PR #16 holds `0052` and `0053`. akanora's #26 also chose `0052`; on the integration branch + it is `0054`, after #16's. Merge #16 first. If #26 is merged upstream on its own as `0052`, #16's two must be + renumbered after it (sqlx rejects a reused version with different content). +- **akanora's PRs #24–#29** (sourcejump/sourcejump), on local branch `integrate/akanora-prs`, one cherry-pick each + with his authorship, then fixes, then one regenerated spec/types/query cache (commits before it don't build with + `SQLX_OFFLINE=true`, so it ships whole). `just check` passed (303 Rust tests, web tests) bar the screenshots. + - #27 Windows build, as submitted. #29 link previews and an error page, as submitted; previews checked. + - #26 one `current_map_tiers` view for the tier in force; also used by the three copies added since it branched. + Checked equal to the old lookup on every map and track, untiered ones included. + - #24 `GET /v1/maps/{map}/personal-bests?players=` (1–64 SteamID64s): each player's PB and rank on every board + of a map, in one request on map change. Changed to require a server key (401 first), and the 64 limit is + checked while parsing. **The plugin must send `Authorization` on it.** + - #28 sign out everywhere: same Origin check as sign-out, ends only that player's sessions. Changed to answer 401 + with no live session, rather than 303 as if it had worked. + - #25 your own place pinned under a map board's top: needs a signed-in check in a browser, not done yet. + +## API additions the web would use + +- **Personal bests in place order:** a profile now opens best place first. The API pages personal bests by map + only, so the web loads every page of a style's 2.0 list on open, 100 a request (shortcut in `PlayerStyles.tsx`). + A `sort=place` option on `GET /v1/players/{player}/personal-bests` would end that. Pre-2.0 views keep map order, + since legacy runs have no place. +- **One record per board:** home's "Latest world records" fetches 100 records to find 8 boards (shortcut in + `LiveNow.tsx`). A `distinct` option on `GET /v1/runs?records=true` would make it exact. +- **Map boards sorted by more than time:** sorting a map leaderboard by jumps, sync or date loads the whole board + (shortcut in `Leaderboard.tsx`). A `sort` parameter would serve boards with thousands of runs. + +## Open questions for the lead + +- **Style order:** the Style menus list Autosync right after Normal, a display order in the web + (`features/ruleset/menuOrder.ts`); the ruleset and the Ruleset page keep the ruleset's order. If the community + wants that to be the ruleset's own order, that's a ruleset migration, and `menuOrder` can go. + +## Practices the redesign settled + +- One font, Geist (450 and 700), with Exo 2 bold for server names only (the `font-server` token). +- Phone tables: `Table phoneLead` with a `phoneFill` column sizes the first view to end at the ranked column; + `Pager` reserves its widest row so turning a page never moves it (`design-system.md`). +- A board's first record shows "(NEW)" where other records show what they took off: `RecentRun.gap` is null only + for a board's first run, so the API's meaning of a null gap must stay that. diff --git a/docs/site-api.md b/docs/site-api.md index 36ecdcd..c66f82a 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -1,54 +1,56 @@ # Site API -What the endpoints behind the website do: sign-in, players, maps, the server list and community posts; the staff tools are in `staff-api.md`. Rules for every client (errors, retries, SteamIDs) and game servers' endpoints: `api.md`. +The website's endpoints; staff tools: `staff-api.md`. Rules for every client and game servers' endpoints: `api.md`. ## Sign-in and sessions -Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirects, cookies) via the site's origin (Caddy in production, Next.js locally). -- Steam must confirm its answer (`check_authentication`). Only signed fields are read, the return URL must be our callback, a nonce works once, under 5 minutes old (`openid_nonces`). The callback URL must carry the value `/v1/auth/steam` put in the `sj_sign_in` cookie, tying sign-in to its browser. Refused: `/sign-in/failed`; cancelled: back where they were. +Steam OpenID sign-in uses the configured site origin for cookies and callbacks, canonicalizing aliases first. +- Steam must confirm its answer (`check_authentication`). Only signed fields are read, the return URL must be our callback, a nonce works once, within 5 minutes (`openid_nonces`). The callback must carry the value `/v1/auth/steam` put in the `sj_sign_in` cookie, tying sign-in to its browser. Refused: `/sign-in/failed`; cancelled: back where they were. - `return_to` must be a path on our site; anything else becomes `/`. -- A session is 32 random bytes in the `sj_session` cookie (`HttpOnly; Secure; SameSite=Lax`). Only the SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). -- Sign-out also requires our `Origin` header. A missing session answers `401` without `WWW-Authenticate`. -- `SJ_PUBLIC_URL` is where players reach the site; redirects and the origin check use it. +- A session is 32 random bytes in the `sj_session` cookie (`HttpOnly; Secure; SameSite=Lax`); only its SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). +- Sign-out needs our `Origin`; so does `…/sign-out-everywhere`, which ends all their sessions. A missing session gets `401` without `WWW-Authenticate`. +- `SJ_PUBLIC_URL`, where players reach the site, builds redirects and the origin check. ## Players and privileges -- Profiles take a SteamID64, SteamID2 or SteamID3 and answer with the SteamID64. Placements rank personal bests per map, style and track; equal times share a place. -- Per style, a profile counts completed maps (main tracks, out of the map list's count), completed bonuses and world records, and carries the first 50 main-track personal bests by map; `…/personal-bests?style=&tracks=main|bonuses&cursor=` pages on, and `records=true` keeps only world records (2.0 only). Without `style` it lists every style, newest first; `all_styles` counts across styles. Ranks: `main_standing`, `bonus_standing` (lead, 2026-11-04). -- `PUT /v1/players/{player}/details` (rules in `players/details.rs`): setup and a country (`GET /v1/countries`), a save per 5 s; others' need `manage_bans` and a logged reason. Old-site setup shows first. -- Avatar, country (unless the player picked one) and (until a run gives one) name come from their public Steam profile XML, fetched at sign-in and on viewing one over a day old (an hour after a failed one): one request per 2 s, 50 queued, one per player. Country names map to ISO codes in `players/countries.rs`. -- Staff privileges are a bitmap in `players.privileges` (`players/privileges.rs`). Bit positions never change; the API names privileges and never sends numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. +- Profiles take a SteamID64, SteamID2 or SteamID3 and answer with a SteamID64. +- Per style, a profile counts completed maps (main tracks, out of the map list's count), completed bonuses and world records, and carries the first 50 main-track PBs by map; `…/personal-bests?style=&tracks=main|bonuses&cursor=` pages on; `records=true` keeps only 2.0 world records. Without `style`, every style, newest first; `all_styles` counts across styles. Ranks: `main_standing`, `bonus_standing` (lead, 2026-11-04). PBs have a placement (ties share one), `tier` and `world_record_time`; profiles `tier_count`. +- `PUT /v1/players/{player}/details` (`players/details.rs`): setup and a country (`GET /v1/countries`), a save per 5 s; others' need `manage_bans` and a logged reason. Old-site setup shows first. +- Country: a run's server GeoIP code, else the player's pick (shown until the next such run), else Steam's. +- Avatar, country and (until a run gives one) name come from the public Steam profile XML, fetched at sign-in, and when a day old after a run, view or `…/avatar` (an hour after a failure): one request per 2 s, 50 queued, one per player. Country names map to ISO codes in `players/countries.rs`. +- `GET /v1/players/{player}/avatar` (`players/avatar.rs`) 302s to the stored Steam CDN avatar (cached a day); if none, fetched unpaced (4 at once, 4 s), else an initials SVG (5 min). Unknown: 404, no fetch; legacy-only: the old site's. +- Staff privileges: a bitmap in `players.privileges` (`players/privileges.rs`); bit positions never change; the API names them, never numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. ## Maps and leaderboards -- The map list holds every map with a run (`maps.last_run_at`, set by the ingest); whether one is ranked is open. Sorts: name, players, last/first run (`listed_at`), tier, main-track record; `tier` keeps one tier. `player` (any SteamID form) with `completed=true|false` keeps maps whose main track they have or haven't finished in the list's style; `completed` counts them. `stats`: tiers, 5 newest, 5 most players this week. -- Leaderboards rank personal bests per map, style and track; equal times share a place, and the earlier run is listed first. The world record of a tie belongs to whoever set it first. -- `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, so a map page switches between them without another request. `…/leaderboard?cursor=` pages on from there; cursors are opaque. -- WR history is every run faster than all runs that finished before it on that leaderboard, by `finished_at`. Ties don't count. +- Maps with runs (`maps.last_run_at`). `q` searches map names and the style's main WR holders. Sorts: name, players, last/first run (`listed_at`), tier and main WR. `tier` keeps one main tier. `player` (any SteamID) with `completed=true|false` filters the style's main completions; `completed` counts them. Global `stats` totals; newest and weekly lists take five within `stats.tier` (null: all). Weekly counts distinct players. +- Leaderboards rank PBs per map, style and track; equal times share a place, the earlier run listed first. A tie's world record belongs to whoever set it first. +- `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, for map pages to switch locally. `…/leaderboard?cursor=` pages on from there; cursors are opaque. +- WR history: every run faster than all finished before it on that board, by `finished_at`; ties don't count. - Tiers: the `tiers` policy holds the tier count, `map_tiers` the tier per map and track (append-only, newest in force). The API serves no tier until a count is published. -- Any run opens by ID with stats, server and place (while it's a personal best); compliance and keys stay private. -- Pre-2.0 runs (`legacy_*` tables, `legacy.rs`) count toward no 2.0 standing: not WRs, WR histories, placements or `…/records`. The normal style's main track has two more views, `view=all` (each player's faster of 2.0 and legacy) and `view=legacy`, on `…/leaderboard` and `…/personal-bests`; entries carry `legacy`; a legacy `run_id` is the old site's, at `GET /v1/legacy-runs/{id}` (no run page). A map's `legacy_record_history` charts the Pre-2.0 view. Banned players' legacy runs are left out. Legacy-only maps and players get pages and show in search. -- The tier count is published with the CLI's `tiers count` (it can't drop below a tier a map holds). Staff rate tracks and set images and descriptions on the map's Manage view (`/maps/{map}/manage`), or with the CLI's `maps tier` and `maps image`, logged. -- A map holds up to 10 pictures (`map_images`, in order; the first is the cover). The API reads PNG, JPEG or WebP up to 15 MB, crops to 16:9, centred (at least 1920×1080), and stores 1920×1080 and 480×270 WebP at quality 80 (`maps/image.rs`), named by content hash, cached for good, deleted with the picture. `GET /v1/maps/{map}` carries `images`, each with both URLs and `focus` (0–100, the strip a banner shows); lists carry the cover as `image`. Browsers read the files from `SJ_S3_PUBLIC_URL`; the API only writes them (ADR 0006). +- Any run opens by ID with stats, server and place (while a PB); compliance and keys stay private. +- Pre-2.0 runs (`legacy_*` tables, `legacy.rs`) count toward no 2.0 standing: not WRs, WR histories, placements or `…/records`. The normal style's main track also has `view=all` (each player's faster of 2.0 and legacy) and `view=legacy` on `…/leaderboard` and `…/personal-bests`; entries carry `legacy`; a legacy `run_id` is the old site's, at `GET /v1/legacy-runs/{id}` (no run page). A map's `legacy_record_history` charts the Pre-2.0 view. Banned players' legacy runs are left out. Legacy-only maps and players have pages and show in search. +- The CLI's `tiers count` publishes the count (never below a tier a map holds). Staff rate tracks and set images and descriptions on the map's Manage view (`/maps/{map}/manage`), or with the CLI's `maps tier` and `maps image`, logged. +- A map holds up to 10 pictures (`map_images`, ordered; first is the cover). The API takes PNG, JPEG or WebP ≤15 MB, crops to 16:9, centred (at least 1920×1080), and stores 1920×1080 and 480×270 WebP at quality 80 (`maps/image.rs`), named by content hash, cached for good, deleted with the picture. `GET /v1/maps/{map}` carries `images`, each with both URLs and `focus` (0–100, the strip a banner shows); lists carry the cover as `image`. Browsers read them from `SJ_S3_PUBLIC_URL`; the API only writes (ADR 0006). - Staff set `description` (≤1000 chars), `released` (year, month or day) and `mapper` (made if new) ## Player leaderboards - `GET /v1/leaderboards?style=&track=main|bonuses` gives, in one style and kind of track, the top 20 (`limit`) by points and by tracks completed (`leaderboards.rs`); equal shown (rounded) values share a rank. `view=legacy` ranks legacy records (one style, main tracks, the old site's tiers), banned players left out; never counted toward 2.0. `GET /v1/leaderboards/points|completed` is one list in full (`limit`, `offset`, `total`), and each player's world records in that style and kind of track (`leaderboards/list.rs`). -- Points per personal best: a map is worth `base` at tier 1, times `growth_percent` each tier up (a bonus `bonus_percent` of that at its own tier); finishing earns `finish_percent`, the rest is speed, `(WR ÷ time) ^ speed_exponent` (SQL `points_for`). Untiered tracks earn none. The `points` policy holds the values; until one is published the API uses `PointsPolicy::DRAFT` (50, 200, 50, 4, 25) and says `draft` (lead, 2026-10-26). -- Stored, not computed per visit (lead, 2026-10-26): `personal_bests.points`, `standings` (per style, main and bonuses apart) and `legacy_standings`, recounted by `leaderboards/standings.rs` where they change: a track when a personal best or its tier changes there (a new WR moves all points); everything on a points or tiers policy, or at startup if the formula changed; legacy on bans, lifts, imports. One advisory lock serializes recounts. So are world records (`leaderboards/world_records.rs`): holders and `runs.was_record`, per board. +- Points per PB: a map is worth `base` at tier 1, times `growth_percent` each tier up (a bonus `bonus_percent` of that at its own tier); finishing earns `finish_percent`, the rest is speed, `(WR ÷ time) ^ speed_exponent` (SQL `points_for`). Untiered tracks earn none. The `points` policy holds the values; until one is published the API uses `PointsPolicy::DRAFT` (50, 200, 50, 4, 25) and says `draft` (lead, 2026-10-26). +- Stored, not computed per visit (lead, 2026-10-26): `personal_bests.points`, `standings` (per style, main and bonuses apart) and `legacy_standings`, recounted by `leaderboards/standings.rs` where they change: a track when a PB or its tier changes there (a new WR moves all points); everything on a points or tiers policy, or at startup if the formula changed; legacy on bans, lifts, imports. One advisory lock serializes recounts. So are world records (`leaderboards/world_records.rs`): holders and `runs.was_record`, per board. ## Activity -- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=` (`runs/recent.rs`): valid runs newest first by `finished_at`, each with its board's tier, `placement` counted against the valid runs before it (null unless it beat the player's own best), `world_record` (as in WR history) and its `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. +- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=&offset=` (`runs/recent.rs`, with `total`): valid runs newest first by `finished_at`, each with its board's tier, `placement` against the valid runs before it (null unless a PB), `world_record` (as in WR history) and `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. ## Daily totals - `GET /v1/daily-totals/players|runs?range=month|year|all` (`daily_totals.rs`, hourly): players with a time (incl. pre-2.0), 2.0 runs and WRs per UTC day. ## Server list -- `GET /v1/servers` shows only addresses in `server_listings`, kept by staff (lead, 2026-10-20), heard from within the `servers` policy's `listed_hours` (24); `online` means within `online_minutes` (25). Without the policy the list is empty. *Connected*: the latest heartbeat had a still-valid key. Compliance and versions aren't public. `whitelist` (staff-set: only approved players join) puts it under the Whitelist tab. -- Listed servers' heartbeats also go to `server_heartbeat_log` (players, 30 days) and `server_activity_daily` (per-server UTC-day totals, 400 days). `…/activity?range=day|week|month` buckets the log (20 min, 2 h, 8 h); `year` reads the daily totals. Per bucket: servers heard from, and their average players summed. -- Staff with `manage_servers` see every server on `/servers`: unlisted ones dimmed, toggles to list or unlist and to mark whitelist, and a dialog with its last report (versions, plugins, compliance, reported IP, key), loaded in the browser, never in the server render. The CLI's `servers seen`, `servers list ` and `servers unlist ` do the same. +- `GET /v1/servers` shows only addresses in `server_listings`, kept by staff (lead, 2026-10-20), heard from within the `servers` policy's `listed_hours` (24); `online` means within `online_minutes` (25). No policy, no list. *Connected*: the latest heartbeat had a still-valid key. Compliance and versions aren't public. `whitelist` (staff-set: only approved players join) puts it under the Whitelist tab. +- Listed servers' heartbeats also go to `server_heartbeat_log` (players, 30 days) and, per UTC day for 400 days, `server_activity_daily` (per-server totals) and `server_activity_peaks`. `…/activity?range=day|week|month` buckets the log (20 min, 2 h, 8 h), `year` the daily tables. Per bucket: servers heard from, their average players summed, `peak_players` (most online at once); the top-level one, the whole range through now (never above a longer range's). +- Staff with `manage_servers` see every server on `/servers`: unlisted ones dimmed, listing and whitelist toggles, and a dialog with its last report (versions, plugins, compliance, reported IP, key), browser-loaded, never server-rendered. The CLI's `servers seen` and `servers list|unlist ` do the same. ## Community posts -- Articles (Markdown) and YouTube videos (a link with an optional note; the site links out and embeds nothing, lead 2026-10-20). Players with `post_community` post and change or remove their own; `manage_posts` edits anyone's, with a `reason` and logged (`edit_post`, fields changed) when it's someone else's and changes something. Every write needs a session and our `Origin`. -- `body_html` is rendered on each read by `posts/markdown.rs`, the only place deciding what HTML a post may contain: raw HTML becomes text, images their alt text, and links keep only web, mail and on-site addresses, opening `nofollow noopener`. -- A video link in any common form is stored as its YouTube ID (`posts/youtube.rs`), served back as a watch link. -- Pages link to `/community/{id}-{slug}`; only the ID counts, so a new title doesn't break links. Removing a post hides it and keeps the row. `DELETE /v1/posts/{post}` is for the author only. +- Articles (Markdown) and YouTube videos (a link with an optional note; the site links out and embeds nothing, lead 2026-10-20). `post_community` lets players post and change or remove their own; `manage_posts` edits anyone's, with a `reason`, logged (`edit_post`, fields changed) if someone else's and changed. Every write needs a session and our `Origin`. +- `body_html` is rendered on each read by `posts/markdown.rs`, sole judge of the HTML a post may hold: raw HTML becomes text, images their alt text, and links keep only web, mail and on-site addresses, opening `nofollow noopener`. +- Video links in any common form are stored as YouTube IDs (`posts/youtube.rs`), served as watch links. +- Pages link to `/community/{id}-{slug}`; only the ID counts, so retitling keeps links. Removal hides a post (the row stays); `DELETE /v1/posts/{post}` is the author's alone. ## Run comments - `/v1/runs/{id}/comments` (`runs/comments.rs`): players not banned from posting comment and reply one level deep (plain text, one per 30 s); the runner pins one; authors `DELETE` theirs (lead 2026-10-29). 25 threads a page, 3 replies each; more at `…/replies`. diff --git a/web/e2e/maps-cards.e2e.ts b/web/e2e/maps-cards.e2e.ts new file mode 100644 index 0000000..f600667 --- /dev/null +++ b/web/e2e/maps-cards.e2e.ts @@ -0,0 +1,305 @@ +// Map-card regressions: real podiums, complete text, responsive columns and stable image dimensions. +import { expect, test, type Locator } from "@playwright/test"; +import type { Schemas } from "../src/api/client"; +import { formatTime } from "../src/features/runs/time"; + +async function expectTextInside(card: Locator) { + const clipped = await card.evaluate((element) => { + const bounds = element.getBoundingClientRect(); + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const failures: string[] = []; + let node; + while ((node = walker.nextNode())) { + if (!node.textContent?.trim()) continue; + const range = document.createRange(); + range.selectNodeContents(node); + for (const rect of Array.from(range.getClientRects())) { + if ( + rect.left < bounds.left - 1 || + rect.right > bounds.right + 1 || + rect.top < bounds.top - 1 || + rect.bottom > bounds.bottom + 1 + ) { + failures.push(node.textContent); + } + } + } + return failures; + }); + expect(clipped).toEqual([]); +} + +test("cards show the API's top three for the chosen style", async ({ + page, + request, +}) => { + const response = await request.get("/v1/maps?limit=1&sort=popular"); + const list = (await response.json()) as Schemas["MapList"]; + const map = list.maps[0]!; + const result = await request.get( + `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=${list.style}&limit=3`, + ); + const board = (await result.json()) as Schemas["Leaderboard"]; + await page.goto("/maps"); + const card = page.locator(`[data-map="${map.name}"]`); + await expect(card).toBeVisible(); + const rows = card.locator("ol > li"); + await expect(rows).toHaveCount(board.entries.length); + for (let index = 0; index < board.entries.length; index++) { + const entry = board.entries[index]!; + await expect( + rows.nth(index).getByLabel(`Placement ${entry.rank}`), + ).toBeVisible(); + await expect( + rows.nth(index).getByText(entry.player.name, { exact: true }), + ).toBeVisible(); + await expect( + rows.nth(index).getByText(formatTime(entry.time), { exact: true }), + ).toBeVisible(); + } + await expectTextInside(card); + const preview = await card.evaluate((element) => { + const cover = element.firstElementChild!; + const image = cover.firstElementChild!; + const records = element.querySelector("ol")!; + return { + bottom: cover.getBoundingClientRect().bottom, + records: records.getBoundingClientRect().top, + mask: getComputedStyle(image).maskImage, + filter: getComputedStyle(image).filter, + }; + }); + expect(preview.bottom).toBeLessThanOrEqual(preview.records); + expect(preview.mask).toBe("none"); + expect(preview.filter).toBe("none"); +}); + +test("map hover stays still and the preview opens the map", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await card.scrollIntoViewIfNeeded(); + const before = await card.boundingBox(); + const border = await card.evaluate( + (element) => getComputedStyle(element).borderColor, + ); + await card.hover(); + expect(await card.boundingBox()).toEqual(before); + expect( + await card.evaluate((element) => getComputedStyle(element).borderColor), + ).not.toBe(border); + const href = await card.locator("h3 a").getAttribute("href"); + const preview = await card.locator(":scope > div").first().boundingBox(); + await page.mouse.click( + preview!.x + preview!.width / 2, + preview!.y + preview!.height / 2, + ); + await expect(page).toHaveURL(new RegExp(`${href}$`)); +}); + +test("player links and replay controls work independently of the map link", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => { + (window as { mapsStillHere?: boolean }).mapsStillHere = true; + }); + const replay = card + .getByRole("link", { name: "Watch replay", exact: true }) + .first(); + const href = await replay.getAttribute("href"); + const id = /\/runs\/(\d+)/.exec(href!)![1]; + await replay.click(); + await expect(page).toHaveURL(new RegExp(`/maps\\?replay=${id}$`)); + const dialog = page.getByRole("dialog"); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("link", { name: "Run page" })).toHaveAttribute( + "href", + `/runs/${id}`, + ); + expect( + await page.evaluate( + () => (window as { mapsStillHere?: boolean }).mapsStillHere, + ), + ).toBe(true); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(page).toHaveURL(/\/maps$/); + await expect(replay).toBeFocused(); + const player = card + .locator("ol > li") + .first() + .locator('a[href^="/players/"]'); + await expect( + card.locator("ol > li").first().locator('a[href^="/players/"]'), + ).toHaveCount(1); + const profile = await player.getAttribute("href"); + const avatar = player.locator(":scope > span").first(); + const name = player.locator(":scope > span").nth(1); + const color = await name.evaluate( + (element) => getComputedStyle(element).color, + ); + const avatarBorder = await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor); + await avatar.hover(); + await expect + .poll(() => name.evaluate((element) => getComputedStyle(element).color)) + .not.toBe(color); + expect( + await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor), + ).toBe(avatarBorder); + await avatar.click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await page.goBack(); + await player.locator(":scope > span").nth(1).click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await expect(dialog).toBeHidden(); +}); + +test("cards keep complete names and long times inside at every breakpoint", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await card.evaluate((element) => { + element.querySelector("h3 a")!.textContent = + "bhop_" + "long_map_name_".repeat(5).slice(0, 59); + for (const row of Array.from(element.querySelectorAll("ol > li"))) { + const player = row.querySelector('a[href^="/players/"]')!; + const result = row.lastElementChild!; + player.children[1]!.textContent = + "Long player name 玩家 日本語 Кириллица"; + result.children[0]!.querySelector("a")!.textContent = "1:23:45.678"; + result.children[1]!.textContent = "+2:34:56.789"; + } + }); + for (const width of [1920, 1440, 1084, 1080, 1024, 768, 390, 320]) { + await page.setViewportSize({ width, height: 1000 }); + await expectTextInside(card); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + const layout = await card.evaluate((element) => ({ + width: element.clientWidth, + result: getComputedStyle( + element.querySelector("ol > li > span:last-child")!, + ).display, + })); + expect(layout.result).toBe(layout.width >= 320 ? "grid" : "flex"); + if (width === 1920 || width === 1440) { + const columns = await card + .locator("xpath=../..") + .evaluate( + (element) => + getComputedStyle(element).gridTemplateColumns.split(" ").length, + ); + expect(columns).toBe(width === 1920 ? 4 : 3); + } + } +}); + +test("loading avatars and map pictures does not move the podium", async ({ + page, +}) => { + await page.route( + /avatars(?:\.[a-z]+)?\.steamstatic\.com|\/v1\/players\/[^/]+\/avatar/, + (route) => route.abort(), + ); + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + const before = await card.locator("ol").boundingBox(); + await card + .locator("img") + .evaluateAll((images) => + Promise.all( + images.map((image) => + (image as HTMLImageElement).decode().catch(() => {}), + ), + ), + ); + expect(await card.locator("ol").boundingBox()).toEqual(before); + await expect(card.locator("ol img")).toHaveCount(0); + await expectTextInside(card); +}); + +test("a single finisher and an empty style stay honest and readable", async ({ + page, + request, +}) => { + let selected: { list: Schemas["MapList"]; style: string } | undefined; + for (const style of ["scroll", "hsw"]) { + const response = await request.get(`/v1/maps?style=${style}&limit=100`); + if (!response.ok()) continue; + const list = (await response.json()) as Schemas["MapList"]; + if ( + list.style === style && + list.maps.some((map) => !map.world_record) && + list.maps.some((map) => map.world_record) + ) { + selected = { list, style }; + break; + } + } + test.skip( + !selected, + "The current API data has no style with both empty and populated boards.", + ); + const { list, style } = selected!; + const empty = list.maps.find((map) => !map.world_record)!; + await page.setViewportSize({ width: 390, height: 900 }); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(empty.name)}`); + const emptyCard = page.locator(`[data-map="${empty!.name}"]`); + await expect( + emptyCard.getByText("No times in this style", { exact: true }), + ).toBeVisible(); + await expect(emptyCard.getByLabel("Placement 1")).toHaveCount(0); + await expectTextInside(emptyCard); + await expect(emptyCard.locator("h3 a")).toHaveAttribute( + "href", + `/maps/${empty.name}?style=${style}`, + ); + + // Pick an actual sparse board rather than inventing second and third place. + let single: string | undefined; + for (const map of list.maps + .filter((map) => map.world_record) + .sort((a, b) => a.players - b.players) + .slice(0, 6)) { + const response = await request.get( + `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=${style}&limit=3`, + ); + const board = (await response.json()) as Schemas["Leaderboard"]; + if (board.total === 1) { + single = map.name; + break; + } + } + test.skip( + !single, + "The current API data has no sampled board with one finisher.", + ); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(single!)}`); + const singleCard = page.locator(`[data-map="${single}"]`); + await expect(singleCard.locator("ol > li")).toHaveCount(1); + await expect(singleCard.getByText(/ranked times? in this style/)).toHaveCount( + 0, + ); + await expect(singleCard.getByLabel("Placement 1")).toBeVisible(); + await expect(singleCard.getByLabel("Placement 2")).toHaveCount(0); + await expectTextInside(singleCard); +}); diff --git a/web/e2e/maps-overview.e2e.ts b/web/e2e/maps-overview.e2e.ts new file mode 100644 index 0000000..5529378 --- /dev/null +++ b/web/e2e/maps-overview.e2e.ts @@ -0,0 +1,342 @@ +// Regression checks for the Maps overview's alignment and filtered layouts. +import { expect, test, type Locator } from "@playwright/test"; +import type { Schemas } from "../src/api/client"; + +async function expectAligned(overview: Locator) { + const geometry = await overview.evaluate((element) => { + const nav = element.querySelector("nav")!; + const links = nav.querySelectorAll("li a"); + const reset = nav.querySelector("a")!.getBoundingClientRect(); + const first = links[0]!.firstElementChild!.getBoundingClientRect(); + const last = + links[links.length - 1]!.lastElementChild!.getBoundingClientRect(); + const panel = element.getBoundingClientRect(); + const graph = element.querySelector("svg")!.getBoundingClientRect(); + const legend = nav.getBoundingClientRect(); + const center = (rect: DOMRect) => rect.y + rect.height / 2; + return { + left: Math.abs(reset.left - first.left), + right: Math.abs(reset.right - last.right), + graph: Math.abs(center(graph) - center(panel)), + legend: Math.abs(center(legend) - center(panel)), + headings: Array.from(element.querySelectorAll("section h2")).map( + (heading) => heading.getBoundingClientRect().top, + ), + }; + }); + expect(geometry.left).toBeLessThan(1); + expect(geometry.right).toBeLessThan(1); + expect(geometry.graph).toBeLessThan(1); + expect(geometry.legend).toBeLessThan(1); + for (const top of geometry.headings) { + expect(Math.abs(top - geometry.headings[0]!)).toBeLessThan(1); + } +} + +test("the overview stays centered and the reset matches the tier columns", async ({ + page, +}) => { + await page.goto("/maps"); + const overview = page.getByRole("region", { + name: "Map overview", + exact: true, + }); + const nav = overview.getByRole("navigation", { name: "Filter maps by tier" }); + await expect(nav).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await expectAligned(overview); + + // The page name remains available to screen readers without adding a visible heading. + const heading = await page + .getByRole("heading", { name: "Maps", exact: true }) + .boundingBox(); + expect(heading!.height).toBeLessThanOrEqual(1); + + const reset = nav.getByRole("link", { name: /All tiers/ }); + const firstTier = nav.locator("li a").first(); + const bounds = await firstTier.boundingBox(); + await firstTier.hover(); + expect(await firstTier.boundingBox()).toEqual(bounds); + await reset.focus(); + await page.keyboard.press("Tab"); + await expect(firstTier).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(firstTier).toHaveAttribute("aria-current", "true"); + await expectAligned(overview); + await reset.click(); + await expect(reset).toHaveAttribute("aria-current", "true"); + await expectAligned(overview); + + await page.setViewportSize({ width: 1920, height: 1000 }); + const spacing = await overview.evaluate((element) => { + const groups = Array.from(element.querySelectorAll("section")); + return { + trailing: + element.getBoundingClientRect().right - + groups[groups.length - 1]!.getBoundingClientRect().right, + columnGaps: groups.map( + (group) => + group.getBoundingClientRect().right - + (group.querySelector("ul") ?? group).getBoundingClientRect().right, + ), + }; + }); + expect(spacing.trailing).toBeLessThanOrEqual(21); + for (const gap of spacing.columnGaps) expect(gap).toBeLessThan(1); + const controls = await overview.locator("xpath=../..").evaluate((element) => { + const frame = element + .querySelector('[aria-label="Map overview"]')! + .parentElement!.getBoundingClientRect(); + const input = element + .querySelector('input[type="search"]')! + .getBoundingClientRect(); + const buttons = element.querySelectorAll('button[aria-haspopup="menu"]'); + const first = buttons[0]!.getBoundingClientRect(); + const gallery = document + .querySelector("[data-map]")! + .closest("section")! + .getBoundingClientRect(); + return { + searchWidth: input.width, + left: Math.abs(first.left - gallery.left), + right: Math.abs(input.right - gallery.right), + separated: input.top - frame.bottom, + frameCenter: Math.abs( + (frame.left + frame.right - gallery.left - gallery.right) / 2, + ), + frameWidth: frame.width, + pageWidth: gallery.width, + }; + }); + expect(controls.searchWidth).toBeLessThanOrEqual(320); + expect(controls.left).toBeLessThan(1); + expect(controls.right).toBeLessThan(1); + expect(controls.separated).toBeGreaterThanOrEqual(20); + expect(controls.frameCenter).toBeLessThan(1); + expect(controls.frameWidth).toBeLessThan(controls.pageWidth); +}); + +test("the donut has clean sector boundaries, animates hover and has no click focus box", async ({ + page, +}) => { + await page.emulateMedia({ reducedMotion: "no-preference" }); + await page.goto("/maps"); + const chart = page.getByRole("img", { name: /Maps per tier/ }); + await expect(chart).toBeVisible(); + const geometry = await chart.evaluate((svg) => { + const rect = svg.getBoundingClientRect(); + const reset = svg.parentElement!.querySelector("nav > a")!.textContent!; + const total = Number(reset.match(/([\d,]+) maps/)![1]!.replaceAll(",", "")); + const links = Array.from(svg.querySelectorAll("a")); + const count = Number( + links[0]! + .getAttribute("aria-label")! + .match(/: ([\d,]+) maps/)![1]! + .replaceAll(",", ""), + ); + const angle = (((((count / total) * 100) / 2) * 3.6 - 90) * Math.PI) / 180; + const hit = (share: number, radius: number) => { + const angle = (share / 100) * Math.PI * 2 - Math.PI / 2; + return ( + document + .elementFromPoint( + rect.x + rect.width * (0.5 + (radius / 100) * Math.cos(angle)), + rect.y + rect.height * (0.5 + (radius / 100) * Math.sin(angle)), + ) + ?.closest("svg a") + ?.getAttribute("aria-label") ?? null + ); + }; + let start = 0; + const samples = links.map((link) => { + const label = link.getAttribute("aria-label")!; + const count = Number( + label.match(/: ([\d,]+) maps/)![1]!.replaceAll(",", ""), + ); + const length = (count / total) * 100; + const sample = { + label, + middle: [33, 40, 47].map((radius) => hit(start + length / 2, radius)), + seam: + length === 100 + ? [] + : [33, 40, 47].map((radius) => hit(start, radius)), + }; + start += length; + return sample; + }); + return { + samples, + x: rect.x + rect.width * (0.5 + 0.4 * Math.cos(angle)), + y: rect.y + rect.height * (0.5 + 0.4 * Math.sin(angle)), + }; + }); + for (const sample of geometry.samples) { + for (const middle of sample.middle) expect(middle).toBe(sample.label); + for (const seam of sample.seam) expect(seam).toBeNull(); + } + const highlight = chart.locator("a").first().locator("path").last(); + await expect(highlight).toHaveCSS("opacity", "0"); + await page.mouse.move(geometry.x, geometry.y); + const hovered = await chart + .locator("a") + .first() + .locator("path") + .last() + .evaluate(async (path) => { + await Promise.all( + path.getAnimations().map((animation) => animation.finished), + ); + const style = getComputedStyle(path); + return { + transition: style.transitionProperty, + duration: parseFloat(style.transitionDuration), + }; + }); + await expect(highlight).toHaveCSS("opacity", "1"); + expect(hovered.transition).toContain("opacity"); + expect(hovered.duration).toBeGreaterThan(0); + await page.mouse.click(geometry.x, geometry.y); + await expect(chart.locator("text").first()).not.toHaveText("All"); + expect( + await chart + .locator("a") + .first() + .evaluate((link) => getComputedStyle(link).outlineStyle), + ).toBe("none"); +}); + +test("a filtered short list is centered and its details stay beside the names", async ({ + page, + request, +}) => { + const response = await request.get("/v1/maps?limit=1"); + expect(response.ok()).toBe(true); + const { stats } = (await response.json()) as { stats: Schemas["MapStats"] }; + const tier = + stats.by_tier.findIndex((_, index) => { + const newest = stats.newest.filter( + (map) => map.tier === index + 1, + ).length; + const played = stats.played_this_week.filter( + (map) => map.tier === index + 1, + ).length; + return ( + (newest > 0 && newest < 5 && played === 0) || + (played > 0 && played < 5 && newest === 0) + ); + }) + 1; + test.skip( + tier === 0, + "The current API data has no tier with just one short summary list.", + ); + + await page.goto("/maps"); + const headingPositions = await page + .getByRole("region", { name: "Map overview", exact: true }) + .locator("section") + .evaluateAll((sections) => + Object.fromEntries( + sections.map((section) => [ + section.getAttribute("aria-label"), + section.querySelector("h2")!.getBoundingClientRect().top, + ]), + ), + ); + + await page.goto(`/maps?tier=${tier}`); + const overview = page.getByRole("region", { + name: "Map overview", + exact: true, + }); + await expect(overview.getByRole("navigation")).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await expectAligned(overview); + const filteredHeading = await overview + .locator("section:has(ul)") + .first() + .evaluate((section) => ({ + name: section.getAttribute("aria-label")!, + top: section.querySelector("h2")!.getBoundingClientRect().top, + })); + expect( + Math.abs(filteredHeading.top - headingPositions[filteredHeading.name]), + ).toBeLessThan(1); + const list = overview.locator("section:has(ul)").first().locator("ul"); + await expect(list).toHaveCount(1); + const layout = await list.evaluate((element) => + Array.from(element.querySelectorAll("a")).map((row) => { + const name = row.children[1]!.getBoundingClientRect(); + const detail = row.children[2]!.getBoundingClientRect(); + return { + width: row.getBoundingClientRect().width, + gap: detail.left - name.right, + top: Math.abs(detail.top - name.top), + }; + }), + ); + for (const row of layout) { + expect(row.width).toBeLessThan(250); + expect(Math.abs(row.gap - 8)).toBeLessThan(1); + expect(row.top).toBeLessThan(1); + } +}); + +test("the compact legend fits a narrow phone without changing its reset alignment", async ({ + page, +}) => { + await page.setViewportSize({ width: 320, height: 900 }); + await page.goto("/maps"); + const nav = page.getByRole("navigation", { name: "Filter maps by tier" }); + await expect(nav).toBeVisible(); + const edges = await nav.evaluate((element) => { + const reset = element.querySelector("a")!.getBoundingClientRect(); + const links = element.querySelectorAll("li a"); + return { + left: + reset.left - links[0]!.firstElementChild!.getBoundingClientRect().left, + right: + reset.right - + links[links.length - 1]!.lastElementChild!.getBoundingClientRect() + .right, + overflow: document.documentElement.scrollWidth > innerWidth, + }; + }); + expect(Math.abs(edges.left)).toBeLessThan(1); + expect(Math.abs(edges.right)).toBeLessThan(1); + expect(edges.overflow).toBe(false); +}); + +test("searching a WR holder shows their maps", async ({ page, request }) => { + const response = await request.get("/v1/maps?limit=100"); + expect(response.ok()).toBe(true); + const all = (await response.json()) as Schemas["MapList"]; + const holder = all.maps.find((map) => map.world_record)?.world_record?.player + .name; + test.skip( + !holder, + "The current data has no world record holders to search for.", + ); + const matches = await request.get( + `/v1/maps?q=${encodeURIComponent(holder!)}&sort=popular`, + ); + expect(matches.ok()).toBe(true); + const filtered = (await matches.json()) as Schemas["MapList"]; + expect(filtered.total).toBeGreaterThan(0); + + await page.goto("/maps"); + await page + .getByRole("searchbox", { + name: "Search maps, WR holders, or enter a SteamID", + exact: true, + }) + .fill(holder!); + await expect(page).toHaveURL((url) => url.searchParams.get("q") === holder); + const cards = page.locator("[data-map]"); + await expect(cards).toHaveCount(filtered.maps.length); + expect( + await cards.evaluateAll((elements) => + elements.map((element) => element.getAttribute("data-map")), + ), + ).toEqual(filtered.maps.map((map) => map.name)); +}); diff --git a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png index 626adf1..a395a37 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png index 7d042cf..f88f6c4 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png index e100367..5e728d7 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png index de65fcc..17c8df7 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png differ diff --git a/web/next.config.ts b/web/next.config.ts index bbe0a26..4ca998d 100644 --- a/web/next.config.ts +++ b/web/next.config.ts @@ -29,6 +29,8 @@ const nextConfig: NextConfig = { turbopack: { rules: { "*.css": { + // CSS Modules use Next's native pipeline; rewriting their extension would lose the class exports. + condition: { not: { path: "*.module.css" } }, loaders: ["@tailwindcss/turbopack"], as: "*.css", }, diff --git a/web/package-lock.json b/web/package-lock.json index b4ea69f..a292a4d 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -8,7 +8,7 @@ "name": "sourcejump-web", "version": "0.1.0", "dependencies": { - "flag-icons": "7.6.0", + "country-flag-icons": "1.6.20", "gl-matrix": "3.4.4", "lucide-react": "1.67.0", "lzma1": "0.7.0", @@ -3394,6 +3394,12 @@ "dev": true, "license": "MIT" }, + "node_modules/country-flag-icons": { + "version": "1.6.20", + "resolved": "https://registry.npmjs.org/country-flag-icons/-/country-flag-icons-1.6.20.tgz", + "integrity": "sha512-py8JiEKzjhYw6HPJ0L7SxLgCYim36UPRTZX43/kqGueUCZLSvnrqAiwW8HtQibur7mdkFQUkjOgdK+o/9FBtaw==", + "license": "MIT" + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -4364,12 +4370,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/flag-icons": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/flag-icons/-/flag-icons-7.6.0.tgz", - "integrity": "sha512-hir/PsXwr0EESyizKrXJzmkzpLIMf+1vlNKLqAfvdh+bsU94a7LYWTiubkHKqptGoCPzOUGcm6c4PfC9/BaGSQ==", - "license": "MIT" - }, "node_modules/flat-cache": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", diff --git a/web/package.json b/web/package.json index e3cd268..366916b 100644 --- a/web/package.json +++ b/web/package.json @@ -16,7 +16,7 @@ "test:ui": "playwright test" }, "dependencies": { - "flag-icons": "7.6.0", + "country-flag-icons": "1.6.20", "gl-matrix": "3.4.4", "lucide-react": "1.67.0", "lzma1": "0.7.0", diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index 239e647..a6b0e3b 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -55,6 +55,27 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/auth/sign-out-everywhere": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Ends every session of the signed-in player, in every browser, and signs this one out. A form on the + * website posts here. Unlike signing out, it needs a live session: answering a request without one as if it + * had worked would tell the player their other browsers were signed out when nothing was ended. + */ + post: operations["sign_out_everywhere"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/auth/steam": { parameters: { query?: never; @@ -245,6 +266,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/maps/{map}/personal-bests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * These players' SourceJump personal bests on the map, every style and track. An unknown map, or players + * without runs on it, give an empty list. + */ + get: operations["players_personal_bests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/maps/{map}/records": { parameters: { query?: never; @@ -353,6 +394,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/players/{player}/avatar": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Redirects to the player's Steam avatar. Takes a `SteamID64`, `SteamID2` or `SteamID3`. Only players + * SourceJump knows are looked up on Steam; a player known only from the old site gets the avatar it had. + */ + get: operations["player_avatar"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/players/{player}/details": { parameters: { query?: never; @@ -1446,6 +1507,13 @@ export interface components { * @description Where the bucket starts. */ at: string; + /** + * Format: int32 + * @description The most players online at once during the bucket, across listed servers: each server's latest + * heartbeat count, summed at the same moment. Up to a month, sampled every 5 minutes; for a year, the + * day's highest total at any heartbeat. + */ + peak_players: number; /** * Format: int32 * @description The average player count of each of those servers during the bucket, summed. @@ -1537,7 +1605,10 @@ export interface components { /** @description New details for a profile. Every field is replaced: leave one out or null to clear it. */ DetailsInput: { aspect?: components["schemas"]["Aspect"] | null; - /** @description An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's. */ + /** + * @description An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one; + * null to stop showing the player's pick. + */ country_code?: string | null; /** * Format: int32 @@ -2147,7 +2218,7 @@ export interface components { /** @description Sorted by style, track and rank. One flat list keeps it simple to read in SourcePawn. */ records: components["schemas"]["Record"][]; }; - /** @description The whole list at a glance, whatever the search or filter. */ + /** @description Global totals and tier-scoped newest and weekly lists. */ MapStats: { /** * @description Of those, the maps whose main track has each tier, tier 1 first. Empty until a tier count is @@ -2163,6 +2234,11 @@ export interface components { newest: components["schemas"]["NewestMap"][]; /** @description The maps the most players finished a run on in the last 7 days, most first. */ played_this_week: components["schemas"]["PlayedMap"][]; + /** + * Format: int32 + * @description The tier the newest and weekly lists describe; None describes all tiers. Totals remain global. + */ + tier?: number | null; }; MapStyle: { /** @description The top of the leaderboard, so a map page can switch styles and tracks without asking again. */ @@ -2266,6 +2342,12 @@ export interface components { /** Format: int64 */ run_id: number; style: string; + /** + * Format: int32 + * @description The board's tier. None while tiers aren't in force or staff haven't set this board's, and for a legacy + * run. + */ + tier?: number | null; /** * Format: double * @description Seconds. @@ -2276,6 +2358,12 @@ export interface components { * @description 0 is the main track, 1 and up are bonuses. */ track: number; + /** + * Format: double + * @description The board's 2.0 record time, as on its map leaderboard, so a client can show the gap to it. None for a + * legacy run. + */ + world_record_time?: number | null; }; PersonalBestPage: { /** @description Pass as `cursor` for the personal bests after these. None at the end. */ @@ -2324,6 +2412,30 @@ export interface components { PlayerList: { players: components["schemas"]["PlayerSummary"][]; }; + PlayerPersonalBest: { + /** Format: date-time */ + finished_at: string; + /** + * Format: int64 + * @description Place on the leaderboard; equal times share a place, as in `…/records`. + */ + rank: number; + /** Format: int64 */ + run_id: number; + /** @description SteamID64, as a string. */ + steamid64: string; + style: string; + /** + * Format: double + * @description Seconds. + */ + time: number; + /** + * Format: int32 + * @description 0 is the main track, 1 and up are bonuses. + */ + track: number; + }; PlayerPrivileges: { /** @description What the player holds after the change. */ privileges: components["schemas"]["Privilege"][]; @@ -2335,9 +2447,12 @@ export interface components { */ all_styles: components["schemas"]["StyleTotals"]; avatar_url?: string | null; - /** @description Whether the player picked `country_code` themselves, rather than it coming from Steam. */ + /** @description Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam. */ country_chosen: boolean; - /** @description ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one. */ + /** + * @description ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it + * since, or else their Steam profile's. None if none has one. + */ country_code?: string | null; details?: components["schemas"]["PlayerDetails"] | null; /** @description Whether `details` are what they had on the old site, shown until they save their own. */ @@ -2368,6 +2483,12 @@ export interface components { steamid64: string; /** @description One entry per style they hold a personal best in, sorted by style key. Counts are 2.0 alone. */ styles: components["schemas"]["PlayerStyle"][]; + /** + * Format: int32 + * @description Number of tiers in force; None while the community hasn't set tiers, and personal bests then have no + * tier. + */ + tier_count?: number | null; }; /** * @description A player as leaderboards, records and runs show them: enough to draw their name, avatar and flag, and to @@ -2444,6 +2565,14 @@ export interface components { */ players: number; }; + PlayersPersonalBests: { + map: string; + /** + * @description Sorted by player, style and track. A player with no personal best on the map has no entries. One flat + * list keeps it simple to read in SourcePawn. + */ + personal_bests: components["schemas"]["PlayerPersonalBest"][]; + }; /** @description A published `sourcejump.smx` build. */ PluginRelease: { download_url: string; @@ -2657,6 +2786,11 @@ export interface components { * @description Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier. */ tier_count?: number | null; + /** + * Format: int64 + * @description How many runs match the filters, across all pages. + */ + total: number; }; Record: { /** Format: date-time */ @@ -2992,6 +3126,14 @@ export interface components { world_record_time?: number | null; }; RunPlayer: { + /** + * @description The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO + * 3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It + * becomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored + * anyway. Runs only: detections ignore it. + * @example SE + */ + country_code?: string | null; name: string; /** @example 76561197960287930 */ steamid64: string; @@ -3110,6 +3252,13 @@ export interface components { ServerActivity: { /** Format: int32 */ bucket_minutes: number; + /** + * Format: int32 + * @description The most players online at once across listed servers over the whole range, from the start of its + * first point up to now, the bucket in progress included: no point reads higher, and a shorter range never + * reads higher than a longer one. + */ + peak_players: number; /** * @description Oldest first, one per bucket, empty buckets included. The bucket still in progress is left out, so the * last point isn't a partial count. @@ -3559,6 +3708,45 @@ export interface operations { }; }; }; + sign_out_everywhere: { + parameters: { + query?: { + /** @description The page to come back to: a path on this site, such as `/maps`. Anything else means `/`. */ + return_to?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Back to the page the player came from, signed out everywhere */ + 303: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Not signed in; no session was ended */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not sent from SourceJump's own pages */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; start: { parameters: { query?: { @@ -3774,9 +3962,9 @@ export interface operations { parameters: { query?: { /** - * @description Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - * name comes first, then maps with a word starting with it, then other matches, each in the chosen - * sort; near misses for a typo come last, closest first. + * @description Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + * matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + * other map matches and record holders, each in the chosen sort; near misses come last. */ q?: string | null; /** @description Default `name`. */ @@ -3918,6 +4106,49 @@ export interface operations { }; }; }; + players_personal_bests: { + parameters: { + query: { + /** @description Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once. */ + players: string; + }; + header?: never; + path: { + /** @description Map name */ + map: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PlayersPersonalBests"]; + }; + }; + /** @description Missing, unknown or revoked API key */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not a valid map name, or `players` isn't 1 to 64 SteamID64s */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; map_records: { parameters: { query?: { @@ -4144,6 +4375,56 @@ export interface operations { }; }; }; + player_avatar: { + parameters: { + query?: never; + header?: never; + path: { + /** @description SteamID64, SteamID2 (STEAM_0:1:2) or SteamID3 ([U:1:4]) */ + player: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description No avatar yet: a placeholder with the player's initials, cached five minutes */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "image/svg+xml": string; + }; + }; + /** @description To the avatar on Steam's CDN; cached a day */ + 302: { + headers: { + /** @description The avatar's URL */ + Location?: string; + [name: string]: unknown; + }; + content?: never; + }; + /** @description SourceJump has no such player */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not a SteamID */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; update_player_details: { parameters: { query?: never; @@ -4688,6 +4969,8 @@ export interface operations { records?: boolean | null; /** @description 1 to 100. Default 50. */ limit?: number | null; + /** @description Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given. */ + offset?: number | null; /** @description Continue after this point: a `next_cursor` from an earlier page with the same filters. */ cursor?: string | null; }; @@ -4705,7 +4988,7 @@ export interface operations { "application/json": components["schemas"]["RecentRuns"]; }; }; - /** @description Not a valid tier, limit or cursor */ + /** @description Not a valid tier, limit, offset or cursor */ 422: { headers: { [name: string]: unknown; diff --git a/web/src/app/activity/page.tsx b/web/src/app/activity/page.tsx index 7de643e..4f3fd7e 100644 --- a/web/src/app/activity/page.tsx +++ b/web/src/app/activity/page.tsx @@ -1,5 +1,5 @@ -// Activity page: runs and world records per day, then the latest runs, narrowed by style, track, lowest tier or -// world records only. +// Activity page: one board. Runs and world records per day, then the latest runs, narrowed by style, track, +// lowest tier or world records only. import type { Metadata } from "next"; import { RecentRuns } from "@/features/activity/RecentRuns"; import { DailyTotals } from "@/features/dailyTotals/DailyTotals"; @@ -12,19 +12,21 @@ export const metadata: Metadata = { export default function ActivityPage({ searchParams }: PageProps<"/activity">) { return ( - -

Activity

- - {searchParams.then(({ style, track, tier, show }) => ( - - ))} + +
+ + {searchParams.then(({ style, track, tier, show, page }) => ( + + ))} +
); } diff --git a/web/src/app/dev/ui/page.tsx b/web/src/app/dev/ui/page.tsx index dbd7fa0..3c14e9c 100644 --- a/web/src/app/dev/ui/page.tsx +++ b/web/src/app/dev/ui/page.tsx @@ -146,7 +146,8 @@ export default function StyleGuidePage() {

- Play for everything. Its digits share one width, so times line up: + Geist for everything; times and tables use its equal-width digits, so + they line up:

{typeScale.map(([name, className]) => ( @@ -162,14 +163,19 @@ export default function StyleGuidePage() {
- - - + + - +
diff --git a/web/src/app/error.tsx b/web/src/app/error.tsx new file mode 100644 index 0000000..b33d5cd --- /dev/null +++ b/web/src/app/error.tsx @@ -0,0 +1,36 @@ +"use client"; +// The page for an unexpected failure while showing any page below the root layout, so the header and footer stay +// and the player can try again or move on, instead of a blank error screen. +import { useEffect } from "react"; +import { Button, ButtonLink } from "@/ui/Button"; +import { Page } from "@/ui/Page"; + +export default function ErrorPage({ + error, + retry, +}: { + error: unknown; + retry: () => void; +}) { + useEffect(() => { + // The server logs its own failures; this keeps the browser's in its console for whoever reports one. + console.error(error); + }, [error]); + + return ( + +
+

Something went wrong

+

+ This page couldn't be shown. Try again, or come back in a moment. +

+
+ + Go to the home page +
+
+
+ ); +} diff --git a/web/src/app/globals.css b/web/src/app/globals.css index 8bdcfec..36e617d 100644 --- a/web/src/app/globals.css +++ b/web/src/app/globals.css @@ -4,6 +4,17 @@ @import "../ui/motion.css"; @layer base { + /* Taps show the site's own pressed and hover states, not the browser's grey flash, and act without the + double-tap zoom delay. */ + html { + -webkit-tap-highlight-color: transparent; + } + a, + button, + [role="button"] { + touch-action: manipulation; + } + /* Tailwind leaves buttons with the default arrow; everything clickable here shows the hand. */ button:not(:disabled), [role="button"]:not([aria-disabled="true"]), @@ -12,15 +23,18 @@ cursor: pointer; } + /* The window either side of the sheet; pages sit on the sheet (the root layout). */ body { - background: var(--color-bg); + background: var(--color-gutter); color: var(--color-text); font-family: var(--font-sans); + font-weight: var(--font-weight-normal); font-size: var(--text-base); line-height: var(--text-base--line-height); } - /* Play's figures are already equal width; this keeps times aligned if a fallback font is in use. */ + /* Geist's figures differ in width; times and table cells take its equal-width ones so columns line up. Elsewhere + they stay proportional, which is as wide as Play's were. */ time, td { font-variant-numeric: tabular-nums; diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx index 07418f3..71fcdae 100644 --- a/web/src/app/layout.tsx +++ b/web/src/app/layout.tsx @@ -1,16 +1,24 @@ // Root layout: fonts, global styles, the header and footer, the run dialog, and site-wide metadata. import type { Metadata } from "next"; -import { Play } from "next/font/google"; +import Image from "next/image"; +import { Exo_2, Geist } from "next/font/google"; import { Suspense } from "react"; +import art from "@/features/site/header-interloper.webp"; import { RunDialogHost } from "@/features/runs/RunDialogHost"; import { SiteFooter } from "@/features/site/SiteFooter"; import { SiteHeader } from "@/features/site/SiteHeader"; import { NavigationProgress } from "@/ui/NavigationProgress"; import "./globals.css"; -const play = Play({ - variable: "--font-play", - weight: ["400", "700"], +// A variable font, so the in-between weights the type tokens use (tokens.css) load in the one file. +const geist = Geist({ + variable: "--font-geist", + subsets: ["latin", "latin-ext", "cyrillic"], +}); +// Game servers' names (the `font-server` token): a bold face with more character than Geist, in its one weight. +const exo = Exo_2({ + variable: "--font-exo", + weight: "700", subsets: ["latin", "latin-ext", "cyrillic"], }); @@ -25,17 +33,39 @@ export const instant = false; export default function RootLayout({ children }: LayoutProps<"/">) { return ( - + - {/* The header and page fill at least the window, so the footer starts right at the fold: the page - always scrolls, and the scrollbar doesn't come and go between short and long pages. The space - above the footer is padding in here, not a margin on the footer, so it doesn't push it lower. */} -
- -
{children}
+ {/* What shows in the gutters either side of the sheet: the header's map picture, blurred and darkened + far back, fixed while the page scrolls. Blurred anyway, so a small copy of it is plenty. */} +
+ +
+
+ {/* The sheet, as the old sourcejump.net had it: one column down the middle of the window, edges lit, + holding the header, the page and the footer, the gutters either side. */} +
+ {/* The header and page fill at least the window, so the footer starts right at the fold: the page + always scrolls, and the scrollbar doesn't come and go between short and long pages. The space + above the footer is padding in here, not a margin on the footer, so it doesn't push it lower. */} +
+ +
{children}
+
+
- {/* The run dialog, over whichever page opened it (`?run=` in the address). */} diff --git a/web/src/app/leaderboards/[ranking]/page.tsx b/web/src/app/leaderboards/[ranking]/page.tsx index a8f5854..ccedbc6 100644 --- a/web/src/app/leaderboards/[ranking]/page.tsx +++ b/web/src/app/leaderboards/[ranking]/page.tsx @@ -31,7 +31,7 @@ export default function LeaderboardListPage({ return ( {Promise.all([params, searchParams]).then( - ([{ ranking }, { style, track, view }]) => { + ([{ ranking }, { style, track, view, page }]) => { if (!rankings.includes(ranking)) notFound(); return ( ); }, diff --git a/web/src/app/leaderboards/page.tsx b/web/src/app/leaderboards/page.tsx index 4c706ff..80efa69 100644 --- a/web/src/app/leaderboards/page.tsx +++ b/web/src/app/leaderboards/page.tsx @@ -1,4 +1,5 @@ -// Leaderboards page: the top players by points and by completions, per style and track, and pre-2.0. +// Leaderboards page: the top players by points and by completions, per style and track, and pre-2.0, each list +// paged on its own. import type { Metadata } from "next"; import { Leaderboards } from "@/features/leaderboards/Leaderboards"; import { Page } from "@/ui/Page"; @@ -12,17 +13,24 @@ export default function LeaderboardsPage({ searchParams, }: PageProps<"/leaderboards">) { return ( - +

Leaderboards

- {searchParams.then(({ style, track, view }) => ( - - ))} + {searchParams.then( + ({ style, track, view, points_page, completed_page }) => ( + + ), + )}
); } diff --git a/web/src/app/maps/[map]/layout.tsx b/web/src/app/maps/[map]/layout.tsx index e5ba9bf..432becd 100644 --- a/web/src/app/maps/[map]/layout.tsx +++ b/web/src/app/maps/[map]/layout.tsx @@ -7,7 +7,7 @@ export default function MapLayout({ children, }: LayoutProps<"/maps/[map]">) { return ( - + {params.then(({ map }) => ( ))} diff --git a/web/src/app/maps/[map]/page.tsx b/web/src/app/maps/[map]/page.tsx index 91c6490..abed4d4 100644 --- a/web/src/app/maps/[map]/page.tsx +++ b/web/src/app/maps/[map]/page.tsx @@ -1,12 +1,19 @@ // A map's page: its description, leaderboards per style and track, and their WR history, under the map's header. import type { Metadata } from "next"; +import { getMap } from "@/features/maps/mapDetail"; +import { mapPreview } from "@/features/maps/mapPreview"; import { MapView } from "@/features/maps/MapView"; +import { currentStyles } from "@/features/ruleset/styles"; import { PageView } from "@/ui/Page"; export async function generateMetadata({ params, }: PageProps<"/maps/[map]">): Promise { - return { title: decodeURIComponent((await params).map) }; + const name = decodeURIComponent((await params).map); + // The same reads as the page's own (`getMap` is per request), so the preview costs no extra request. + const [result, styles] = await Promise.all([getMap(name), currentStyles()]); + const map = result?.data; + return map ? mapPreview(map, styles.keys, styles.name) : { title: name }; } export default function MapPage({ params }: PageProps<"/maps/[map]">) { diff --git a/web/src/app/maps/page.tsx b/web/src/app/maps/page.tsx index cde80b7..8f37dcc 100644 --- a/web/src/app/maps/page.tsx +++ b/web/src/app/maps/page.tsx @@ -1,4 +1,4 @@ -// Maps page: every map with a finished run, searchable, with its world record in a chosen style. +// Maps page: the difficulty overview, filters and maps with a finished run in the chosen style. import type { Metadata } from "next"; import { MapList } from "@/features/maps/MapList"; import { Page } from "@/ui/Page"; @@ -10,8 +10,7 @@ export const metadata: Metadata = { export default function MapsPage({ searchParams }: PageProps<"/maps">) { return ( - -

Maps

+ {searchParams.then((params) => ( ))} diff --git a/web/src/app/page.tsx b/web/src/app/page.tsx index 6c77803..f005dac 100644 --- a/web/src/app/page.tsx +++ b/web/src/app/page.tsx @@ -1,16 +1,13 @@ -// Home page: the site's header, what bunnyhopping is, how to start, and the latest records and servers. -import { BhopIntro } from "@/features/home/BhopIntro"; -import { GetStarted } from "@/features/home/GetStarted"; +// Home page: the site's header with the way in, then what's happening now: how busy SourceJump is, the newest +// world records beside the top players, and the servers people are playing on. import { HomeHeader } from "@/features/home/HomeHeader"; import { LiveNow } from "@/features/home/LiveNow"; import { Page } from "@/ui/Page"; export default function HomePage() { return ( - + - - ); diff --git a/web/src/app/players/[steamid]/layout.tsx b/web/src/app/players/[steamid]/layout.tsx index df86c5f..e90354d 100644 --- a/web/src/app/players/[steamid]/layout.tsx +++ b/web/src/app/players/[steamid]/layout.tsx @@ -1,4 +1,4 @@ -// A player's pages: the header stays while the profile and the Manage view swap beneath it. +// A player's pages: the masthead stays while the profile and the Manage view swap beneath it. import { PlayerHeader } from "@/features/players/PlayerHeader"; import { Page } from "@/ui/Page"; @@ -7,11 +7,14 @@ export default function PlayerLayout({ children, }: LayoutProps<"/players/[steamid]">) { return ( - + // The masthead runs edge to edge, so the page sets its own width below it. + {params.then(({ steamid }) => ( ))} - {children} +
+ {children} +
); } diff --git a/web/src/app/players/[steamid]/page.tsx b/web/src/app/players/[steamid]/page.tsx index f29f57d..8f5587d 100644 --- a/web/src/app/players/[steamid]/page.tsx +++ b/web/src/app/players/[steamid]/page.tsx @@ -1,16 +1,25 @@ // A player's profile page, under their header. Any SteamID form works in the URL and lands on the SteamID64 // address. import type { Metadata } from "next"; +import { getPlayer } from "@/features/players/playerDetail"; +import { playerPreview } from "@/features/players/playerPreview"; import { PlayerProfile } from "@/features/players/PlayerProfile"; import { PageView } from "@/ui/Page"; -export const metadata: Metadata = { title: "Player" }; +export async function generateMetadata({ + params, +}: PageProps<"/players/[steamid]">): Promise { + // The same read as the header's (`getPlayer` is per request), so the preview costs no extra request. + const steamid = decodeURIComponent((await params).steamid); + const player = (await getPlayer(steamid))?.data; + return player ? playerPreview(player) : { title: "Player" }; +} export default function PlayerPage({ params, }: PageProps<"/players/[steamid]">) { return ( - + {params.then(({ steamid }) => ( ))} diff --git a/web/src/app/players/page.tsx b/web/src/app/players/page.tsx index 37fc7ce..be0fb66 100644 --- a/web/src/app/players/page.tsx +++ b/web/src/app/players/page.tsx @@ -1,8 +1,11 @@ -// Players page: how many players have a recorded time over time, search by name or SteamID, and recently -// active players; for staff, a Banned tab. +// Players page, laid out as the other boards: the title with how many players have a recorded time and the search +// beside it, players found as you type or recently active in two columns, then players over time. For staff, a +// Banned tab. import type { Metadata } from "next"; +import { api } from "@/api/client"; import { DailyTotals } from "@/features/dailyTotals/DailyTotals"; -import { PlayerSearch } from "@/features/players/PlayerSearch"; +import { PlayersBoard } from "@/features/players/PlayerSearch"; +import { CountUp } from "@/ui/CountUp"; import { Page } from "@/ui/Page"; export const metadata: Metadata = { @@ -12,15 +15,44 @@ export const metadata: Metadata = { export default function PlayersPage({ searchParams }: PageProps<"/players">) { return ( - -

Players

- - {searchParams.then(({ q, view }) => ( - - ))} + + {searchParams.then(async ({ q, view }) => { + const search = typeof q === "string" ? q.trim() : ""; + const total = await playerTotal(); + return ( + <> + +

Players

+ {total != null && ( +

+ + + {" "} + players have a recorded time on SourceJump. +

+ )} +
+ } + /> + {/* A separate thing from the list above it, so a step further off than the page's usual gap; gone with no chart. */} +
+ +
+ + ); + })} ); } + +/** How many players have a recorded time; none if the totals can't be loaded. */ +async function playerTotal(): Promise { + const result = await api + .GET("/v1/daily-totals/players", { params: { query: { range: "month" } } }) + .catch(() => undefined); + return result?.data?.points.at(-1)?.players; +} diff --git a/web/src/app/runs/[id]/page.tsx b/web/src/app/runs/[id]/page.tsx index 8dd2821..ee1237b 100644 --- a/web/src/app/runs/[id]/page.tsx +++ b/web/src/app/runs/[id]/page.tsx @@ -2,14 +2,19 @@ // staff act on the run here. // Following a run link within the site opens the run dialog instead. import type { Metadata } from "next"; +import { currentStyles } from "@/features/ruleset/styles"; import { getRun, RunDetails } from "@/features/runs/RunDetails"; +import { runPreview } from "@/features/runs/runPreview"; import { Page } from "@/ui/Page"; export async function generateMetadata({ params, }: PageProps<"/runs/[id]">): Promise { - const run = await getRun((await params).id); - return { title: run ? `${run.player.name} on ${run.map}` : "Run" }; + const [run, styles] = await Promise.all([ + getRun((await params).id), + currentStyles(), + ]); + return run ? runPreview(run, styles.name) : { title: "Run" }; } export default function RunPage({ params }: PageProps<"/runs/[id]">) { diff --git a/web/src/app/servers/page.tsx b/web/src/app/servers/page.tsx index c703778..cf8ea10 100644 --- a/web/src/app/servers/page.tsx +++ b/web/src/app/servers/page.tsx @@ -11,7 +11,7 @@ export const metadata: Metadata = { export default function ServersPage() { return ( -

Servers

+ {/* The board's activity card carries the page's heading, on a phone as on wider screens. */}
); diff --git a/web/src/app/sign-in/failed/page.tsx b/web/src/app/sign-in/failed/page.tsx index e4c4985..1ffcb72 100644 --- a/web/src/app/sign-in/failed/page.tsx +++ b/web/src/app/sign-in/failed/page.tsx @@ -1,7 +1,7 @@ // Where sign-in lands when Steam didn't confirm it. import type { Metadata } from "next"; -import { ButtonAnchor } from "@/ui/Button"; import { Page } from "@/ui/Page"; +import { SteamButton } from "@/ui/SteamButton"; export const metadata: Metadata = { title: "Sign-in didn't complete", @@ -16,9 +16,7 @@ export default function SignInFailedPage() { Steam didn't confirm the sign-in, or it took too long. Nothing was changed. Try again.

- - Sign in with Steam - + Sign in with Steam ); } diff --git a/web/src/app/staff/layout.tsx b/web/src/app/staff/layout.tsx index 3533bcd..be9e8ad 100644 --- a/web/src/app/staff/layout.tsx +++ b/web/src/app/staff/layout.tsx @@ -9,7 +9,7 @@ export const metadata: Metadata = { export default function StaffLayout({ children }: LayoutProps<"/staff">) { return ( -
+
{children}
diff --git a/web/src/features/activity/RecentRunTable.tsx b/web/src/features/activity/RecentRunTable.tsx index e89520c..7f12f89 100644 --- a/web/src/features/activity/RecentRunTable.tsx +++ b/web/src/features/activity/RecentRunTable.tsx @@ -1,23 +1,28 @@ "use client"; -// The latest runs as a table: who, which board, the time, and where it placed when it finished. "Show more" -// loads older runs a page at a time. -import { useState, type CSSProperties } from "react"; +// The latest runs as a table: who, which board, the time, and where it placed when it finished. Runs come a +// hundred at a time and are paged here, so turning a page is instant; the next hundred load in the background. +import { useSearchParams } from "next/navigation"; +import { + useCallback, + useEffect, + useRef, + useState, + type CSSProperties, + type FormEvent, + type MouseEvent, +} from "react"; import { api, type Schemas } from "@/api/client"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { RecordGap } from "@/features/runs/RecordGap"; import { RunLink } from "@/features/runs/RunLink"; -import { - formatGap, - formatSince, - formatTime, - trackName, -} from "@/features/runs/time"; +import { formatAge, formatTime, trackName } from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; -import { Button } from "@/ui/Button"; -import { Card } from "@/ui/Card"; import { classNames } from "@/ui/classNames"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; import { Table, TableBody, @@ -27,180 +32,433 @@ import { TableRow, } from "@/ui/Table"; import { TierBadge } from "@/ui/TierBadge"; +import { avatarSrc } from "@/features/players/avatarSrc"; -type Page = Schemas["RecentRuns"]; +type Run = Schemas["RecentRun"]; type Query = { style?: string; track?: "main" | "bonus"; min_tier?: number; records?: boolean; + /** Runs per request, a whole number of pages. */ + limit: number; }; +/** + * Runs loaded so far, by chunk: chunk `k` starts `k * limit` runs from the newest. With `total`, the API takes + * offsets and any chunk can load. Without it (an API before `total`), chunks load in order from `cursor`. + */ +export interface RunChunks { + chunks: Record; + total: number | null; + cursor: string | null; + tierCount: number | null; +} + export function RecentRunTable({ first, query, + address, + pageSize, styleNames, showStyle, }: { - first: Page; - /** The filters `first` was loaded with, for loading the pages after it. */ + /** The chunk holding the page in the address, or every chunk up to it. */ + first: RunChunks; + /** The filters `first` was loaded with, for loading the rest. */ query: Query; + /** The page's address with these filters, which the page number is added to. */ + address: string; + pageSize: number; styleNames: Record; /** With every style shown, each run names its own. */ showStyle: boolean; }) { - const [runs, setRuns] = useState(first.runs); - const [cursor, setCursor] = useState(first.next_cursor); - const [loading, setLoading] = useState(false); + const [loaded, setLoaded] = useState(first); const [failed, setFailed] = useState(false); - const tierCount = first.tier_count; - - async function showMore(after: string) { - setLoading(true); - setFailed(false); - const loaded = await api - .GET("/v1/runs", { params: { query: { ...query, cursor: after } } }) - .then((result) => result.data) - .catch(() => undefined); - setLoading(false); - if (!loaded) { - setFailed(true); - return; + const [waiting, setWaiting] = useState(false); + const [turned, setTurned] = useState(false); + // The latest chunks for the loops below, which outlive the render that started them. + const latest = useRef(first); + const inFlight = useRef(new Map>()); + const turns = useRef(0); + const board = useRef(null); + const rows = useRef(null); + // Held at the first page's height, so a short last page doesn't pull the page controls up. + const [minHeight, setMinHeight] = useState(); + const tierCount = first.tierCount; + const chunk = query.limit; + const pagesPerChunk = chunk / pageSize; + const chunkOf = (p: number) => Math.floor((p - 1) / pagesPerChunk); + + // No `page` means page 1, never the page the table first opened on. + const asked = Math.max( + 1, + Math.floor(Number(useSearchParams().get("page") ?? 1)) || 1, + ); + const more = loaded.total == null && loaded.cursor != null; + const pageCount = pagesIn(loaded, pageSize); + // Counted by the API, or once the last chunk has loaded without it. + const total = loaded.total ?? (loaded.cursor == null ? runsIn(loaded) : null); + const page = Math.min(asked, pageCount); + const shown = + loaded.chunks[chunkOf(page)]?.slice( + ((page - 1) % pagesPerChunk) * pageSize, + (((page - 1) % pagesPerChunk) + 1) * pageSize, + ) ?? []; + + const pageHref = useCallback( + (p: number) => + p > 1 + ? `${address}${address.includes("?") ? "&" : "?"}page=${p}` + : address, + [address], + ); + + /** Loads chunk `k`, once however many ask; false when it can't be loaded yet or failed. */ + const load = useCallback( + (k: number): Promise => { + const pending = inFlight.current.get(k); + if (pending) return pending; + const { chunks, total, cursor } = latest.current; + const byOffset = total != null; + if (!byOffset && (k !== Object.keys(chunks).length || !cursor)) + return Promise.resolve(false); + const request = api + .GET("/v1/runs", { + params: { + query: byOffset + ? { ...query, offset: k * query.limit } + : { ...query, cursor: cursor ?? undefined }, + }, + }) + .then((result) => result.data) + .catch(() => undefined) + .then((next) => { + inFlight.current.delete(k); + setFailed(!next); + if (!next) return false; + latest.current = { + ...latest.current, + chunks: { ...latest.current.chunks, [k]: next.runs }, + // The count moves as runs come in, so the newest answer wins. + total: byOffset ? next.total : null, + cursor: byOffset ? null : (next.next_cursor ?? null), + }; + setLoaded(latest.current); + return true; + }); + inFlight.current.set(k, request); + return request; + }, + [query], + ); + + /** Loads chunk `k`, walking the chunks before it first on an API without offsets. */ + const ensure = useCallback( + async (k: number): Promise => { + while (!latest.current.chunks[k]) { + const { chunks, total } = latest.current; + if (!(await load(total != null ? k : Object.keys(chunks).length))) + return false; + } + return true; + }, + [load], + ); + + // Loads the page asked for if it isn't yet, as after going back to a far page, and the chunks either side of + // it, so Next and Previous never wait. + const askedChunk = chunkOf(asked); + useEffect(() => { + if (failed) return; + void ensure(askedChunk).then((ok) => { + if (!ok) return; + const { total } = latest.current; + if (total == null || (askedChunk + 1) * chunk < total) + void ensure(askedChunk + 1); + if (askedChunk > 0) void ensure(askedChunk - 1); + }); + }, [askedChunk, failed, ensure, chunk]); + + // Past the last run, the address is corrected to the last page rather than showing one page and naming another. + useEffect(() => { + if (!more && asked > pageCount) + window.history.replaceState(null, "", pageHref(pageCount)); + }, [more, asked, pageCount, pageHref]); + + async function go(target: number) { + const turn = ++turns.current; + const known = latest.current.total; + const wanted = + known != null + ? Math.min(target, pagesIn(latest.current, pageSize)) + : target; + if (!latest.current.chunks[chunkOf(wanted)]) { + setWaiting(true); + // A typed page past what's loaded walks forward to it, or to the last page if the runs end first. + await ensure(chunkOf(wanted)); } - setRuns((shown) => [...shown, ...loaded.runs]); - setCursor(loaded.next_cursor); + // A later click wins over one still loading. + if (turn !== turns.current) return; + setWaiting(false); + setTurned(true); + const next = pageHref(Math.min(wanted, pagesIn(latest.current, pageSize))); + setMinHeight((held) => held ?? rows.current?.offsetHeight); + if (next !== window.location.pathname + window.location.search) + window.history.pushState(null, "", next); + // Keep the table's top in view when a page is turned from the bottom of a long page. + const top = board.current?.getBoundingClientRect().top ?? 0; + if (top < 0) board.current?.scrollIntoView({ block: "start" }); + } + + // The pager's links and box work without this; here they turn the page without asking the server. + function onPagerClick(event: MouseEvent) { + const link = (event.target as HTMLElement).closest("a"); + if ( + !link || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + // Stopped here too, as Next's Link and Form navigate even when the event is already prevented. + event.preventDefault(); + event.stopPropagation(); + void go(Number(new URL(link.href).searchParams.get("page") ?? 1)); + } + + function onPagerSubmit(event: FormEvent) { + event.preventDefault(); + event.stopPropagation(); + const form = event.target as HTMLFormElement; + const typed = Math.floor(Number(new FormData(form).get("page"))); + form.reset(); + if (typed >= 1) void go(typed); } - if (runs.length === 0) { + if (loaded.total === 0 || (pageCount === 1 && !more && shown.length === 0)) { return ( - +

{query.records ? "No world records match these choices." : "No runs match these choices."} - +

); } return ( -
- - - - When - Player - Map - Time - - Place - - - - - {runs.map((run, index) => ( - +
+ {/* On a phone each run is two lines, paired by width as ok-website's feed does: the player beside the time + and its gap, the map (the longest part) beside the age (the shortest); the place leads, the replay + ends. Wider screens get the table. */} +
+ # + Player + Time + {/* The replay button's width, so Time sits over the times. */} + +
+
    + {shown.map((run, row) => ( +
  1. - - {/* Counted from now, which differs between the server's render and the browser's. */} - - - - - - - {run.player.name} - - +
    + + - - - - {run.tier != null && tierCount != null && ( - - )} - - {run.map} - - {(run.track > 0 || showStyle) && ( - - {[ - run.track > 0 && trackName(run.track), - showStyle && (styleNames[run.style] ?? run.style), - ] - .filter(Boolean) - .join(" · ")} +
    +
    + + + {run.player.name} + + {run.player.country_code && ( + + )} - )} - - - - {/* Against the record when the run finished: what a new WR took off, or how far behind it was. */} - {run.gap != null && ( - - {run.gap < 0 - ? `−${formatTime(-run.gap)}` - : formatGap(run.gap)} + + + {formatTime(run.time)} + + {/* No gap: the board's first run, a record that beat nothing. */} + + +
    +
    + {/* One line tall: what doesn't fit wraps below and is hidden, so the style shows whole or not at all. */} + + + + {/* Counted from now, which differs between the server's render and the browser's. */} + +
    +
    + +
    +
  2. + ))} +
+
+ + + Player + Map + + Time + + {/* Narrow padding keeps the play button close to the time and the place. */} + + Replay + + {/* Centered, as the column holds marks of different widths: the WR badge, a medal, a number. */} + + Place + + + + + {shown.map((run, row) => ( + + + + + + {run.player.name} + + - )} - - {formatTime(run.time)} - - - - {run.world_record ? ( - WR - ) : run.placement != null ? ( - - + + + + - ) : ( - – - )} - - - ))} - -
-
- {failed && ( - - More couldn't be loaded. Try again. - - )} - {cursor && ( - - )} + + + + + + {formatTime(run.time)} + + {/* Against the record when the run finished: what a new WR took off, or how far behind it was. */} + {/* No gap: the board's first run, a record that beat nothing. */} + + + {/* Counted from now, which differs between the server's render and the browser's. */} + + + + + + + + + + + + + ))} + +
+ {(pageCount > 1 || more) && ( +
+ +
+ )} + {failed && ( +

+ Older runs couldn't be loaded. Try again in a moment. +

+ )}
); } @@ -211,3 +469,56 @@ function mapHref(run: Schemas["RecentRun"]): string { if (run.track > 0) search.set("track", String(run.track)); return `/maps/${run.map}?${search}`; } + +function runsIn(loaded: RunChunks): number { + return Object.values(loaded.chunks).reduce( + (sum, runs) => sum + runs.length, + 0, + ); +} + +function pagesIn(loaded: RunChunks, pageSize: number): number { + return Math.max(1, Math.ceil((loaded.total ?? runsIn(loaded)) / pageSize)); +} + +/** Where a run was set: the board's tier, the map, and its track and style when they need saying. */ +function RunMap({ + run, + tierCount, + styleName, +}: { + run: Schemas["RecentRun"]; + tierCount: number | null; + /** Left out when the board already shows one style. */ + styleName: string | undefined; +}) { + const extra = [run.track > 0 && trackName(run.track), styleName] + .filter(Boolean) + .join(" · "); + // The tier and map are one piece, shortened only when they alone overrun the line; the track and style follow + // it, and in a line that can't hold them they wrap out of sight (the phone list's line hides its overflow). + return ( + <> + + {run.tier != null && tierCount != null && ( + + )} + + {run.map} + + + {extra && {extra}} + + ); +} + +/** Where a run placed on its board when it finished: the WR badge, a medal or number, or a dash. */ +function Placement({ run }: { run: Schemas["RecentRun"] }) { + if (run.world_record) return WR; + if (run.placement != null) return ; + return –; +} diff --git a/web/src/features/activity/RecentRuns.tsx b/web/src/features/activity/RecentRuns.tsx index 7ddf234..f13a331 100644 --- a/web/src/features/activity/RecentRuns.tsx +++ b/web/src/features/activity/RecentRuns.tsx @@ -4,7 +4,7 @@ import { tierParam } from "@/features/maps/tierParam"; import { currentStyles } from "@/features/ruleset/styles"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; -import { RecentRunTable } from "./RecentRunTable"; +import { RecentRunTable, type RunChunks } from "./RecentRunTable"; const tracks = [ { key: "all", label: "All" }, @@ -20,8 +20,22 @@ export interface RecentRunsParams { tier?: string; /** "records": world records only. */ show?: string; + page?: string; } +const PAGE_SIZE = 15; +/** Runs per request, six pages: ninety cost the API about what fifteen do, so most pages turn without a request. */ +const CHUNK = 90; +/** How far an address may walk an API without offsets before giving up, at one request per chunk. */ +const MAX_CHUNKS = 20; + +type RunsQuery = { + style?: string; + track?: "main" | "bonus"; + min_tier?: number; + records?: boolean; +}; + interface Filters { style?: string; track: Track; @@ -30,24 +44,31 @@ interface Filters { } export async function RecentRuns({ params }: { params: RecentRunsParams }) { - const styles = await currentStyles(); - const filters: Filters = { - style: styles.keys.find((key) => key === params.style), - track: tracks.find((t) => t.key === params.track)?.key ?? "all", - tier: tierParam(params.tier), - records: params.show === "records", - }; - const query = { - style: filters.style, - track: filters.track === "all" ? undefined : filters.track, - min_tier: filters.tier, - records: filters.records || undefined, - }; - const result = await api - .GET("/v1/runs", { params: { query } }) - .catch(() => undefined); - const first = result?.data; - const tierCount = first?.tier_count ?? undefined; + const track = tracks.find((t) => t.key === params.track)?.key ?? "all"; + const tier = tierParam(params.tier); + const records = params.show === "records"; + const page = Math.max(1, Math.floor(Number(params.page)) || 1); + const queryFor = (style: string | undefined): RunsQuery => ({ + style, + track: track === "all" ? undefined : track, + min_tier: tier, + records: records || undefined, + }); + + // The runs don't wait for the ruleset: the style in the address is almost always one it ranks, and only a + // stale one costs a second request. + const [styles, guessed] = await Promise.all([ + currentStyles(), + loadRuns(queryFor(params.style || undefined), page), + ]); + const style = styles.keys.find((key) => key === params.style); + const query = queryFor(style); + const first = + style === (params.style || undefined) + ? guessed + : await loadRuns(query, page); + const filters: Filters = { style, track, tier, records }; + const tierCount = first?.tierCount ?? undefined; // Only what differs from the defaults goes in the address, so the plain page stays /activity. const href = (choice: Partial) => { @@ -62,68 +83,84 @@ export async function RecentRuns({ params }: { params: RecentRunsParams }) { }; return ( -
- - - {styles.keys.length > 1 && ( +
+
+ Show} options={[ - { value: "", label: "All", href: href({ style: undefined }) }, - ...styles.keys.map((key) => ({ - value: key, - label: styles.name(key), - href: href({ style: key }), - })), + { + value: "all", + label: "All runs", + href: href({ records: false }), + }, + { + value: "records", + label: "World records", + href: href({ records: true }), + }, ]} - value={filters.style ?? ""} + value={filters.records ? "records" : "all"} /> - )} - ({ - value: t.key, - label: t.label, - href: href({ track: t.key }), - }))} - value={filters.track} - /> - {/* Tiers are the community's to set; until a tier count is published there's nothing to filter by. */} - {tierCount != null && ( + {styles.keys.length > 1 && ( + ({ + value: key, + label: styles.name(key), + href: href({ style: key }), + })), + ]} + value={filters.style ?? ""} + /> + )} ({ - value: String(i + 1), - label: `Tier ${i + 1}`, - href: href({ tier: i + 1 }), - })), - ]} - value={filters.tier ? String(filters.tier) : ""} + label="Track" + options={tracks.map((t) => ({ + value: t.key, + label: t.label, + href: href({ track: t.key }), + }))} + value={filters.track} /> - )} - + {/* Tiers are the community's to set; until a tier count is published there's nothing to filter by. */} + {tierCount != null && ( + + Tier + Lowest tier + + } + options={[ + { value: "", label: "Any", href: href({ tier: undefined }) }, + ...Array.from({ length: tierCount }, (_, i) => ({ + value: String(i + 1), + label: `Tier ${i + 1}`, + href: href({ tier: i + 1 }), + })), + ]} + value={filters.tier ? String(filters.tier) : ""} + /> + )} + +
{!first ? ( -

Runs couldn't be loaded. Try again in a moment.

+

+ Runs couldn't be loaded. Try again in a moment. +

) : ( // Keyed by the filters, so a new choice starts again from the newest runs and they all fade in. [key, styles.name(key)]), )} @@ -133,3 +170,50 @@ export async function RecentRuns({ params }: { params: RecentRunsParams }) {
); } + +/** The chunk holding `page`; undefined when the first request fails. */ +async function loadRuns( + query: RunsQuery, + page: number, +): Promise { + const get = (from: { offset?: number; cursor?: string }) => + api + .GET("/v1/runs", { + params: { query: { ...query, limit: CHUNK, ...from } }, + }) + .then((result) => result.data) + .catch(() => undefined); + const wanted = Math.floor(((page - 1) * PAGE_SIZE) / CHUNK); + const first = await get({ offset: wanted * CHUNK }); + if (!first) return undefined; + const tierCount = first.tier_count ?? null; + + // An API that counts its runs honours the offset, so this is the page's own chunk. One past the end is asked + // again for the last chunk. + if (typeof first.total === "number") { + const last = Math.max(0, Math.ceil(first.total / CHUNK) - 1); + const page = wanted > last ? await get({ offset: last * CHUNK }) : first; + if (!page) return undefined; + return { + chunks: { [Math.min(wanted, last)]: page.runs }, + total: page.total, + cursor: null, + tierCount, + }; + } + + // One that doesn't (the beta before `total`) ignored the offset and sent the newest runs, so walk forward. + const chunks: Record = { 0: first.runs }; + let cursor = first.next_cursor ?? null; + for ( + let chunk = 1; + cursor && chunk <= wanted && chunk < MAX_CHUNKS; + chunk++ + ) { + const next = await get({ cursor }); + if (!next) break; + chunks[chunk] = next.runs; + cursor = next.next_cursor ?? null; + } + return { chunks, total: null, cursor, tierCount }; +} diff --git a/web/src/features/community/PostByline.tsx b/web/src/features/community/PostByline.tsx index 36ca2f3..7f7d1dc 100644 --- a/web/src/features/community/PostByline.tsx +++ b/web/src/features/community/PostByline.tsx @@ -3,23 +3,25 @@ import type { Schemas } from "@/api/client"; import { formatDate } from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Link } from "@/ui/Link"; +import { avatarSrc } from "@/features/players/avatarSrc"; +import { Dot } from "@/ui/Dot"; export function PostByline({ post }: { post: Schemas["PostSummary"] }) { const edited = post.updated_at.slice(0, 10) !== post.created_at.slice(0, 10); return ( - + {post.author.name} - · + {edited && ( diff --git a/web/src/features/dailyTotals/DailyTotals.tsx b/web/src/features/dailyTotals/DailyTotals.tsx index 06d2281..9da64c6 100644 --- a/web/src/features/dailyTotals/DailyTotals.tsx +++ b/web/src/features/dailyTotals/DailyTotals.tsx @@ -9,7 +9,17 @@ import { const ranges = ["month", "year", "all"] as const satisfies TotalsRange[]; -export async function DailyTotals({ kind }: { kind: DailyTotalsData["kind"] }) { +export async function DailyTotals({ + kind, + heading, + plain = false, +}: { + kind: DailyTotalsData["kind"]; + /** Sits in the chart's top row, so the page doesn't spend a line on its own title. */ + heading?: string; + /** Draws on the parent's surface instead of its own card. */ + plain?: boolean; +}) { // Both endpoints take the same range and return their own totals type, so one fetch serves either kind. const data: DailyTotalsData = { kind, @@ -34,6 +44,8 @@ export async function DailyTotals({ kind }: { kind: DailyTotalsData["kind"] }) { ); } diff --git a/web/src/features/dailyTotals/DailyTotalsChart.tsx b/web/src/features/dailyTotals/DailyTotalsChart.tsx index 12dad56..483c8b4 100644 --- a/web/src/features/dailyTotals/DailyTotalsChart.tsx +++ b/web/src/features/dailyTotals/DailyTotalsChart.tsx @@ -2,11 +2,13 @@ // A chart of the site's daily totals over a month, a year or all time: players with a recorded time on the // Players page, runs and world records per day on the Activity page. Hovering, tapping or arrow keys read a // point. Every range arrives with the page, so switching is instant. -import { useState } from "react"; +import { type ReactNode, useState } from "react"; import type { Schemas } from "@/api/client"; -import { Card, Label } from "@/ui/Card"; +import { Card } from "@/ui/Card"; +import { classNames } from "@/ui/classNames"; import { LineChart } from "@/ui/LineChart"; import { Segmented } from "@/ui/Segmented"; +import { Dot } from "@/ui/Dot"; export type TotalsRange = Schemas["TotalsRange"]; @@ -52,9 +54,13 @@ interface Point { export function DailyTotalsChart({ data, initialRange, + heading, + plain = false, }: { data: DailyTotalsData; initialRange: TotalsRange; + heading?: string; + plain?: boolean; }) { const [range, setRange] = useState(initialRange); const [active, setActive] = useState(null); @@ -77,14 +83,97 @@ export function DailyTotalsChart({ const bucketDays = current?.bucket_days ?? 1; const rangeLabel = ranges.find((r) => r.value === range)?.label ?? ""; - return ( - -
- + const stats = shown && ( +

+ {data.kind === "players" ? ( + + {shown.y === 1 ? "player" : "players"} with a recorded time + + ) : ( + <> + {/* Each number in its line's color, so the line reads as the legend. */} + + {shown.y === 1 ? "run" : "runs"} + + + + {shown.y2 === 1 ? "world record" : "world records"} + + + )} + + {when(shown.day, bucketDays)} +

+ ); + + const plot = + points.length < 2 ? ( +

+ {current + ? "Not enough days yet to draw a chart." + : "This range couldn't be loaded."} +

+ ) : ( +
+ ({ + x: Date.parse(p.day), + y: p.y, + y2: p.y2, + }))} + active={active} + onActive={setActive} + formatValue={(value) => axis.format(Math.round(value))} + /> + {/* Indented by the value labels' width, so the dates sit under the plot's ends. */} +
+ {date.format(new Date(points[0]?.day ?? 0))} + {date.format(new Date(points.at(-1)?.day ?? 0))} +
+
+ ); + + const frame = ( + <> + {/* On a phone: the title and the range on one line, the totals on the next, so the board starts sooner. + The title's column dissolves there (`contents`) so its two parts can take those places. */} +
+ {heading ? ( +
+

{heading}

+ {stats} +
+ ) : ( + stats + )} { @@ -93,89 +182,27 @@ export function DailyTotalsChart({ }} />
- - {shown && ( -

- {data.kind === "players" ? ( - - ) : ( - <> - - - - )} - - {active === null ? "Latest: " : ""} - {when(shown.day, bucketDays)} - -

- )} - - {points.length < 2 ? ( -

- {current - ? "Not enough days yet to draw a chart." - : "This range couldn't be loaded."} -

- ) : ( -
- ({ - x: Date.parse(p.day), - y: p.y, - y2: p.y2, - }))} - active={active} - onActive={setActive} - formatValue={(value) => axis.format(Math.round(value))} - /> - {/* Indented by the value labels' width, so the dates sit under the plot's ends. */} -
- {date.format(new Date(points[0]?.day ?? 0))} - {date.format(new Date(points.at(-1)?.day ?? 0))} -
-
- )} - + {plot} + ); + + if (plain) return
{frame}
; + return {frame}; } -function Amount({ +function Stat({ value, - unit, - swatch, + tone = "text-text", + children, }: { value: number; - unit: string; - /** The line's color, beside its number, when the chart has two. */ - swatch?: string; + tone?: string; + children: ReactNode; }) { return ( - - {swatch && ( - - )} - - {count.format(value)} - - - {value === 1 ? unit : `${unit}s`} - + + {count.format(value)}{" "} + {children} ); } diff --git a/web/src/features/home/BhopDemo.tsx b/web/src/features/home/BhopDemo.tsx deleted file mode 100644 index b1efc01..0000000 --- a/web/src/features/home/BhopDemo.tsx +++ /dev/null @@ -1,455 +0,0 @@ -"use client"; -// The home page's bhop demo: a simulated player hopping block to block, seen from above at an angle, with the -// keys they hold and their speed shown the way a bhop server's HUD shows them. -import { ArrowLeft, ArrowRight, Pause, Play } from "lucide-react"; -import { - useEffect, - useId, - useMemo, - useRef, - useState, - type ReactNode, -} from "react"; -import { Button } from "@/ui/Button"; -import { classNames } from "@/ui/classNames"; -import { simulateStrafes, tickSeconds, type StrafeTick } from "./strafeSim"; - -const SECONDS = 9.5; -// Once the run ends it fades out, then starts again. -const FADE_SECONDS = 0.6; -// How long the jump key stays lit after a jump, so it's visible at 60 frames a second. -const JUMP_LIT_TICKS = 12; -// With reduced motion the demo shows one still moment, late enough that several hops are behind it. -const STILL_TICK = 620; - -// The drawing, in its own units. The player stays at PLAYER_X while the course moves past, a little left of -// the middle so more of the course ahead shows than behind. The block tops sit at the middle height: the hops -// and strafes reach about as far above them as the blocks' sides reach below. -const WIDTH = 1000; -const HEIGHT = 440; -const PLAYER_X = 460; -const GROUND_Y = HEIGHT / 2; -// An oblique view: forward runs to the right, left runs up and a little right, height runs up. Height is drawn -// taller than it is, so the hops read as clearly as the strafes. -const SCALE = 0.75; -const DEPTH_X = 0.35; -const DEPTH_Y = 0.9; -const HEIGHT_Y = 1.3; -// Blocks stand on a floor this far below them; their tops are where the player lands. -const FLOOR = 48; -const BLOCK = 32; -// The floor's grid reaches further back than forward, and fades out towards the back. -const GRID = 64; -const GRID_BACK = 640; -const GRID_FRONT = 384; -// The trail keeps the last few seconds; older parts have left the drawing anyway. -const TRAIL_TICKS = 400; - -type Point = readonly [number, number]; - -/** - * Rounded to a tenth: Node and the browser can differ in a sine's last digits, and the server's drawing has to - * match the browser's exactly for React to take it over. - */ -function project(x: number, y: number, z: number): Point { - return [ - round((x + y * DEPTH_X) * SCALE), - round(-(y * DEPTH_Y + z * HEIGHT_Y) * SCALE), - ]; -} - -function round(value: number): number { - return Math.round(value * 10) / 10; -} - -function points(list: readonly Point[]): string { - return list.map(([x, y]) => `${x},${y}`).join(" "); -} - -export function BhopDemo() { - const ticks = useMemo(() => simulateStrafes(SECONDS + 1), []); - const landings = useMemo( - () => ticks.flatMap((tick, index) => (tick.jump ? [index] : [])), - [ticks], - ); - const [time, setTime] = useState(0); - const [playing, setPlaying] = useState(true); - const [still, setStill] = useState(false); - const frame = useRef(null); - - // Plays only while on screen and not paused; the browser already pauses animation frames in hidden tabs. - useEffect(() => { - if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { - // eslint-disable-next-line react-hooks/set-state-in-effect -- read once, after hydration - setStill(true); - return; - } - const element = frame.current; - if (!element || !playing) return; - let request = 0; - let last = 0; - let visible = false; - const step = (now: number) => { - const delta = last ? Math.min((now - last) / 1000, 0.1) : 0; - last = now; - setTime((t) => { - const next = t + delta; - return next > SECONDS + FADE_SECONDS ? 0 : next; - }); - request = requestAnimationFrame(step); - }; - const observer = new IntersectionObserver(([entry]) => { - if (entry?.isIntersecting && !visible) { - visible = true; - last = 0; - request = requestAnimationFrame(step); - } else if (!entry?.isIntersecting && visible) { - visible = false; - cancelAnimationFrame(request); - } - }); - observer.observe(element); - return () => { - observer.disconnect(); - cancelAnimationFrame(request); - }; - }, [playing]); - - const shown = still ? STILL_TICK * tickSeconds : Math.min(time, SECONDS); - const exact = shown / tickSeconds; - const index = Math.min(Math.floor(exact), ticks.length - 2); - const now = lerp(ticks[index]!, ticks[index + 1]!, exact - index); - const tick = ticks[index]!; - const hop = landings.filter((landing) => landing <= index).length; - const lastLanding = landings[hop - 1] ?? 0; - const jumping = index - lastLanding < JUMP_LIT_TICKS; - const [playerX, playerY] = project(now.x, now.y, now.z); - const [shadowX, shadowY] = project(now.x, now.y, -FLOOR); - const [cameraX] = project(now.x, 0, 0); - const trail = ticks.slice(Math.max(0, index - TRAIL_TICKS), index + 1); - - // The course doesn't move relative to itself, so it's built once and the camera slides over it. - const course = useMemo( - () => , - [ticks, landings], - ); - - return ( -
- - SECONDS && !still && "opacity-0", - )} - > - - {course} - {/* Which blocks the player has landed on, and a ring where they just did. */} - {landings.slice(0, hop).map((landing) => ( - - ))} - {hop > 0 && !still && ( - - )} - project(t.x, t.y, -FLOOR)))} - fill="none" - className="stroke-accent opacity-30" - strokeWidth={2} - strokeLinecap="round" - strokeLinejoin="round" - /> - project(t.x, t.y, t.z)))} - fill="none" - className="stroke-accent opacity-20" - strokeWidth={10} - strokeLinejoin="round" - strokeLinecap="round" - /> - project(t.x, t.y, t.z)))} - fill="none" - className="stroke-accent" - strokeWidth={2.5} - strokeLinejoin="round" - strokeLinecap="round" - /> - - - - - - - - -
-
-
- W - - A - - S - D - - Jump - -
-
- - Mouse - -
- - - - - - -
-
-
-
- - Hop {Math.max(hop, 1)} - - - {Math.round(now.speed)} - - u/s - - -
-
- - {!still && ( - - )} -
- ); -} - -/** The blocks under each landing and the floor below them, in course coordinates. */ -function Course({ - ticks, - landings, -}: { - ticks: StrafeTick[]; - landings: number[]; -}) { - const fade = useId(); - const [start, end] = [-WIDTH, (ticks.at(-1)?.x ?? 0) + WIDTH * 2]; - const lines: [Point, Point][] = []; - for (let x = start; x <= end; x += GRID) { - lines.push([ - project(x, -GRID_FRONT, -FLOOR), - project(x, GRID_BACK, -FLOOR), - ]); - } - for (let y = -GRID_FRONT; y <= GRID_BACK; y += GRID) { - lines.push([project(start, y, -FLOOR), project(end, y, -FLOOR)]); - } - const [, back] = project(0, GRID_BACK, -FLOOR); - const [, middle] = project(0, 0, -FLOOR); - // The mask's own box: left alone, a mask covers only the drawing's first screenful of the course. - const [left] = project(start, -GRID_FRONT, -FLOOR); - const [right, bottom] = project(end, -GRID_FRONT, -FLOOR); - const area = { - x: left, - y: back, - width: right + GRID_BACK * DEPTH_X * SCALE - left, - height: bottom - back, - }; - // Back blocks first, so nearer ones are drawn over them. - const blocks = [...landings].sort((a, b) => ticks[b]!.y - ticks[a]!.y); - return ( - <> - {/* An alpha mask, so only the gradient's opacity counts and it needs no colour. */} - - - - - - - - - {lines.map(([[x1, y1], [x2, y2]], i) => ( - - ))} - - {blocks.map((landing) => ( - - ))} - - ); -} - -/** A block standing on the floor, its top where the player lands. The start block is a start zone. */ -function Block({ tick, start }: { tick: StrafeTick; start: boolean }) { - const size = start ? BLOCK * 2 : BLOCK; - const { x, y } = tick; - const corner = (dx: number, dy: number, z: number) => - project(x + dx * size, y + dy * size, z); - // Seen from the front and to the right: the front and right faces show, the back and left stay hidden. - const front = [ - corner(-1, -1, 0), - corner(1, -1, 0), - corner(1, -1, -FLOOR), - corner(-1, -1, -FLOOR), - ]; - const right = [ - corner(1, -1, 0), - corner(1, 1, 0), - corner(1, 1, -FLOOR), - corner(1, -1, -FLOOR), - ]; - return ( - - - - - - ); -} - -function BlockTop({ - tick, - size = BLOCK, - className, -}: { - tick: StrafeTick; - size?: number; - className: string; -}) { - const { x, y } = tick; - const top = [ - project(x - size, y - size, 0), - project(x + size, y - size, 0), - project(x + size, y + size, 0), - project(x - size, y + size, 0), - ]; - return ( - - ); -} - -/** A ring spreading from where the player just landed. */ -function Ripple({ tick }: { tick: StrafeTick }) { - const [cx, cy] = project(tick.x, tick.y, 0); - return ( - - ); -} - -function Keycap({ - on = false, - label, - className, - children, -}: { - on?: boolean; - /** For keys drawn as an icon. */ - label?: string; - className?: string; - children: ReactNode; -}) { - return ( - - {children} - - ); -} - -function lerp(a: StrafeTick, b: StrafeTick, amount: number) { - const mix = (p: number, q: number) => p + (q - p) * amount; - return { - x: mix(a.x, b.x), - y: mix(a.y, b.y), - // The jump resets height in one tick; blending across it would dip the player through the block. - z: b.jump ? a.z : mix(a.z, b.z), - speed: mix(a.speed, b.speed), - }; -} diff --git a/web/src/features/home/BhopIntro.tsx b/web/src/features/home/BhopIntro.tsx deleted file mode 100644 index a492a20..0000000 --- a/web/src/features/home/BhopIntro.tsx +++ /dev/null @@ -1,56 +0,0 @@ -// The home page's introduction to bunnyhopping: the demo, and the three things a player does in a line each. -import type { ReactNode } from "react"; -import { BhopDemo } from "./BhopDemo"; - -const steps: { title: string; body: string; keys: ReactNode }[] = [ - { - title: "Jump as you land", - body: "Same tick, no friction, no speed lost.", - keys: Jump, - }, - { - title: "Strafe in the air", - body: "Turn the mouse the way of the key you hold.", - keys: ( - <> - A - D - - ), - }, - { - title: "Chain the hops", - body: "Each hop starts with the last one's speed.", - keys: u/s, - }, -]; - -export function BhopIntro() { - return ( -
-

- Speed from jumping and strafing -

- -
    - {steps.map((step) => ( -
  1. - {step.keys} - - {step.title} - {step.body} - -
  2. - ))} -
-
- ); -} - -function Key({ children }: { children: ReactNode }) { - return ( - - {children} - - ); -} diff --git a/web/src/features/home/GetStarted.tsx b/web/src/features/home/GetStarted.tsx deleted file mode 100644 index 661292f..0000000 --- a/web/src/features/home/GetStarted.tsx +++ /dev/null @@ -1,63 +0,0 @@ -// The home page's way in for a new player: where to play, what to play, and where their times show up. -import { - Activity, - ArrowRight, - Map, - Server, - type LucideIcon, -} from "lucide-react"; -import { Card } from "@/ui/Card"; -import { Link } from "@/ui/Link"; - -const steps: { icon: LucideIcon; title: string; body: string; href: string }[] = - [ - { - icon: Server, - title: "Join a server", - body: "Runs on listed servers count here.", - href: "/servers", - }, - { - icon: Map, - title: "Pick a map", - body: "Leaderboards and record history for each.", - href: "/maps", - }, - { - icon: Activity, - title: "Follow the times", - body: "New runs and world records as they land.", - href: "/activity", - }, - ]; - -export function GetStarted() { - return ( -
-

- Your times, on one global list -

-
    - {steps.map(({ icon: Icon, ...step }) => ( -
  1. - - - - - - - {step.title} - {step.body} - - - - -
  2. - ))} -
-
- ); -} diff --git a/web/src/features/home/HomeHeader.tsx b/web/src/features/home/HomeHeader.tsx index d461f2b..6aefef4 100644 --- a/web/src/features/home/HomeHeader.tsx +++ b/web/src/features/home/HomeHeader.tsx @@ -21,7 +21,7 @@ const nativePlacement = { /** A static import, so Next.js knows the size, serves modern formats at the screen's width, and blurs in. */ export function HomeHeader() { return ( -
+
{/* On a phone the text takes the lower half, so the picture fills only the top two thirds and fades out there: the jumper then sits between the top edge and the text instead of behind it. The settle zoom is on this box so the depth canvas moves with the picture. */} @@ -47,15 +47,19 @@ export function HomeHeader() { any part of it. */}
-
+
-

SourceJump

+

+ SourceJump +

The global bunnyhop community for Counter-Strike: Source.

+ {/* Its own compositing layer: with the depth canvas redrawing beneath every frame, some GPU browsers drew a + hovered button's new color for a frame and then the stale one again (Chromium, NVIDIA, 2026-11-08). */}
diff --git a/web/src/features/home/LiveNow.tsx b/web/src/features/home/LiveNow.tsx index 0244998..6322a3a 100644 --- a/web/src/features/home/LiveNow.tsx +++ b/web/src/features/home/LiveNow.tsx @@ -1,205 +1,420 @@ -// The home page's live part: the newest world records beside the busiest servers online right now. -import { ArrowRight } from "lucide-react"; -import type { CSSProperties } from "react"; +// The home page's live part, under its header: the numbers that say how busy SourceJump is (players on now, the +// latest day's runs, the week's world records), the newest world records beside the top of the points board, then +// the servers people are playing on now. +import type { CSSProperties, ReactNode } from "react"; import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; +import { RecordGap } from "@/features/runs/RecordGap"; import { RunLink } from "@/features/runs/RunLink"; -import { formatSince, formatTime, trackName } from "@/features/runs/time"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { + formatAge, + formatDate, + formatTime, + trackName, +} from "@/features/runs/time"; +import { ServerRow } from "@/features/servers/ServerRow"; import { Avatar } from "@/ui/Avatar"; import { buttonClasses } from "@/ui/Button"; -import { Card, Label } from "@/ui/Card"; -import { DividedList } from "@/ui/Divided"; +import { classNames } from "@/ui/classNames"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { TierBadge } from "@/ui/TierBadge"; +import { avatarSrc } from "@/features/players/avatarSrc"; -const RECORDS = 6; +const RECORDS = 8; +/** + * Records fetched to find RECORDS boards among: a board's record often falls several times in a row, and only the + * latest shows. shortcut: fewer than RECORDS show if the last 100 records were set on fewer boards; a `distinct` + * option on the API would end that. + */ +const RECORDS_SCANNED = 100; +const LEADERS = 10; const SERVERS = 4; +const numbers = new Intl.NumberFormat("en"); export async function LiveNow() { - const [records, servers, styles] = await Promise.all([ + // Each part shows what it has; one that can't be loaded says so, or (a fact) leaves its number out. + const [records, servers, leaders, runs, styles] = await Promise.all([ api - .GET("/v1/runs", { params: { query: { records: true, limit: RECORDS } } }) + .GET("/v1/runs", { + params: { query: { records: true, limit: RECORDS_SCANNED } }, + }) .catch(() => undefined), api.GET("/v1/servers").catch(() => undefined), + api + .GET("/v1/leaderboards/{ranking}", { + params: { path: { ranking: "points" }, query: { limit: LEADERS } }, + }) + .catch(() => undefined), + api + .GET("/v1/daily-totals/runs", { params: { query: { range: "month" } } }) + .catch(() => undefined), currentStyles(), ]); + const listed = servers?.data?.servers; + // The API lists online servers first, busiest first. + const online = listed?.filter((server) => server.online) ?? []; + const playing = online.reduce((sum, server) => sum + server.players, 0); + // Where the players are, "12 playing now on 3 servers"; with nobody playing, how many servers are up to join. + const busy = online.filter((server) => server.players > 0).length; + const playingDetail = + playing > 0 + ? ` on ${busy} ${busy === 1 ? "server" : "servers"}` + : `, ${online.length} ${online.length === 1 ? "server" : "servers"} online`; + const lastDay = runs?.data?.points.at(-1); + const week = runs?.data?.points.slice(-7) ?? []; + const board = leaders?.data; + return ( -
- - - Latest world records - - {records?.data ? ( - 1 ? styles.name : undefined} - /> - ) : ( -

- Records couldn't be loaded. Try again in a moment. -

- )} -
- - - Online now - - {servers?.data ? ( - + <> + 0 && { + value: week.reduce((sum, day) => sum + day.world_records, 0), + text: "world records in the last 7 days", + href: "/activity?show=records", + }, + ]} + /> + + {/* Side by side, the two panels end level: each list's rows share out the taller one's height. */} +
+ + {records?.data ? ( + 1 ? styles.name : undefined} + /> + ) : ( + Records couldn't be loaded. Try again in a moment. + )} + + + {board ? ( + + ) : ( + + The leaderboard couldn't be loaded. Try again in a moment. + + )} + +
+ + + {!listed ? ( + Servers couldn't be loaded. Try again in a moment. + ) : online.length === 0 ? ( +
+

+ No servers are online right now. The server list shows where + players were last seen. +

+ + Server list + +
) : ( -

- Servers couldn't be loaded. Try again in a moment. -

+ // The Servers page's own rows, two to a line, with the lines between them drawn by each cell. +
    + {online.slice(0, SERVERS).map((server, index) => ( +
  • + +
  • + ))} +
)} -
-
+ + ); } -function Heading({ +interface Fact { + value: number; + /** A count of what's happening right now, in the green of the servers' online dots. */ + live?: boolean; + /** What the number counts, read after it. */ + text: string; + href: string; +} + +/** + * How busy SourceJump is, one strip split three ways, each part opening the page it comes from. One line each, so it stays + * short: the number, then what it counts (beneath it until the boxes are wide enough for one line). + */ +function Facts({ facts }: { facts: (Fact | false | 0 | null | undefined)[] }) { + const shown = facts.filter((fact): fact is Fact => !!fact); + if (shown.length === 0) return null; + return ( +
    + {shown.map((fact) => ( +
  • + + + {numbers.format(fact.value)} + + + {fact.text} + + +
  • + ))} +
+ ); +} + +function Panel({ + title, href, link, + note, + className, children, }: { + title: string; href: string; link: string; - children: string; + /** Beside the title, e.g. which board the panel shows. */ + note?: ReactNode; + className?: string; + children: ReactNode; }) { return ( -
- - - {link} - - -
+
+
+

+ {title} + {note && ( + {note} + )} +

+ + {link} + +
+ {children} +
); } +function Note({ children }: { children: ReactNode }) { + return

{children}

; +} + function Records({ runs, + tierCount, styleName, }: { runs: Schemas["RecentRun"][]; + tierCount: number | null; /** Given when more than one style is ranked, so each record names its own. */ styleName?: (key: string) => string; }) { - if (runs.length === 0) { - return

No world records yet.

; - } + if (runs.length === 0) return No world records yet.; + // The track on a bonus, and the style when more than one is ranked. + const details = (run: Schemas["RecentRun"]) => + [run.track > 0 && trackName(run.track), styleName?.(run.style)] + .filter(Boolean) + .join(" · "); return ( - +
    {runs.map((run, index) => (
  • - - - - - {run.player.name} - - - - - 0 ? `&track=${run.track}` : ""}`} - className="hover:text-accent" - > - {run.map} - - {[run.track > 0 && trackName(run.track), styleName?.(run.style)] - .filter(Boolean) - .map((part) => ` · ${part}`)} - - - - {/* Every row is a world record, so the time says by how much it beat the last one instead of "WR". */} - - {run.gap != null && run.gap < 0 && ( - - −{formatTime(-run.gap)} + {/* Who, then where: the player, then the map with its tier, and its style and track; then the time. Side + by side from sm; on a phone the map takes the line under the player, the style giving way first and + left out below 360px. */} + + + + + {run.tier != null && tierCount != null && ( + + )} + 0 ? `&track=${run.track}` : ""}`} + className="hover:text-accent truncate" + > + {run.map} + + {details(run) && ( + + {details(run)} + + )} + + {details(run) && ( + + {details(run)} )} + + + {/* As on the Activity board: the time with what it took off the old record in brackets, how long ago + beneath, then the replay. A phone leaves the brackets to the run's page, so the map keeps its width. */} + + {formatTime(run.time)} + {/* No gap: the board's first run, a record that beat nothing. */} + - + {/* Counted from now, which differs between the server's render and the browser's. */} - +
  • ))} - +
); } -function Servers({ servers }: { servers: Schemas["ListedServer"][] }) { - // The API lists online servers first, busiest first. - const online = servers.filter((server) => server.online).slice(0, SERVERS); - if (online.length === 0) { - return ( -
-

- No servers are online right now. The server list shows where players - were last seen. -

- - Server list - -
- ); - } +/** Who set a record: their avatar, name and, when Steam has it, flag (a placeholder on every row would be noise). */ +function RecordHolder({ + player, + className, +}: { + player: Schemas["RecentRun"]["player"]; + className?: string; +}) { return ( - - {online.map((server) => { - const address = `${server.ip}:${server.port}`; - return ( -
  • - - {server.hostname} - - {server.map} + + + + {player.name} + + {player.country_code && ( + + + + )} + + ); +} + +function Leaders({ standings }: { standings: Schemas["Standing"][] }) { + if (standings.length === 0) return No one has points yet.; + return ( +
      + {standings.map((standing, index) => ( +
    1. + + {/* Counted down the list, not the shared rank of a tie, as on the Leaderboards page. */} + + + + + {standing.player.name} + {standing.player.country_code && ( + + )} - - - - {server.players} - /{server.max_slots} + + + {numbers.format(standing.points)} + + + {standing.completed} {standing.completed === 1 ? "map" : "maps"} - - Join - -
    2. - ); - })} - + + + ))} +
    ); } + +/** Each board's latest record only, newest first: one map's record falling seven times reads as seven maps' news. */ +function latestPerBoard(runs: Schemas["RecentRun"][]): Schemas["RecentRun"][] { + const seen = new Set(); + return runs.filter((run) => { + const board = `${run.map}/${run.style}/${run.track}`; + if (seen.has(board)) return false; + seen.add(board); + return true; + }); +} diff --git a/web/src/features/home/strafeSim.test.ts b/web/src/features/home/strafeSim.test.ts deleted file mode 100644 index 1f71202..0000000 --- a/web/src/features/home/strafeSim.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { simulateStrafes, tickSeconds } from "./strafeSim"; - -describe("simulateStrafes", () => { - const ticks = simulateStrafes(10); - - it("gains speed from strafing alone", () => { - expect(ticks[0]!.speed).toBeGreaterThanOrEqual(250); - expect(ticks.at(-1)!.speed).toBeGreaterThan(600); - // Only switching strafes costs speed, a little, on the tick the keys change; every other tick gains. - for (let i = 1; i < ticks.length; i++) { - const change = ticks[i]!.speed - ticks[i - 1]!.speed; - if (ticks[i]!.jump) expect(change).toBeGreaterThan(-1); - else expect(change).toBeGreaterThan(0); - } - }); - - it("jumps on landing, once per Source jump arc", () => { - const jumps = ticks.flatMap((tick, index) => (tick.jump ? [index] : [])); - // A jump at 57 units of height lasts about 0.755 s under 800 gravity. - const gaps = jumps.slice(1).map((jump, i) => jump - jumps[i]!); - for (const gap of gaps) { - expect(gap * tickSeconds).toBeCloseTo(0.755, 1); - } - for (const index of jumps.slice(1)) { - expect(ticks[index - 1]!.z).toBeLessThan(5); - } - }); - - it("switches strafe key with each hop and weaves around the line forward", () => { - const keys = ticks.filter((tick) => tick.jump).map((tick) => tick.key); - keys.slice(1).forEach((key, i) => expect(key).not.toBe(keys[i])); - const ys = ticks.map((tick) => tick.y); - expect(Math.min(...ys)).toBeLessThan(-30); - expect(Math.max(...ys)).toBeGreaterThan(30); - }); -}); diff --git a/web/src/features/home/strafeSim.ts b/web/src/features/home/strafeSim.ts deleted file mode 100644 index 363a562..0000000 --- a/web/src/features/home/strafeSim.ts +++ /dev/null @@ -1,93 +0,0 @@ -// The home page's bhop demo, simulated: a player chaining hops and strafing, moved by Source's air rules. - -// Source's movement constants as CS:S ships them. The air acceleration and the turn rate aren't any server's -// setting or a real player's input; they're picked so the demo's path weaves visibly at a readable pace. -const TICK = 1 / 100; -const GRAVITY = 800; -const JUMP_SPEED = Math.sqrt(2 * GRAVITY * 57); -const MAX_SPEED = 250; -const AIR_WISH_CAP = 30; -const AIR_ACCELERATE = 100; -const TURN_RATE = (100 * Math.PI) / 180; - -/** One tick of the demo, in Source units (x forward, y left, z up) and seconds. */ -export interface StrafeTick { - x: number; - y: number; - z: number; - /** Horizontal speed, the number a speedometer shows. */ - speed: number; - /** Where the player looks, in radians. */ - yaw: number; - /** The strafe key held: A turns left, D right. */ - key: "A" | "D"; - /** True on the tick the player lands and jumps again. */ - jump: boolean; -} - -/** - * Runs `seconds` of perfect hops from running speed. Each hop is one strafe: the player holds A and turns the - * mouse left, lands, jumps on the same tick, then holds D and turns right. Speed is never set, only gained: - * it comes out of Source's air acceleration (PM_AirAccelerate), the same rule the game runs. - */ -export function simulateStrafes(seconds: number): StrafeTick[] { - const ticks: StrafeTick[] = []; - // Facing a quarter turn right of the way forward, so the alternating strafes weave around the x axis. - let yaw = -TURN_RATE * airTime() * 0.5; - let vx = MAX_SPEED * Math.cos(yaw); - let vy = MAX_SPEED * Math.sin(yaw); - let vz = JUMP_SPEED; - let x = 0; - let y = 0; - let z = 0; - let left = true; - - for (let tick = 0; tick * TICK < seconds; tick++) { - let jump = tick === 0; - if (z <= 0 && vz < 0) { - // Jumping on the landing tick skips ground friction, so no speed is lost between hops. - z = 0; - vz = JUMP_SPEED; - left = !left; - jump = true; - } - - yaw += (left ? 1 : -1) * TURN_RATE * TICK; - // A or D alone: the wanted direction is square to the view, to the side being turned towards. - const wishX = Math.cos(yaw + (left ? 1 : -1) * (Math.PI / 2)); - const wishY = Math.sin(yaw + (left ? 1 : -1) * (Math.PI / 2)); - // The air cap is what makes strafing work: only speed along the wanted direction is limited, so steering - // keeps that projection low and every tick adds a little speed sideways. - const current = vx * wishX + vy * wishY; - const add = Math.min( - AIR_WISH_CAP - current, - AIR_ACCELERATE * MAX_SPEED * TICK, - ); - if (add > 0) { - vx += add * wishX; - vy += add * wishY; - } - - vz -= GRAVITY * TICK; - x += vx * TICK; - y += vy * TICK; - z = Math.max(z + vz * TICK, 0); - ticks.push({ - x, - y, - z, - speed: Math.hypot(vx, vy), - yaw, - key: left ? "A" : "D", - jump, - }); - } - return ticks; -} - -function airTime(): number { - return (2 * JUMP_SPEED) / GRAVITY; -} - -/** How long one tick lasts, for playing the ticks back in real time. */ -export const tickSeconds = TICK; diff --git a/web/src/features/leaderboards/BoardChoices.tsx b/web/src/features/leaderboards/BoardChoices.tsx index b794fe7..7df8f4b 100644 --- a/web/src/features/leaderboards/BoardChoices.tsx +++ b/web/src/features/leaderboards/BoardChoices.tsx @@ -7,8 +7,18 @@ import { ChoiceMenu } from "@/ui/ChoiceMenu"; import { LinkTabs } from "@/ui/LinkTabs"; export type Track = Schemas["LeaderboardTrack"]; -/** Players per page of a full list. */ -export const LIST_PAGE_SIZE = 50; +/** + * Players per page: 15 on a full list (a screen's worth), 20 on each of the overview's two lists. Either turns + * pages in the browser, from chunks of players loaded a request at a time (`useStandingsPages`). Here and not in + * a client module, whose exports reach server code only as references. + */ +export const LIST_PAGE_SIZE = 15; +export const OVERVIEW_PAGE_SIZE = 20; +/** + * A multiple of both page sizes, so every page lies within one chunk: with 100, page 7 of 15 (players 91 to 105) + * spanned two chunks and showed only the first one's ten. + */ +export const STANDINGS_CHUNK = 60; type Styles = Awaited>; export interface BoardParams { diff --git a/web/src/features/leaderboards/LeaderboardList.tsx b/web/src/features/leaderboards/LeaderboardList.tsx index b650e37..2070cb2 100644 --- a/web/src/features/leaderboards/LeaderboardList.tsx +++ b/web/src/features/leaderboards/LeaderboardList.tsx @@ -1,4 +1,5 @@ -// One leaderboard in full, by points or by completions, under the same choices as the overview it opens from. +// One leaderboard in full, by points or by completions, a page at a time, under the same choices as the overview +// it opens from. import { ArrowLeft } from "lucide-react"; import { api } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; @@ -12,6 +13,7 @@ import { boardQuery, completedLabel, LIST_PAGE_SIZE, + STANDINGS_CHUNK, } from "./BoardChoices"; import { PointsNote } from "./PointsNote"; import { StandingsTable } from "./StandingsTable"; @@ -27,17 +29,27 @@ export function listTitle(ranking: Ranking, track: string | undefined) { export async function LeaderboardList({ ranking, params, + page: requested, }: { ranking: Ranking; params: BoardParams; + /** `?page=` as given. */ + page?: string; }) { + const page = Math.max(1, Math.floor(Number(requested)) || 1); + // The chunk of players the page falls in; the table turns pages within it, and loads the chunks beside it ahead. + const chunk = Math.floor(((page - 1) * LIST_PAGE_SIZE) / STANDINGS_CHUNK); const styles = await currentStyles(); const board = boardFrom(params, styles); const list = await api .GET("/v1/leaderboards/{ranking}", { params: { path: { ranking }, - query: { ...boardApiQuery(board), limit: LIST_PAGE_SIZE }, + query: { + ...boardApiQuery(board), + limit: STANDINGS_CHUNK, + offset: chunk * STANDINGS_CHUNK, + }, }, }) .then((result) => result.data) @@ -68,14 +80,28 @@ export async function LeaderboardList({

    This leaderboard couldn't be loaded. Try again in a moment.

    ) : list.standings.length === 0 ? ( - {ranking === "points" - ? !board.legacy && !list.points.tiers - ? "Points start once maps have tiers." - : "Nobody has points here yet." - : "Nobody has finished one yet."} + {chunk > 0 + ? "There's no page this far." + : ranking === "points" + ? !board.legacy && !list.points.tiers + ? "Points start once maps have tiers." + : "Nobody has points here yet." + : "Nobody has finished one yet."} ) : ( - + // Keyed by the board, so another choice starts again from what the server sent. + )} {list && ranking === "points" && ( diff --git a/web/src/features/leaderboards/Leaderboards.tsx b/web/src/features/leaderboards/Leaderboards.tsx index f3a502f..d72f283 100644 --- a/web/src/features/leaderboards/Leaderboards.tsx +++ b/web/src/features/leaderboards/Leaderboards.tsx @@ -1,144 +1,106 @@ // The Leaderboards page: in one style and kind of track, the top players by points and by completions, side -// by side. Pre-2.0 switches both lists to the old site's records. -import { ArrowRight } from "lucide-react"; -import type { CSSProperties, ReactNode } from "react"; +// by side, each a page at a time with its own pager, turning without a wait (StandingsPanel). Pre-2.0 switches +// both lists to the old site's records. import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; -import { Avatar } from "@/ui/Avatar"; -import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Link } from "@/ui/Link"; -import { Medal } from "@/ui/Medal"; import { + type Board, type BoardParams, BoardChoices, boardApiQuery, boardFrom, boardQuery, completedLabel, + STANDINGS_CHUNK as CHUNK, + OVERVIEW_PAGE_SIZE as PAGE_SIZE, } from "./BoardChoices"; import { PointsNote } from "./PointsNote"; +import { StandingsPanel } from "./StandingsPanel"; -type Standing = Schemas["Standing"]; +type Ranking = Schemas["Ranking"]; + +/** Each list keeps its own page in the address, so paging one leaves the other where it is. */ +const PAGE_PARAM: Record = { + points: "points_page", + completed: "completed_page", +}; const numbers = new Intl.NumberFormat("en"); -const percent = new Intl.NumberFormat("en", { style: "percent" }); -export async function Leaderboards({ params }: { params: BoardParams }) { +export async function Leaderboards({ + params, + pages, +}: { + params: BoardParams; + /** The `points_page` and `completed_page` from the address, as given. */ + pages: Partial>; +}) { const styles = await currentStyles(); const choice = boardFrom(params, styles); - const legacy = choice.legacy; - const board = await api - .GET("/v1/leaderboards", { params: { query: boardApiQuery(choice) } }) - .then((result) => result.data) - .catch(() => undefined); const query = boardQuery(choice, styles); + const chunkOf = (ranking: Ranking) => { + const page = Math.max(1, Math.floor(Number(pages[ranking])) || 1); + return Math.floor(((page - 1) * PAGE_SIZE) / CHUNK); + }; + const [points, completed] = await Promise.all([ + load("points", choice, chunkOf("points")), + load("completed", choice, chunkOf("completed")), + ]); + const formula = points?.points ?? completed?.points; + const apiQuery = boardApiQuery(choice); return ( -
    +
    - - {!board ? ( -

    The leaderboards couldn't be loaded. Try again in a moment.

    - ) : ( - <> - {/* Keyed by what's shown, so every row enters on a new choice, not only the players who are new. */} -
    - numbers.format(standing.points)} - /> - ( - <> - {numbers.format(standing.completed)} - {board.out_of > 0 && ( - - {percent.format(standing.completed / board.out_of)} - - )} - - )} - /> -
    - - - )} + {/* Keyed by the board, so another choice starts both lists again from what the server sent. */} +
    + + +
    + {formula && }
    ); } -function List({ - title, - more, - standings, - empty, - value, -}: { - title: string; - /** The full list's page. */ - more: string; - standings: Standing[]; - empty: string; - value: (standing: Standing) => ReactNode; -}) { - return ( - -

    {title}

    - {standings.length === 0 ? ( -

    {empty}

    - ) : ( -
      - {standings.map((standing, index) => ( -
    1. - - - - {standing.player.name} - - - - {value(standing)} - -
    2. - ))} -
    - )} - {standings.length > 0 && ( - - Show more - - - )} -
    - ); +/** The chunk of players the page asked for falls in; undefined when it can't be loaded. */ +function load(ranking: Ranking, board: Board, chunk: number) { + return api + .GET("/v1/leaderboards/{ranking}", { + params: { + path: { ranking }, + query: { ...boardApiQuery(board), limit: CHUNK, offset: chunk * CHUNK }, + }, + }) + .then((result) => result.data) + .catch(() => undefined); } diff --git a/web/src/features/leaderboards/StandingsPanel.tsx b/web/src/features/leaderboards/StandingsPanel.tsx new file mode 100644 index 0000000..e2771ef --- /dev/null +++ b/web/src/features/leaderboards/StandingsPanel.tsx @@ -0,0 +1,197 @@ +"use client"; +// One list of the Leaderboards page, a page of 20 at a time, turning without a wait (`useStandingsPages`). +import type { CSSProperties, ReactNode } from "react"; +import type { Schemas } from "@/api/client"; +import { Avatar } from "@/ui/Avatar"; +import { Flag } from "@/ui/Flag"; +import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; +import { OVERVIEW_PAGE_SIZE as PAGE_SIZE } from "./BoardChoices"; +import { useStandingsPages } from "./useStandingsPages"; +import { avatarSrc } from "@/features/players/avatarSrc"; + +type Standing = Schemas["ListedStanding"]; +type Ranking = Schemas["Ranking"]; + +const numbers = new Intl.NumberFormat("en"); +const percent = new Intl.NumberFormat("en", { style: "percent" }); + +export function StandingsPanel({ + ranking, + title, + note, + full, + param, + apiQuery, + first, + firstChunk, + total, + outOf, + bonuses, + empty, +}: { + ranking: Ranking; + title: string; + /** Beside the title, e.g. that points are a draft. */ + note?: string; + /** The list on its own page, with more columns. */ + full: string; + /** This list's page in the address. */ + param: string; + /** What the API takes for this board, without the paging. */ + apiQuery: Record; + /** The chunk the page asked for falls in, from the server; undefined when it couldn't be loaded. */ + first: Standing[] | undefined; + firstChunk: number; + total: number; + /** What completions are counted out of. */ + outOf: number; + bonuses: boolean; + empty: string; +}) { + const { + page, + pageCount, + shown, + failed, + turned, + pageHref, + onPagerClick, + onPagerSubmit, + } = useStandingsPages({ + ranking, + apiQuery, + first, + firstChunk, + total, + pageSize: PAGE_SIZE, + param, + path: "/leaderboards", + }); + + return ( +
    +
    +

    + {title} + {note && ( + {note} + )} +

    + + Full table + +
    + {total === 0 && first ? ( +

    {empty}

    + ) : !shown ? ( +

    + {failed + ? "This list couldn't be loaded. Try again in a moment." + : "Loading…"} +

    + ) : ( +
      + {shown.map((standing, index) => ( +
    1. + + {ranking === "points" ? ( + <> + + {numbers.format(standing.points)} + + + {numbers.format(standing.completed)}{" "} + {bonuses ? "bonuses" : "maps"} + + + ) : ( + <> + + {numbers.format(standing.completed)} + + {outOf > 0 && ( + + {percent.format(standing.completed / outOf)} + + )} + + )} + +
    2. + ))} +
    + )} + {total > PAGE_SIZE && ( +
    + +
    + )} +
    + ); +} + +function Row({ + standing, + place, + children, +}: { + standing: Standing; + /** + * The row's place down the list, counted 1, 2, 3 even where players tie: a column of the same rank repeated + * read as a mistake. Ties keep the API's order. + */ + place: number; + children: ReactNode; +}) { + return ( + + + + {/* The flag sits close to the name it belongs to; most players have no country on Steam, and a + placeholder on every row would only be noise. */} + + + {standing.player.name} + + {standing.player.country_code && ( + + )} + + + {children} + + + ); +} diff --git a/web/src/features/leaderboards/StandingsTable.tsx b/web/src/features/leaderboards/StandingsTable.tsx index 8b6a083..c99d43e 100644 --- a/web/src/features/leaderboards/StandingsTable.tsx +++ b/web/src/features/leaderboards/StandingsTable.tsx @@ -1,13 +1,13 @@ "use client"; -// One leaderboard in full, as a table: the first 50 come with the page and "Show more" loads 50 at a time. -// Beside each player's points and completions, their share of the tracks and their world records. -import { type CSSProperties, useState } from "react"; -import { api, type Schemas } from "@/api/client"; +// One leaderboard in full, as a table, 15 players a page, turning without a wait (`useStandingsPages`). Beside each +// player's points and completions, their share of the tracks and their world records. +import type { CSSProperties } from "react"; +import type { Schemas } from "@/api/client"; import { Avatar } from "@/ui/Avatar"; -import { Button } from "@/ui/Button"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; import { Table, TableBody, @@ -17,98 +17,105 @@ import { TableRow, } from "@/ui/Table"; import { LIST_PAGE_SIZE as PAGE_SIZE } from "./BoardChoices"; +import { useStandingsPages } from "./useStandingsPages"; +import { avatarSrc } from "@/features/players/avatarSrc"; const numbers = new Intl.NumberFormat("en"); const percent = new Intl.NumberFormat("en", { style: "percent" }); -type List = Schemas["LeaderboardList"]; +type Standing = Schemas["ListedStanding"]; -/** Give it a `key` per board, so another choice starts again from the top. */ export function StandingsTable({ + ranking, + apiQuery, first, + firstChunk, + total, + outOf, + legacy, + path, completedLabel, }: { - first: List; + ranking: Schemas["Ranking"]; + /** What the API takes for this board, without the paging. */ + apiQuery: Record; + /** The chunk the page asked for falls in, from the server. */ + first: Standing[]; + firstChunk: number; + total: number; + /** What completions are counted out of. */ + outOf: number; + /** The Pre-2.0 view, which has no world records to count. */ + legacy: boolean; + /** This list's own page, which the address keeps. */ + path: string; /** "Completed maps" or "Completed bonuses". */ completedLabel: string; }) { - const [standings, setStandings] = useState(first.standings); - // Rows read so far, counting repeats, so a page of players already shown still moves the next one on. - const [offset, setOffset] = useState(first.standings.length); - const [loading, setLoading] = useState(false); - const [failed, setFailed] = useState(false); - // Set when a page comes back empty: players left the board since the first page, so the total overstates it. - const [ended, setEnded] = useState(false); - const complete = ended || standings.length >= first.total; - const byPoints = first.ranking === "points"; - const legacy = first.view === "legacy"; - - async function showMore() { - setLoading(true); - setFailed(false); - const loaded = await api - .GET("/v1/leaderboards/{ranking}", { - params: { - path: { ranking: first.ranking }, - query: { - ...(legacy - ? { view: "legacy" } - : { - style: first.style ?? undefined, - track: first.track, - view: "current", - }), - limit: PAGE_SIZE, - offset, - }, - }, - }) - .then((result) => result.data) - .catch(() => undefined); - setLoading(false); - if (!loaded) { - setFailed(true); - return; - } - if (loaded.standings.length === 0) setEnded(true); - setOffset((read) => read + loaded.standings.length); - // Standings move while someone reads them, so a player already shown can come again on a later page. - setStandings((shown) => { - const seen = new Set(shown.map((standing) => standing.player.steamid64)); - return [ - ...shown, - ...loaded.standings.filter( - (standing) => !seen.has(standing.player.steamid64), - ), - ]; - }); - } + const { + page, + pageCount, + shown, + failed, + turned, + pageHref, + onPagerClick, + onPagerSubmit, + } = useStandingsPages({ + ranking, + apiQuery, + first, + firstChunk, + total, + pageSize: PAGE_SIZE, + param: "page", + path, + }); + const byPoints = ranking === "points"; // The ranked value comes first after the player, the other one after it. - const pointsCell = (standing: Schemas["ListedStanding"]) => ( + const pointsCell = (standing: Standing) => ( {numbers.format(standing.points)} ); - const completedCell = (standing: Schemas["ListedStanding"]) => ( + const completedCell = (standing: Standing) => ( {numbers.format(standing.completed)} - {first.out_of > 0 && ( + {outOf > 0 && ( - {percent.format(standing.completed / first.out_of)} + {percent.format(standing.completed / outOf)} )} ); + if (!shown) { + return ( +

    + {failed + ? "This page couldn't be loaded. Try again in a moment." + : "Loading…"} +

    + ); + } + return (
    - + {/* On a phone the first view is the rank, the player and the ranked number, ending at the edge; the other + numbers scroll into view. The lead is the rank column and the ranked number's (measured, with a little + to spare), with the completed heading on two lines there. */} +
    - Rank + {/* Centered over the medals and numbers, which are narrower than the heading. */} + + Rank + {/* The player column takes the spare width, so the numbers sit together on the right, evenly spaced. */} - Player + + Player + {byPoints ? ( <> Points @@ -116,7 +123,9 @@ export function StandingsTable({ ) : ( <> - {completedLabel} + + {completedLabel} + Points )} @@ -126,34 +135,43 @@ export function StandingsTable({ - {standings.map((standing, index) => ( + {shown.map((standing, index) => ( - - + + {/* Counted down the list, not the shared rank of a tie, as on the overview (StandingsPanel). */} + + + - - + + + {/* Left out below 360px, where the name needs the room. */} - {standing.player.name} + {standing.player.name} - + {standing.player.country_code && ( + + )} {byPoints ? ( @@ -176,23 +194,17 @@ export function StandingsTable({ ))}
    -
    - - {complete - ? `All ${numbers.format(ended ? standings.length : first.total)} players` - : `Top ${numbers.format(standings.length)} of ${numbers.format(first.total)} players`} - - {failed && ( - - More couldn't be loaded. Try again. - - )} - {!complete && ( - - )} -
    + {pageCount > 1 && ( +
    + +
    + )}
    ); } diff --git a/web/src/features/leaderboards/useStandingsPages.ts b/web/src/features/leaderboards/useStandingsPages.ts new file mode 100644 index 0000000..2bb65b2 --- /dev/null +++ b/web/src/features/leaderboards/useStandingsPages.ts @@ -0,0 +1,174 @@ +// Paging a leaderboard without a wait, as on the Activity board: the server sends the chunk of players the page +// asked for falls in, pages within it turn here at once, and the chunks either side load ahead, so Next and +// Previous never wait. The page lives in the address (pushed, so Back works), and the pager's links and form still +// work without script. Shared by the overview's lists (StandingsPanel) and the full tables (StandingsTable). +import { useSearchParams } from "next/navigation"; +import { + type FormEvent, + type MouseEvent, + useCallback, + useEffect, + useRef, + useState, +} from "react"; +import { api, type Schemas } from "@/api/client"; +import { STANDINGS_CHUNK } from "./BoardChoices"; + +type Standing = Schemas["ListedStanding"]; + +export function useStandingsPages({ + ranking, + apiQuery, + first, + firstChunk, + total, + pageSize, + param, + path, +}: { + ranking: Schemas["Ranking"]; + /** What the API takes for this board, without the paging. */ + apiQuery: Record; + /** The chunk the page asked for falls in, from the server; undefined when it couldn't be loaded. */ + first: Standing[] | undefined; + firstChunk: number; + total: number; + pageSize: number; + /** This list's page in the address. */ + param: string; + /** The page's path, which the address keeps. */ + path: string; +}) { + const params = useSearchParams(); + const asked = Math.max(1, Math.floor(Number(params.get(param))) || 1); + const [chunks, setChunks] = useState>( + first ? { [firstChunk]: first } : {}, + ); + const [failed, setFailed] = useState(false); + /** Set after the first turn: pages turned here appear at once, without the rows' entrance. */ + const [turned, setTurned] = useState(false); + const inFlight = useRef(new Map>()); + /** The chunks loaded so far, read by `load` without waiting for a render. */ + const loaded = useRef(chunks); + + // A page is cut from one chunk, so it has to divide the chunk evenly; else a page spanning two would come up short. + if (STANDINGS_CHUNK % pageSize !== 0) { + throw new Error( + `A page of ${pageSize} doesn't divide a chunk of ${STANDINGS_CHUNK}`, + ); + } + const pageCount = Math.max(1, Math.ceil(total / pageSize)); + const page = Math.min(asked, pageCount); + const chunkOf = useCallback( + (p: number) => Math.floor(((p - 1) * pageSize) / STANDINGS_CHUNK), + [pageSize], + ); + + const load = useCallback( + (k: number): Promise => { + if (loaded.current[k]) return Promise.resolve(true); + const pending = inFlight.current.get(k); + if (pending) return pending; + const request = api + .GET("/v1/leaderboards/{ranking}", { + params: { + path: { ranking }, + query: { + ...apiQuery, + limit: STANDINGS_CHUNK, + offset: k * STANDINGS_CHUNK, + }, + }, + }) + .then((result) => result.data) + .catch(() => undefined) + .then((list) => { + inFlight.current.delete(k); + if (!list) { + setFailed(true); + return false; + } + setFailed(false); + loaded.current = { ...loaded.current, [k]: list.standings }; + setChunks(loaded.current); + return true; + }); + inFlight.current.set(k, request); + return request; + }, + [ranking, apiQuery], + ); + + // The page shown, and the chunks either side of it, ready before they're asked for. + const shownChunk = chunkOf(page); + useEffect(() => { + void load(shownChunk).then((ok) => { + if (!ok) return; + if ((shownChunk + 1) * STANDINGS_CHUNK < total) void load(shownChunk + 1); + if (shownChunk > 0) void load(shownChunk - 1); + }); + }, [shownChunk, total, load]); + + /** This list's page in the address, keeping the board and any other list's page. */ + const pageHref = useCallback( + (to: number) => { + const search = new URLSearchParams(params.toString()); + if (to > 1) search.set(param, String(to)); + else search.delete(param); + const text = search.toString(); + return text ? `${path}?${text}` : path; + }, + [params, param, path], + ); + + const turns = useRef(0); + async function go(target: number) { + const turn = ++turns.current; + const wanted = Math.min(Math.max(1, target), pageCount); + if (!(await load(chunkOf(wanted))) || turn !== turns.current) return; + setTurned(true); + window.history.pushState(null, "", pageHref(wanted)); + } + + /** For the pager's wrapper, in the capture phase: turns pages here instead of loading them. */ + function onPagerClick(event: MouseEvent) { + const link = (event.target as HTMLElement).closest("a"); + if ( + !link || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + // Stopped here too, as Next's Link navigates even when the event is already prevented. + event.preventDefault(); + event.stopPropagation(); + void go(Number(new URL(link.href).searchParams.get(param) ?? 1)); + } + + /** The pager's "go to page" form. */ + function onPagerSubmit(event: FormEvent) { + event.preventDefault(); + event.stopPropagation(); + const form = event.target as HTMLFormElement; + const typed = Math.floor(Number(new FormData(form).get(param))); + form.reset(); + if (typed >= 1) void go(typed); + } + + const chunk = chunks[shownChunk]; + const start = (page - 1) * pageSize - shownChunk * STANDINGS_CHUNK; + return { + page, + pageCount, + /** The page's rows; undefined while they load or when they couldn't be. */ + shown: chunk?.slice(start, start + pageSize), + failed, + turned, + pageHref, + onPagerClick, + onPagerSubmit, + }; +} diff --git a/web/src/features/legacy/LegacyRunDetailList.tsx b/web/src/features/legacy/LegacyRunDetailList.tsx index 5d79f26..daf1d18 100644 --- a/web/src/features/legacy/LegacyRunDetailList.tsx +++ b/web/src/features/legacy/LegacyRunDetailList.tsx @@ -13,6 +13,7 @@ import { DividedList } from "@/ui/Divided"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { LegacyBadge } from "./LegacyBadge"; +import { avatarSrc } from "@/features/players/avatarSrc"; export function LegacyRunDetailList({ run, @@ -37,7 +38,7 @@ export function LegacyRunDetailList({ {/* Behind the pre-2.0 record, put before the time as for 2.0 runs. */} {gap > 0 && ( - + {formatGap(gap)} )} @@ -51,11 +52,13 @@ export function LegacyRunDetailList({ > - {run.player.name} - + + {run.player.name} + + {run.player_name !== run.player.name && ( diff --git a/web/src/features/maps/Leaderboard.tsx b/web/src/features/maps/Leaderboard.tsx index aea520d..ddbf0f7 100644 --- a/web/src/features/maps/Leaderboard.tsx +++ b/web/src/features/maps/Leaderboard.tsx @@ -1,19 +1,29 @@ "use client"; // A map's leaderboard for one style, track and view: the 2.0 top comes with the page, other views load their -// first page when chosen, and "Show more" loads the rest a page at a time. The signed-in player's row stands -// out, and legacy runs carry the Pre-2.0 badge. +// first page when chosen, and "Show more" loads the rest a page at a time. Headings sort it: the API orders +// boards by time only, so sorting by anything else loads the whole board and sorts it here. The signed-in +// player's row stands out; on the 2.0 board, when it isn't among the rows shown, it's pinned below them. Legacy +// runs carry the Pre-2.0 badge. import { useEffect, useState } from "react"; import { api, type Schemas } from "@/api/client"; import { LegacyBadge } from "@/features/legacy/LegacyBadge"; import type { View } from "@/features/legacy/views"; +import { ReplayLink } from "@/features/replays/ReplayLink"; import { RunLink } from "@/features/runs/RunLink"; -import { formatDate, formatGap, formatTime } from "@/features/runs/time"; +import { + formatAge, + formatDate, + formatGap, + formatTime, +} from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; import { Button } from "@/ui/Button"; +import { classNames } from "@/ui/classNames"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { SortButton } from "@/ui/SortButton"; import { Table, TableBody, @@ -22,10 +32,63 @@ import { TableHeaderCell, TableRow, } from "@/ui/Table"; +import { avatarSrc } from "@/features/players/avatarSrc"; const PAGE_SIZE = 50; +/** The API's largest page, for loading a whole board to sort. */ +const FULL_PAGE_SIZE = 100; const sync = new Intl.NumberFormat("en", { maximumFractionDigits: 1 }); +type Entry = Schemas["LeaderboardEntry"]; +type SortKey = "time" | "player" | "jumps" | "strafes" | "sync" | "date"; +interface Sort { + key: SortKey; + descending: boolean; +} + +/** Which way a column sorts on its first click: best sync and newest date first, the rest from the smallest. */ +const descendingFirst: Record = { + time: false, + player: false, + jumps: false, + strafes: false, + sync: true, + date: true, +}; + +/** Entries in the chosen order; ties keep the board's order by time. */ +function sorted(entries: Entry[], sort: Sort): Entry[] { + if (sort.key === "time" && !sort.descending) return entries; + const value = (entry: Entry): number | string => { + switch (sort.key) { + case "time": + return entry.time; + case "player": + return entry.player.name.toLowerCase(); + case "jumps": + return entry.jumps; + case "strafes": + return entry.strafes; + case "sync": + return entry.sync; + case "date": + // Runs without a date sort as the oldest. + return entry.finished_at ? Date.parse(entry.finished_at) : 0; + } + }; + const direction = sort.descending ? -1 : 1; + return entries + .map((entry, index) => ({ entry, index, value: value(entry) })) + .sort((a, b) => + a.value < b.value + ? -direction + : a.value > b.value + ? direction + : a.index - b.index, + ) + .map(({ entry }) => entry); +} + /** A page of a board, as the leaderboard endpoint or (for 2.0's top) the map's details give it. */ export type BoardPage = Pick< Schemas["Leaderboard"], @@ -55,6 +118,9 @@ export function Leaderboard({ const [cursor, setCursor] = useState(first?.next_cursor); const [loading, setLoading] = useState(false); const [failed, setFailed] = useState(false); + const [sort, setSort] = useState({ key: "time", descending: false }); + // The signed-in player's own entry, wherever on the board it is. Only the 2.0 board ranks them. + const [mine, setMine] = useState(); // A refreshed page (after a staff change, say) brings a new first page; start again from it. const [shownFrom, setShownFrom] = useState(first); if (first && shownFrom !== first) { @@ -64,12 +130,12 @@ export function Leaderboard({ setCursor(first.next_cursor); } - function fetchPage(after: string | undefined) { + function fetchPage(after: string | undefined, limit = PAGE_SIZE) { return api .GET("/v1/maps/{map}/leaderboard", { params: { path: { map }, - query: { style, track, view, limit: PAGE_SIZE, cursor: after }, + query: { style, track, view, limit, cursor: after }, }, }) .then((result) => result.data) @@ -96,6 +162,39 @@ export function Leaderboard({ show(loaded, after); } + /** + * Sorts by a column: again on the same one turns it around. Any order but time's needs the whole board. + * shortcut: loads every row in the browser, 100 a request; fine for boards of a few hundred players, ask the API + * for a `sort` parameter when boards grow to thousands. + */ + async function sortBy(key: SortKey) { + const next: Sort = + sort.key === key + ? { key, descending: !sort.descending } + : { key, descending: descendingFirst[key] }; + if (key !== "time" && cursor) { + setLoading(true); + setFailed(false); + let all = entries; + let after: string | null | undefined = cursor; + while (after) { + const loaded = await fetchPage(after, FULL_PAGE_SIZE); + if (!loaded) { + setLoading(false); + setFailed(true); + return; + } + all = [...all, ...loaded.entries]; + after = loaded.next_cursor; + setPage(loaded); + } + setEntries(all); + setCursor(undefined); + setLoading(false); + } + setSort(next); + } + // Views other than 2.0's don't come with the map; their first page loads once the view is chosen. useEffect(() => { if (!first) @@ -103,6 +202,23 @@ export function Leaderboard({ // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another board }, []); + // The top that comes with the map doesn't carry the player's own place; one row is asked for here, unless + // they're already in that top. + useEffect(() => { + if (!me || view !== "current") return; + if (first?.entries.some((entry) => entry.player.steamid64 === me)) return; + void api + .GET("/v1/maps/{map}/leaderboard", { + params: { + path: { map }, + query: { style, track, limit: 1, player: me }, + }, + }) + .then((result) => setMine(result.data?.player_entry ?? undefined)) + .catch(() => undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another board + }, []); + if (!page) { return failed ? (

    @@ -112,86 +228,124 @@ export function Leaderboard({ } const fastest = page.fastest_time; const record = page.world_record_time; + // Once "Show more" (or sorting, which loads the whole board) reaches them, their row is in the list and isn't + // pinned twice. + const pinned = + mine && + !entries.some((entry) => entry.run_id === mine.run_id && !entry.legacy) + ? mine + : undefined; + const heading = (key: SortKey, label: string) => ( + void sortBy(key)} + /> + ); + const ariaSort = (key: SortKey) => + sort.key === key + ? sort.descending + ? ("descending" as const) + : ("ascending" as const) + : undefined; return (

    - +
    - Place - Player - Time - Gap - Jumps - Strafes - Sync - Date + {/* Short columns center under their names: a medal, a WR badge and a few digits are all narrower than + the heading, and right-aligned they sat off to one side of it. Times and dates keep to the right. + Place and Gap follow the time, so Time sorts for them. */} + {/* "#" on a phone, as on Activity: the word would widen the column well past its medals. */} + + Place + + # + + Place + + + {heading("player", "Player")} + + + {heading("time", "Time")} + + {/* Narrow padding keeps the play button close to the time, as on Activity. */} + + Replay + + {/* On a phone the gap and age go under the time instead, and these columns step aside. */} + + Gap + + + {heading("jumps", "Jumps")} + + + {heading("strafes", "Strafes")} + + + {heading("sync", "Sync")} + + + {heading("date", "Date")} + - {entries.map((entry) => ( - ( + - - {/* Medals mark 2.0 standings; the other views are lists by time. */} - - - - - - - {entry.player.name} - - - {entry.legacy && } - - - - - {formatTime(entry.time)} - - - - {!entry.legacy && entry.time === record ? ( - WR - ) : entry.time === fastest || fastest == null ? null : ( - formatGap(entry.time - fastest) - )} - - - {entry.jumps} - - - {entry.strafes} - - - {sync.format(entry.sync)}% - - - {entry.finished_at ? ( - - ) : ( - "–" - )} - - + entry={entry} + view={view} + mine={entry.player.steamid64 === me} + record={record} + fastest={fastest} + /> ))} + {pinned && ( + // Its own body, so the line above it reads as a gap in the list rather than the next place. + + + + )}
    @@ -201,7 +355,7 @@ export function Leaderboard({ {failed && ( - More couldn't be loaded. Try again. + The rest of the board couldn't be loaded. Try again. )} {cursor && ( @@ -217,3 +371,127 @@ export function Leaderboard({
    ); } + +/** One player's row: place, player, time (with the gap and age under it on a phone), replay, gap, stats and date. */ +function EntryRow({ + entry, + view, + mine, + record, + fastest, + separated = false, +}: { + entry: Entry; + view: View; + /** The signed-in player's own row, which stands out. */ + mine: boolean; + record: number | null | undefined; + fastest: number | null | undefined; + /** Set apart from the rows above it. */ + separated?: boolean; +}) { + return ( + + + {/* Medals mark 2.0 standings; the other views are lists by time. */} + + + + + {/* On a phone the player column takes only the room left (`max-w-0` with full width), and a long + name ends in an ellipsis rather than pushing the times off the screen. */} + + + + {/* Left out on a phone, as on Activity's rows there: the name needs the room more. */} + + {entry.player.name} + + {/* A missing country's placeholder costs a phone's narrow column more than it tells. */} + + {entry.legacy && } + + + + + + + {formatTime(entry.time)} + + {/* On a phone, the Gap column's record mark beside the time; a gap goes on the line below. */} + {!entry.legacy && entry.time === record && ( + + WR + + )} + + {/* Under the time on a phone: the gap and how long ago. Beside the time, the longest gap would + widen the whole column and leave the names a few letters. */} + + {!(!entry.legacy && entry.time === record) && + entry.time !== fastest && + fastest != null && ( + + ({formatGap(entry.time - fastest)}) + + )} + {entry.finished_at && ( + // Counted from now, which differs between the server's render and the browser's. + + )} + + + + + {/* Replays open by 2.0 run ID; a pre-2.0 run's ID is the old site's. */} + {!entry.legacy && } + + + {!entry.legacy && entry.time === record ? ( + WR + ) : entry.time === fastest || fastest == null ? null : ( + {formatGap(entry.time - fastest)} + )} + + + {entry.jumps} + + + {entry.strafes} + + + {sync.format(entry.sync)}% + + + {entry.finished_at ? ( + + ) : ( + "–" + )} + + + ); +} diff --git a/web/src/features/maps/MapBanner.tsx b/web/src/features/maps/MapBanner.tsx index 9f7734f..b147fe1 100644 --- a/web/src/features/maps/MapBanner.tsx +++ b/web/src/features/maps/MapBanner.tsx @@ -1,6 +1,9 @@ "use client"; // A map's banner: its cover, cropped to the strip staff chose. Clicking it shows all the map's pictures whole, -// in a Lightbox. Staff controls for the Manage view come in as `children`, laid over it. +// in a Lightbox. The map's title comes in as `title` and its view tabs as `tabs`. On wide screens (lg up) both are +// laid over the picture's lower edge, so the board below starts sooner. Narrower, a long name and the tabs don't fit +// over it, so the title sits under it on the page and only the tabs stay on the picture. Staff controls for the +// Manage view come in as `children`, laid over the picture too. import { Images } from "lucide-react"; import { type ReactNode, useState } from "react"; import type { Schemas } from "@/api/client"; @@ -10,9 +13,15 @@ import { MapImage } from "./MapImage"; export function MapBanner({ map, images, + title, + tabs, children, }: { map: string; + /** The page's heading, over the picture's bottom left. Clicks pass through it to the picture, bar its links. */ + title?: ReactNode; + /** The map's view tabs, beside the title, or on the picture on a phone. */ + tabs?: ReactNode; /** In order; the first is the cover. */ images: Schemas["MapImage"][]; children?: ReactNode; @@ -22,27 +31,41 @@ export function MapBanner({ return (
    - {cover ? ( - - ) : ( - - )} - {images.length > 1 && ( - - - {images.length} - +
    + {cover ? ( + + ) : ( + + )} + {images.length > 1 && ( + + + {images.length} + + )} + {tabs && ( +
    {tabs}
    + )} +
    + {title && ( + // On wide screens, laid straight over the picture, readable by its own shadow rather than a plate or a scrim. +
    +
    +
    {title}
    + {tabs &&
    {tabs}
    } +
    +
    )} {children} document.getElementById("map-banner-figures"), + () => null, + ); const hasLegacy = map.legacy_players > 0; if (map.tracks.length === 0 && !hasLegacy) { return ( @@ -86,102 +94,177 @@ export function MapBoards({ window.history.replaceState(null, "", url); } + const history = + // The Pre-2.0 view shows the old site's records instead; the two histories are never mixed. + view === "legacy" ? ( + + ) : ( + board && ( + + ) + ); + + // The board comes first, so it starts within the first screen; the record and totals sit on the choices' line, + // and the history follows the board. + // The choices sit close to the board they pick; the history, a separate thing, stands a step further off. return ( <> -
    - {board ? ( - +
    +
    + + ({ + value: key, + label: name(key), + quiet: !hasRuns(key), + }))} + value={styleKey} + onChange={(style) => choose({ style })} + /> + ({ + value: String(t), + label: trackName(t), + quiet: !map.tracks.some((known) => known.track === t), + }))} + value={String(trackNumber)} + onChange={(value) => choose({ track: Number(value) })} + /> + choose({ view: next })} + /> + {track && + track.track > 0 && + track.tier != null && + map.tier_count != null && ( + + )} + + + {bannerSlot && + createPortal( + , + bannerSlot, + )} +
    + + {view === "current" && !board ? ( + + Nobody has a {name(styleKey)} run on{" "} + {trackNumber === 0 ? "the main track" : trackName(trackNumber)} yet. + {onLegacyBoard && " Its pre-2.0 runs are under Runs."} + ) : ( - )} - -
    - - ({ - value: key, - label: name(key), - quiet: !hasRuns(key), - }))} - value={styleKey} - onChange={(style) => choose({ style })} - /> - ({ - value: String(t), - label: trackName(t), - quiet: !map.tracks.some((known) => known.track === t), - }))} - value={String(trackNumber)} - onChange={(value) => choose({ track: Number(value) })} - /> - choose({ view: next })} - /> - {track && - track.track > 0 && - track.tier != null && - map.tier_count != null && ( - - )} - + {history &&
    {history}
    } + + ); +} - {/* The Pre-2.0 view shows the old site's records instead; the two histories are never mixed. */} - {view === "legacy" ? ( - - ) : ( - board && ( - - ) - )} +const number = new Intl.NumberFormat("en"); - {view === "current" && !board ? ( - - Nobody has a {name(styleKey)} run on{" "} - {trackNumber === 0 ? "the main track" : trackName(trackNumber)} yet. - {onLegacyBoard && " Its pre-2.0 runs are under Runs."} - - ) : ( - +/** The banner slot never changes once the page is drawn, so there's nothing to subscribe to. */ +function noChanges() { + return () => {}; +} + +/** The chosen board's world record, players and runs: on the choices' line, or (compact) on the banner. */ +function Figures({ + board, + totals, + compact = false, + className, +}: { + board: Schemas["MapStyle"] | undefined; + totals: { players: number; runs: number }; + compact?: boolean; + className?: string; +}) { + const figure = compact ? "font-bold" : "text-lg font-bold"; + return ( +
    + > +
    +
    World record
    +
    + {board ? ( + + {formatTime(board.world_record.time)} + + ) : ( + – + )} +
    +
    + + +
    + ); +} + +/** A count on the choices' line, the number first: "69 players". */ +function Total({ + label, + value, + figure, +}: { + label: string; + value: number; + figure: string; +}) { + return ( +
    +
    {label}
    +
    + {number.format(value)} +
    +
    ); } @@ -229,19 +312,3 @@ function HistoryCard({ ); } - -function WorldRecordCard({ record }: { record: Schemas["WorldRecord"] }) { - return ( - - {/* Laid out like StatCard, so the three cards' labels and numbers line up. */} -
    - -
    -

    - - {formatTime(record.time)} - -

    -
    - ); -} diff --git a/web/src/features/maps/MapCard.module.css b/web/src/features/maps/MapCard.module.css new file mode 100644 index 0000000..803e6f2 --- /dev/null +++ b/web/src/features/maps/MapCard.module.css @@ -0,0 +1,104 @@ +/* Shared podium columns switch with the card's width, not the viewport's. */ +.cards { + grid-template-columns: minmax(0, 1fr); +} + +.cover { + aspect-ratio: 5 / 2; + min-block-size: calc(var(--spacing) * 32); +} + +.preview { + transition: filter var(--duration-fast); +} + +@media (prefers-reduced-motion: reduce) { + .preview { + transition: none; + } +} + +.podium { + align-content: start; + grid-template-columns: auto auto minmax(0, 1fr); +} + +.entry { + min-block-size: calc(var(--spacing) * 12); + grid-column: 1 / -1; + grid-template-columns: subgrid; +} + +.rank { + grid-column: 1; + grid-row: 1; +} + +.playerLink { + grid-column: 2 / -1; + grid-row: 1; + grid-template-columns: subgrid; +} + +.avatar { + grid-column: 1; + grid-row: 1; + align-self: center; +} + +.player { + grid-column: 2; + grid-row: 1; +} + +.result { + grid-column: 3; + grid-row: 2; +} + +/* Wide cards share aligned time and gap columns; narrow cards put both below the name. */ +@container (min-width: 20rem) { + .podium { + grid-template-columns: + auto auto minmax(0, 1fr) + max-content max-content; + } + + .entry { + min-block-size: calc(var(--spacing) * 8); + } + + .playerLink, + .result { + align-self: center; + } + + .playerLink { + grid-column: 2 / span 2; + } + + .result { + display: grid; + grid-column: 4 / span 2; + grid-row: 1; + grid-template-columns: subgrid; + } +} + +@container (min-width: 42rem) { + .cards { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@container (min-width: 64rem) { + .cards { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} + +@container (min-width: 88rem) { + .cards { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } +} diff --git a/web/src/features/maps/MapCard.tsx b/web/src/features/maps/MapCard.tsx new file mode 100644 index 0000000..d6365b5 --- /dev/null +++ b/web/src/features/maps/MapCard.tsx @@ -0,0 +1,208 @@ +// Map details overlay the preview; records and the signed-in player's PB sit plainly below it. +import type { Schemas } from "@/api/client"; +import { avatarSrc } from "@/features/players/avatarSrc"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { RunLink } from "@/features/runs/RunLink"; +import { formatGap, formatTime } from "@/features/runs/time"; +import { Avatar } from "@/ui/Avatar"; +import { Badge } from "@/ui/Badge"; +import { classNames } from "@/ui/classNames"; +import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { TierBadge } from "@/ui/TierBadge"; +import { MapImage } from "./MapImage"; +import type { MapLeader } from "./mapPodiums"; +import styles from "./MapCard.module.css"; + +const number = new Intl.NumberFormat("en"); + +export function MapCard({ + map, + tierCount, + leaders, + styleName, + styleKey, + showPersonalBest = false, + personalBest, +}: { + map: Schemas["MapSummary"]; + tierCount: number | null | undefined; + leaders: readonly MapLeader[] | null; + styleName: string; + styleKey?: string; + showPersonalBest?: boolean; + personalBest?: MapLeader | null; +}) { + const entries = + leaders ?? (map.world_record ? [{ ...map.world_record, rank: 1 }] : []); + const record = entries[0]; + const fastest = record?.time ?? 0; + + return ( +
    +
    + +
    +
    + {map.tier != null && tierCount != null && ( + + + + )} +

    + + {map.name} + +

    +
    +

    + + {number.format(map.players)}{" "} + {map.players === 1 ? "player" : "players"} + + {map.bonuses > 0 && ( + + {number.format(map.bonuses)}{" "} + {map.bonuses === 1 ? "bonus" : "bonuses"} + + )} +

    +
    +
    +
    +
      + {entries.map((entry) => ( +
    1. + + + + + + + + + {entry.player.name} + + + + + + {formatTime(entry.time)} + + + + {entry.run_id === record?.run_id ? ( + + WR + + ) : ( + + {formatGap(entry.time - fastest)} + + )} + +
    2. + ))} + {entries.length === 0 && ( +
    3. + {leaders === null + ? "Times couldn't be loaded" + : "No times in this style"} +
    4. + )} +
    + {showPersonalBest && ( +
    + Your PB + {personalBest ? ( + <> + + #{number.format(personalBest.rank)} + + + + {formatTime(personalBest.time)} + + {personalBest.time > fastest && fastest > 0 ? ( + + ({formatGap(personalBest.time - fastest)}) + + ) : fastest > 0 ? ( + + {personalBest.run_id === record?.run_id ? "WR" : "WR tie"} + + ) : null} + + + ) : ( + + {personalBest === null ? "Not completed" : "Couldn't load PB"} + + )} +
    + )} +
    +
    + ); +} diff --git a/web/src/features/maps/MapHeader.tsx b/web/src/features/maps/MapHeader.tsx index 4082e73..adfa957 100644 --- a/web/src/features/maps/MapHeader.tsx +++ b/web/src/features/maps/MapHeader.tsx @@ -1,4 +1,4 @@ -// The top of a map's pages: its banner, name and main tier, when it was released and who made it, and the +// The top of a map's pages: its banner with, laid over it, the name and main tier, when it was released and who made it, and the // Map / Zones switch (with Manage for staff). It sits in the map's layout, so switching between the views leaves it in place. import { notFound } from "next/navigation"; import type { Schemas } from "@/api/client"; @@ -34,36 +34,55 @@ export async function MapHeader({ name }: { name: string }) { (map !== undefined || staffMap?.known === true); return ( - <> - - {canEdit && cover && } - -
    -
    -

    {map?.name ?? name}

    - {mainTier != null && tierCount != null && ( - - )} - {/* A map without a finished run has no page to switch to. */} - {map && ( - - )} -
    -

    -

    -

    -
    - + +
    + {/* Inline, so a long name wraps with the badge after it, and `align-middle` centers the badge on the + name's lowercase letters, where the eye reads its middle, rather than on the line box. */} +
    +

    {map?.name ?? name}

    + {mainTier != null && tierCount != null && ( + + {/* Over the picture (lg up), a dark fill of its own, as the tabs and picture count have, so its + outline and label read on any picture; on the page below lg it needs none. */} + + + )} +
    +

    +

    +

    + {/* Below lg, where the title sits under the picture, the map's boards put the chosen board's record, players and runs here (MapBoards), so + its leaderboard starts higher up the screen. */} +
    +
    +
  • + } + tabs={ + // A map without a finished run has no page to switch to. + map && ( + + ) + } + > + {canEdit && cover && } + ); } diff --git a/web/src/features/maps/MapImage.tsx b/web/src/features/maps/MapImage.tsx index 19f234d..71719cd 100644 --- a/web/src/features/maps/MapImage.tsx +++ b/web/src/features/maps/MapImage.tsx @@ -8,7 +8,8 @@ import { classNames } from "@/ui/classNames"; const sizes = { thumbnail: "h-10 w-14 rounded-md sm:h-12 sm:w-20", tile: "h-14 w-24 rounded-md sm:h-20 sm:w-36", - banner: "h-36 w-full rounded-lg sm:h-48", + card: "aspect-video w-full rounded-none border-0", + banner: "h-36 w-full rounded-md lg:h-44", }; export function MapImage({ diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index 73a8f62..d1102a7 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -1,21 +1,20 @@ // The Maps page's totals (maps, tiered maps, maps per tier), its search, sort, style and completion choices, -// and one row per map with its picture, tier and world record. Staff who manage maps also get a "No runs yet" tab +// and one card per map with its picture, tier and top three. Staff who manage maps also get a "No runs yet" tab // and a "Map files" tab for uploading viewer files in bulk, and can set up a map by name before its first run. -import { Search, X } from "lucide-react"; -import Form from "next/form"; +import { X } from "lucide-react"; import type { CSSProperties } from "react"; import { api, type Schemas } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { currentStyles } from "@/features/ruleset/styles"; import { STEAMID } from "@/features/players/steamId"; -import { formatSince, formatTime } from "@/features/runs/time"; +import { formatSince } from "@/features/runs/time"; import { BulkUpload } from "@/features/staff/maps/BulkUpload"; import { UnplayedMaps } from "@/features/staff/maps/UnplayedMaps"; import { Avatar } from "@/ui/Avatar"; -import { Button, ButtonLink } from "@/ui/Button"; +import { ButtonLink } from "@/ui/Button"; import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Input } from "@/ui/Input"; +import { classNames } from "@/ui/classNames"; +import { SearchField } from "@/ui/SearchField"; import { Link } from "@/ui/Link"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; @@ -24,9 +23,13 @@ import { Pager } from "@/ui/Pager"; import { TierBadge } from "@/ui/TierBadge"; import { TierSpread } from "@/ui/TierSpread"; import { managesMaps } from "./MapHeader"; -import { MapImage } from "./MapImage"; +import { MapCard } from "./MapCard"; +import { mapPodiums } from "./mapPodiums"; +import cardStyles from "./MapCard.module.css"; +import overviewStyles from "./MapOverview.module.css"; import { MAP_NAME } from "./mapName"; import { tierParam } from "./tierParam"; +import { avatarSrc } from "@/features/players/avatarSrc"; const PAGE_SIZE = 50; /** In groups (players, name, tier, record), each starting below a line in the menu. */ @@ -116,6 +119,7 @@ export async function MapList({ params }: { params: MapListParams }) { if (files) { return (
    +

    Maps

    {staffTabs}
    @@ -150,6 +154,7 @@ export async function MapList({ params }: { params: MapListParams }) { .catch(() => undefined); const list = result?.data; const style = list?.style ?? requestedStyle; + const podiums = await mapPodiums(list?.maps ?? [], style, me?.steamid64); const typedName = q.toLowerCase(); const offerSetUp = staff && @@ -203,91 +208,78 @@ export async function MapList({ params }: { params: MapListParams }) { }; return ( -
    +
    +

    Maps

    {list && ( - href({ tier: choice })} - newestHref={href({ sort: "newest", tier: null, page: 1 })} - /> + + href({ tier: choice })} + newestHref={href({ sort: "newest", page: 1 })} + /> + )} -
    - {/* Searching keeps the chosen tab, sort, style and completion filter. */} - {unplayed && } - {completion !== "all" && filterPlayer && ( - <> - - - - )} - {sort !== DEFAULT_SORT && ( - - )} - {requestedStyle && ( - - )} - {tier != null && } - - -
    - - {!unplayed && ( - <> - ({ - value: s.key, - label: s.label, - startsGroup: "startsGroup" in s, - href: href({ sort: s.key }), - }))} - value={sort} - /> - {styles.keys.length > 1 && ( +
    + + {!unplayed && ( + <> ({ - value: key, - label: styles.name(key), - href: href({ style: key }), + label="Sort" + options={sorts.map((s) => ({ + value: s.key, + label: s.label, + startsGroup: "startsGroup" in s, + href: href({ sort: s.key }), }))} - value={style ?? styles.keys[0] ?? ""} + value={sort} /> - )} - ({ - value: c.key, - label: c.label, - detail: completionDetail[c.key], - href: href({ completion: c.key }), - disabled: c.key !== "all" && !filterPlayer, - }))} - value={completion} - /> - {completion !== "all" && player && ( - 1 && ( + ({ + value: key, + label: styles.name(key), + href: href({ style: key }), + }))} + value={style ?? styles.keys[0] ?? ""} + /> + )} + ({ + value: c.key, + label: c.label, + detail: completionDetail[c.key], + href: href({ completion: c.key }), + disabled: c.key !== "all" && !filterPlayer, + }))} + value={completion} /> - )} - - )} - {/* Staff only, out of the way of the menus everyone uses. */} - {staff &&
    {staffTabs}
    } -
    + {completion !== "all" && player && ( + + )} + + )} + {/* Staff only, out of the way of the menus everyone uses. */} + {staff &&
    {staffTabs}
    } + + +
    {/* With no results, the empty card below offers this instead. */} {offerSetUp && list && list.maps.length > 0 && ( @@ -314,7 +306,7 @@ export async function MapList({ params }: { params: MapListParams }) { : completion === "no" ? "This player has completed every map here." : q - ? "No map with a run has that name." + ? "No maps match that name or WR holder." : tier != null ? `No map with a run has tier ${tier}.` : "No map has a finished run yet."} @@ -326,30 +318,59 @@ export async function MapList({ params }: { params: MapListParams }) { )} ) : ( - <> - {/* Keyed by what's shown, so a new sort or style remounts every row and they all enter together; - keyed by map alone, rows that stay on the page would swap in place without moving. */} -
      +
      +
      +

      + {q + ? `Maps matching “${q}”` + : tier != null + ? `Tier ${tier} maps` + : "All maps"} +

      +

      + {number.format(list.total)} maps in this view +

      +
      +
        {list.maps.map((map, index) => (
      • - +
      • ))}
      - href({ page: p })} - /> - + {list.total > PAGE_SIZE && ( +
      + href({ page: p })} + /> +
      + )} +
      )}
    ); @@ -376,92 +397,129 @@ function MapStats({ newestHref: string; }) { const tiered = stats.by_tier.reduce((sum, count) => sum + count, 0); - const hasTiers = stats.by_tier.length > 0; - if ( - !hasTiers && - stats.newest.length === 0 && - stats.played_this_week.length === 0 - ) + const hasTiers = stats.by_tier.length > 0 && stats.maps > 0; + const newest = stats.newest.filter( + (map) => selected == null || map.tier === selected, + ); + const playedThisWeek = stats.played_this_week.filter( + (map) => selected == null || map.tier === selected, + ); + if (!hasTiers && newest.length === 0 && playedThisWeek.length === 0) return null; - // The chart keeps the width it needs; the lists share what is left equally, each with a full-height divider. + const weeklyScoped = + selected == null || + stats.tier === selected || + stats.played_this_week.length < 5 || + playedThisWeek.length === 5; + const hasWeekly = stats.maps > 0; return ( - +
    {hasTiers && ( - +
    + +
    )} - {stats.newest.length > 0 && ( +
    ({ + maps={newest.map((map) => ({ name: map.name, tier: map.tier, detail: formatSince(map.listed_at), }))} tierCount={tierCount} /> - )} - {stats.played_this_week.length > 0 && ( - ({ - name: map.name, - tier: map.tier, - detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, - }))} - tierCount={tierCount} - /> - )} - + {hasWeekly && ( + ({ + name: map.name, + tier: map.tier, + detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, + }))} + tierCount={tierCount} + /> + )} +
    +
    ); } /** One of the map stats' lists: a heading, linked to the matching sort if there is one, then a few maps with a detail each. */ function MapStatsList({ title, + empty, href, maps, tierCount, }: { title: string; + empty?: string; href?: string; maps: { name: string; tier?: number | null; detail: string }[]; tierCount: number | null | undefined; }) { return ( -
    -

    +
    +

    {href ? ( - + {title} ) : ( title )}

    -
      - {maps.map((map) => ( -
    • - - {map.tier != null && tierCount != null && ( - - )} - - {map.name} - - {map.detail} - -
    • - ))} -
    + {maps.length === 0 ? ( +

    {empty}

    + ) : ( +
      + {maps.map((map) => ( +
    • + + {map.tier != null && tierCount != null ? ( + + ) : ( + + )} + + {map.name} + + + {map.detail} + + +
    • + ))} +
    + )}
    ); } @@ -484,11 +542,7 @@ function FilterPlayer({ href={`/players/${player.steamid64}`} className="hover:text-accent flex items-center gap-2" > - + {player.name} ) : ( @@ -504,49 +558,3 @@ function FilterPlayer({ ); } - -function MapRow({ - map, - tierCount, -}: { - map: Schemas["MapSummary"]; - tierCount: number | null | undefined; -}) { - const wr = map.world_record; - return ( - - - - - {map.tier != null && tierCount != null && ( - - )} - {map.name} - - - {map.players === 1 ? "1 player" : `${map.players} players`} - {map.bonuses > 0 && - ` · ${map.bonuses === 1 ? "1 bonus" : `${map.bonuses} bonuses`}`} - - - {wr ? ( - - - {formatTime(wr.time)} - - - {wr.player.name} - - - - ) : ( - - No record in this style - - )} - - ); -} diff --git a/web/src/features/maps/MapOverview.module.css b/web/src/features/maps/MapOverview.module.css new file mode 100644 index 0000000..cf3e0b2 --- /dev/null +++ b/web/src/features/maps/MapOverview.module.css @@ -0,0 +1,160 @@ +/* A centered overview sits above the separate map controls; summary rows keep their details close. */ +.overview { + display: grid; + gap: calc(var(--spacing) * 4); + min-inline-size: 0; + max-inline-size: 80rem; + margin-inline: auto; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: calc(var(--spacing) * 3); + min-inline-size: 0; +} + +.search { + order: -1; + min-inline-size: 0; +} + +.search input { + border-color: var(--color-border-strong); + background-color: var(--color-bg); +} + +.search input:focus { + border-color: var(--color-accent); +} + +.summaries { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 4); + border-block-start: 1px solid var(--color-border); + padding-block-start: calc(var(--spacing) * 4); + min-inline-size: 0; +} + +.summary { + display: flex; + flex-direction: column; + gap: calc(var(--spacing) * 2); + min-inline-size: 0; +} + +.list { + display: grid; + gap: calc(var(--spacing) * 2); +} + +.link { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: start; + gap: 0 calc(var(--spacing) * 1.5); + min-block-size: calc(var(--spacing) * 10); +} + +.detail { + grid-column: 2; + grid-row: 2; + align-self: center; +} + +.link > :first-child { + grid-column: 1; + grid-row: 2; +} + +.link > :nth-child(2) { + grid-column: 1 / -1; + grid-row: 1; +} + +@media (min-width: 80rem) { + .overview { + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: calc(var(--spacing) * 6); + } + + .summaries { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 6); + border-block-start: 0; + border-inline-start: 1px solid var(--color-border); + padding-block-start: 0; + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary { + gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 44); + } + + .summary + .summary { + border-inline-start: 1px solid var(--color-border); + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary h2 { + display: flex; + align-items: center; + min-block-size: calc(var(--spacing) * 8); + } + + .list { + grid-template-columns: auto auto auto; + justify-content: start; + gap: var(--spacing) calc(var(--spacing) * 2); + } + + .list > li, + .link { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + } + + .link { + align-items: center; + column-gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 6); + } + + .link > :first-child, + .link > :nth-child(2), + .detail { + grid-row: 1; + } + + .link > :nth-child(2) { + grid-column: 2; + } + + .detail { + grid-column: 3; + text-align: end; + font-size: var(--text-sm); + line-height: var(--text-sm--line-height); + } +} + +@media (min-width: 48rem) { + .search { + order: 0; + inline-size: 20rem; + flex: none; + margin-inline-start: auto; + } +} + +.summaries:only-child { + grid-column: 1 / -1; + border: 0; + padding: 0; +} diff --git a/web/src/features/maps/MapZoneView.tsx b/web/src/features/maps/MapZoneView.tsx index edb49d1..e773331 100644 --- a/web/src/features/maps/MapZoneView.tsx +++ b/web/src/features/maps/MapZoneView.tsx @@ -1,8 +1,9 @@ "use client"; -// A map's zones from above, and on asking, in 3D. The plan is drawn from the zones alone; the map itself -// downloads only once someone asks for the 3D view. -import { Box } from "lucide-react"; -import { useState } from "react"; +// A map's zones in 3D, shown on asking, as a run's replay is: until then a poster of the map with a button, so +// nothing heavy loads with the page. Hiding it, or leaving the page, unloads the view. A map without a file for +// the 3D view yet shows its zones from above instead. +import { Box, X } from "lucide-react"; +import { useEffect, useState } from "react"; import type { Schemas } from "@/api/client"; import { ZoneEditor } from "@/features/staff/maps/ZoneEditor"; import { ZonePlan } from "@/features/staff/maps/ZonePlan"; @@ -13,16 +14,63 @@ export function MapZoneView({ zones, viewerFile, tracks, + cover, }: { map: string; zones: Schemas["Zone"][]; - /** Null when the map has no file for the 3D view yet; the plan still shows. */ + /** Null when the map has no file for the 3D view yet; the plan shows instead. */ viewerFile: Schemas["ViewerFile"] | null; tracks: number[]; + /** The map's cover picture, for the poster. */ + cover: Schemas["MapImage"] | undefined; }) { - const [in3d, setIn3d] = useState(false); - if (in3d && viewerFile) { + const [shown, setShown] = useState(false); + // Next keeps a page left behind alive but hidden, and tears down its effects; back on it, the poster shows + // again rather than the 3D view, as the replay player does. + useEffect(() => () => setShown(false), []); + + if (!viewerFile) { + return ( + <> +

    + No 3D view yet: staff haven't uploaded this map's file. +

    + + + ); + } + + if (!shown) { return ( +
    + {cover && ( + // The map's picture, dimmed, so the space reads as this map until the view loads. Decorative only. + // eslint-disable-next-line @next/next/no-img-element + + )} + +
    + ); + } + + return ( + <> + - ); - } - return ( - <> - - {viewerFile && ( - - )} ); } diff --git a/web/src/features/maps/MapZones.tsx b/web/src/features/maps/MapZones.tsx index e6edc1b..2c088a5 100644 --- a/web/src/features/maps/MapZones.tsx +++ b/web/src/features/maps/MapZones.tsx @@ -37,6 +37,7 @@ export async function MapZones({ name }: { name: string }) { zones={zones.data} viewerFile={map.viewer_file ?? null} tracks={map.tracks.map((track) => track.track)} + cover={map.images[0]} /> )} diff --git a/web/src/features/maps/mapPodiums.test.ts b/web/src/features/maps/mapPodiums.test.ts new file mode 100644 index 0000000..8f8e65c --- /dev/null +++ b/web/src/features/maps/mapPodiums.test.ts @@ -0,0 +1,82 @@ +// PBs use the selected style and viewer, and a failed lookup must not look like an uncompleted map. +import { beforeEach, expect, it, vi } from "vitest"; +import type { Schemas } from "../../api/client"; +import { mapPodiums } from "./mapPodiums"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("next/cache", () => ({ cacheLife: vi.fn() })); +vi.mock("@/api/client", () => ({ api: { GET: get } })); + +const entry = { + rank: 5, + player: { name: "Runner", steamid64: "76561198000000001" }, + time: 12, + run_id: 73, +}; +const record = { + ...entry, + rank: 1, + time: 10, + run_id: 70, + player: { name: "Leader", steamid64: "76561198000000003" }, +}; +const map: Schemas["MapSummary"] = { + name: "bhop_test", + players: 10, + bonuses: 0, + last_run_at: "2026-11-09T00:00:00Z", + world_record: { ...record, finished_at: "2026-11-09T00:00:00Z" }, +}; + +beforeEach(() => { + get.mockReset(); +}); + +it("loads the viewer's PB in the same style-scoped request as the podium", async () => { + get.mockResolvedValue({ data: { entries: [record], player_entry: entry } }); + const result = await mapPodiums([map], "scroll", entry.player.steamid64); + expect(get).toHaveBeenCalledOnce(); + expect(get.mock.calls[0]![1].params.query).toEqual({ + style: "scroll", + track: 0, + limit: 3, + player: entry.player.steamid64, + }); + expect(result.get(map.name)?.personalBest).toEqual(entry); + expect(result.get(map.name)?.entries).toEqual([record]); +}); + +it("scopes each viewer independently and omits PBs for signed-out visitors", async () => { + get.mockImplementation(async (_path, options) => ({ + data: { + entries: [record], + player_entry: + options.params.query.player === entry.player.steamid64 ? entry : null, + }, + })); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name) + ?.personalBest, + ).toEqual(entry); + expect( + (await mapPodiums([map], "normal", "76561198000000002")).get(map.name) + ?.personalBest, + ).toBeNull(); + expect( + (await mapPodiums([map], "normal")).get(map.name)?.personalBest, + ).toBeUndefined(); +}); + +it("distinguishes an empty style from a failed request", async () => { + const empty = await mapPodiums( + [{ ...map, world_record: null }], + "normal", + entry.player.steamid64, + ); + expect(empty.get(map.name)?.personalBest).toBeNull(); + expect(get).not.toHaveBeenCalled(); + get.mockRejectedValue(new Error("unreachable")); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name), + ).toBeNull(); +}); diff --git a/web/src/features/maps/mapPodiums.ts b/web/src/features/maps/mapPodiums.ts new file mode 100644 index 0000000..7a12672 --- /dev/null +++ b/web/src/features/maps/mapPodiums.ts @@ -0,0 +1,73 @@ +// Map-card podiums and the viewer's public PB, cached per style and player in bounded batches. +import { cacheLife } from "next/cache"; +import { api, type Schemas } from "@/api/client"; + +export type MapLeader = Pick< + Schemas["LeaderboardEntry"], + "rank" | "player" | "time" | "run_id" +>; + +export interface MapPodium { + entries: readonly MapLeader[]; + personalBest?: MapLeader | null; +} + +export async function mapPodiums( + maps: Schemas["MapSummary"][], + style: string | null | undefined, + player?: string, +): Promise> { + const podiums = new Map(); + if (!style) return podiums; + // Avoid issuing a page's worth of independent requests to the beta API at once. + for (let offset = 0; offset < maps.length; offset += 6) { + const batch = await Promise.all( + maps.slice(offset, offset + 6).map(async (map) => { + if (!map.world_record) + return [ + map.name, + { entries: [], personalBest: player ? null : undefined }, + ] as const; + const leaders = await cachedPodium({ + map: map.name, + style, + record: map.world_record.run_id, + player, + }).catch(() => null); + return [map.name, leaders] as const; + }), + ); + for (const [map, leaders] of batch) podiums.set(map, leaders); + if (batch.every(([, leaders]) => leaders === null)) break; + } + return podiums; +} + +async function cachedPodium(key: { + map: string; + style: string; + // A new WR changes the key, so cached cards cannot contradict the map list's winner. + record: number; + // PBs are public, but each viewer must have a separate cache entry. + player?: string; +}): Promise { + "use cache"; + cacheLife({ stale: 30, revalidate: 30, expire: 300 }); + const { data, response } = await api.GET("/v1/maps/{map}/leaderboard", { + params: { + path: { map: key.map }, + query: { style: key.style, track: 0, limit: 3, player: key.player }, + }, + signal: AbortSignal.timeout(5000), + }); + if (!data) throw new Error(`Map podium answered ${response.status}`); + return { + entries: data.entries.map(({ rank, player, time, run_id }) => ({ + rank, + player, + time, + run_id, + })), + personalBest: key.player ? (data.player_entry ?? null) : undefined, + }; +} diff --git a/web/src/features/maps/mapPreview.test.ts b/web/src/features/maps/mapPreview.test.ts new file mode 100644 index 0000000..4ddff57 --- /dev/null +++ b/web/src/features/maps/mapPreview.test.ts @@ -0,0 +1,76 @@ +// The text of a map page's link preview. +import { describe, expect, it } from "vitest"; +import type { Schemas } from "@/api/client"; +import { mapDescription } from "./mapPreview"; + +const names: Record = { normal: "Normal", sw: "Sideways" }; +const styleName = (key: string) => names[key] ?? key; +const gabe = { + steamid64: "76561197960287930", + name: "gabe", + avatar_url: null, + country_code: null, +}; + +function board(style: string, time: number) { + return { + style, + players: 1, + runs: 1, + world_record: { player: gabe, time, run_id: 1, finished_at: "" }, + leaderboard: [], + next_cursor: null, + wr_history: [], + }; +} + +function map(overrides: Partial): Schemas["MapDetail"] { + return { + name: "bhop_badges", + images: [], + players: 44, + runs: 90, + tier_count: null, + tracks: [], + legacy_players: 0, + legacy_runs: 0, + all_players: 0, + legacy_record_history: [], + ...overrides, + } as Schemas["MapDetail"]; +} + +describe("mapDescription", () => { + it("names the tier, the opening board's record and the players", () => { + const tracks = [ + { track: 0, tier: 5, styles: [board("sw", 80), board("normal", 64.211)] }, + { track: 1, tier: null, styles: [board("normal", 10)] }, + ]; + expect( + mapDescription( + map({ tracks, tier_count: 10 }), + ["normal", "sw"], + styleName, + ), + ).toBe( + "Tier 5. World record 1:04.211 by gabe in Normal. 44 players, 1 bonus.", + ); + }); + + it("leaves out tiers until a tier count is published", () => { + const tracks = [{ track: 0, tier: 5, styles: [board("normal", 30)] }]; + expect(mapDescription(map({ tracks }), ["normal"], styleName)).toBe( + "World record 30.000 by gabe in Normal. 44 players.", + ); + }); + + it("says when a map has only pre-2.0 records", () => { + expect( + mapDescription( + map({ players: 0, legacy_players: 3 }), + ["normal"], + styleName, + ), + ).toBe("Pre-2.0 records only. 0 players."); + }); +}); diff --git a/web/src/features/maps/mapPreview.ts b/web/src/features/maps/mapPreview.ts new file mode 100644 index 0000000..271a6f5 --- /dev/null +++ b/web/src/features/maps/mapPreview.ts @@ -0,0 +1,54 @@ +// A map page's link preview: its tier, the world record of the board the page opens on, and how many play it. +import type { Metadata } from "next"; +import type { Schemas } from "@/api/client"; +// Relative imports, as the unit tests resolve no `@/` paths. +import { formatTime } from "../runs/time"; +import { count, linkPreview } from "../site/linkPreview"; + +/** The cover's full size, as the API stores it (`docs/site-api.md`). */ +const COVER = { width: 1920, height: 1080 }; + +export function mapPreview( + map: Schemas["MapDetail"], + styleOrder: string[], + styleName: (key: string) => string, +): Metadata { + const cover = map.images[0]; + return linkPreview({ + title: map.name, + description: mapDescription(map, styleOrder, styleName), + picture: cover && { url: cover.url, ...COVER, wide: true }, + }); +} + +/** Plain facts, in the order a player looks for them: how hard, the time to beat, how busy. */ +export function mapDescription( + map: Schemas["MapDetail"], + styleOrder: string[], + styleName: (key: string) => string, +): string { + const main = map.tracks.find((track) => track.track === 0); + // The board the page opens on: the first ranked style with runs on the main track. + const board = styleOrder + .map((key) => main?.styles.find((style) => style.style === key)) + .find((style) => style !== undefined); + const bonuses = map.tracks.filter((track) => track.track > 0).length; + + const parts: string[] = []; + if (main?.tier != null && map.tier_count != null) { + parts.push(`Tier ${main.tier}`); + } + if (board) { + const record = board.world_record; + parts.push( + `World record ${formatTime(record.time)} by ${record.player.name} in ${styleName(board.style)}`, + ); + } else if (map.legacy_players > 0) { + parts.push("Pre-2.0 records only"); + } + const players = count(map.players, "player", "players"); + parts.push( + bonuses > 0 ? `${players}, ${count(bonuses, "bonus", "bonuses")}` : players, + ); + return `${parts.join(". ")}.`; +} diff --git a/web/src/features/players/PlayerDetails.tsx b/web/src/features/players/PlayerDetails.tsx index 3a85416..21adaef 100644 --- a/web/src/features/players/PlayerDetails.tsx +++ b/web/src/features/players/PlayerDetails.tsx @@ -1,5 +1,5 @@ // The top of a player's profile: their setup as they describe it (mouse, DPI, sensitivity and so on), with a -// way to change it for the player themself and for staff who manage bans. A line sets it apart from runs. +// way to change it for the player themself and for staff who manage bans. import { api, type Schemas } from "@/api/client"; import type { signedInPlayer } from "@/features/auth/signedInPlayer"; import { detailFields } from "./detailFields"; @@ -20,16 +20,20 @@ export async function PlayerDetails({ const countries = own || staff ? await countryOptions() : []; return ( -
    +
    {shown.length > 0 ? ( -
    + // One row of specs on wider screens, ruled apart like a spec sheet; a three-column grid on a phone. +
    {shown.map(({ key, label }) => ( -
    -
    +
    +
    {label}
    -
    +
    {String(details?.[key])}
    @@ -56,7 +60,6 @@ export async function PlayerDetails({ From the old site{own ? ", until you save your own" : ""}.

    )} -
    ); } diff --git a/web/src/features/players/PlayerFinder.tsx b/web/src/features/players/PlayerFinder.tsx new file mode 100644 index 0000000..edd0edc --- /dev/null +++ b/web/src/features/players/PlayerFinder.tsx @@ -0,0 +1,215 @@ +"use client"; +// The Players page's search, answering as you type: the field beside the title, and in the panel under it the +// players matching what's typed, or with nothing typed, what the server sent (recently active players, or for +// staff the banned ones). Searches run in the browser the way the header's does: a short pause, each keystroke +// cancelling the request still out, late replies dropped, results kept up until the next arrive, and answers +// cached. The address follows, so a search can be shared; without script the form still submits. +import { Search, X } from "lucide-react"; +import Form from "next/form"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { api, type Schemas } from "@/api/client"; +import { ButtonLink } from "@/ui/Button"; +import { PlayerRows, SEARCH_LIMIT } from "./PlayerRows"; +import { STEAMID } from "./steamId"; + +const PAUSE_MS = 150; + +type Players = Schemas["PlayerSummary"][]; + +export function PlayerFinder({ + heading, + initialQuery, + initialPlayers, + initialNow, + defaultTitle, + defaultAside, + children, + canManage, +}: { + /** The page's title and count, on the field's line. */ + heading: ReactNode; + initialQuery: string; + /** The server's answer for `initialQuery`; undefined when it couldn't be loaded. */ + initialPlayers: Players | undefined; + /** When the server asked, for the rows' "ago": time is read where data arrives, never while rendering. */ + initialNow: string; + /** The panel's title with nothing typed: "Recently active" or "Banned". */ + defaultTitle: ReactNode; + /** Beside it: what the times mean, or staff's tabs. */ + defaultAside: ReactNode; + /** The panel's body with nothing typed, rendered on the server. */ + children: ReactNode; + /** Staff who act on players, offered a SteamID nobody has seen. */ + canManage: boolean; +}) { + const [text, setText] = useState(initialQuery); + const [query, setQuery] = useState(initialQuery.trim()); + const [results, setResults] = useState<{ + query: string; + players: Players | undefined; + at: Date; + }>({ + query: initialQuery.trim(), + players: initialPlayers, + at: new Date(initialNow), + }); + const timer = useRef(undefined); + const controller = useRef(null); + const sequence = useRef(0); + const kept = useRef( + new Map( + initialPlayers + ? [[initialQuery.trim().toLowerCase(), initialPlayers]] + : [], + ), + ); + + useEffect( + () => () => { + window.clearTimeout(timer.current); + controller.current?.abort(); + }, + [], + ); + + function search(value: string) { + const next = value.trim(); + setQuery(next); + window.clearTimeout(timer.current); + controller.current?.abort(); + const seq = ++sequence.current; + // The address follows the field, replaced rather than pushed: one entry in the history per visit. + const url = new URL(window.location.href); + if (next) url.searchParams.set("q", next); + else url.searchParams.delete("q"); + window.history.replaceState(null, "", url); + if (!next) return; + const known = kept.current.get(next.toLowerCase()); + if (known) { + setResults({ query: next, players: known, at: new Date() }); + return; + } + timer.current = window.setTimeout(async () => { + const abort = new AbortController(); + controller.current = abort; + try { + const result = await api.GET("/v1/players", { + params: { query: { q: next, limit: SEARCH_LIMIT } }, + signal: abort.signal, + }); + if (seq !== sequence.current) return; + const players = result.data?.players; + if (players) kept.current.set(next.toLowerCase(), players); + setResults({ query: next, players, at: new Date() }); + } catch (error) { + if ((error as Error).name === "AbortError") return; + if (seq === sequence.current) + setResults({ query: next, players: undefined, at: new Date() }); + } + }, PAUSE_MS); + } + + const searching = query !== ""; + // What's shown stays until the answer for the current text arrives, so typing never blanks the panel. + const shown = results.players; + const pending = searching && results.query !== query; + + return ( + <> +
    + {heading} +
    event.preventDefault()} + > +
    + + { + setText(event.target.value); + search(event.target.value); + }} + className="border-border bg-surface text-text placeholder:text-text-subtle hover:border-border-strong focus:border-accent focus:bg-bg h-10 w-full rounded-md border pr-10 pl-10 transition-colors duration-(--duration-fast) outline-none" + /> + {text && ( + + )} +
    +
    +
    + +
    +
    +

    + {!searching + ? defaultTitle + : shown && shown.length > 0 + ? shown.length === SEARCH_LIMIT + ? `First ${SEARCH_LIMIT} players matching “${results.query}”` + : `${shown.length === 1 ? "1 player matches" : `${shown.length} players match`} “${results.query}”` + : `Players matching “${query}”`} +

    + {!searching ? ( + defaultAside + ) : ( +

    + {shown?.length === SEARCH_LIMIT + ? "There may be more: add more of the name, or a SteamID." + : "Latest finished run"} +

    + )} +
    + {!searching ? ( + children + ) : !shown ? ( +

    + {pending + ? "Searching…" + : "That search didn't work. Try again in a moment."} +

    + ) : shown.length === 0 ? ( +
    + {pending ? "Searching…" : "No player has that name or SteamID."} + {!pending && canManage && STEAMID.test(query) && ( + + Manage {query} anyway + + )} +
    + ) : ( + + )} +
    + + ); +} diff --git a/web/src/features/players/PlayerHeader.tsx b/web/src/features/players/PlayerHeader.tsx index c2e6a54..e365aea 100644 --- a/web/src/features/players/PlayerHeader.tsx +++ b/web/src/features/players/PlayerHeader.tsx @@ -1,15 +1,29 @@ -// The top of a player's pages: avatar, name, flag and Steam profile link, with the Profile / Manage switch for -// staff. It sits in the player's layout, so switching to the Manage view keeps it in place. +// The top of a player's pages, a masthead across the page: avatar, name, flag, country, first and latest run +// and Steam profile link, their rank in the style shown below, and the Profile / Manage switch for staff. +// Behind it, the map of their latest world record (or latest run), captioned as such. It sits in the player's +// layout, so switching to the Manage view keeps it. import { ExternalLink } from "lucide-react"; import { notFound } from "next/navigation"; -import type { Schemas } from "@/api/client"; +import { api, type Schemas } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { getStaffPlayer } from "@/features/staff/players/staffPlayer"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; import { Flag } from "@/ui/Flag"; import { PathTabs } from "@/ui/PathTabs"; +import { + formatDate, + formatSince, + formatTime, + trackName, +} from "@/features/runs/time"; +import { classNames } from "@/ui/classNames"; +import { Link } from "@/ui/Link"; +import { Masthead, type MastheadImage } from "@/ui/Masthead"; +import { currentStyles } from "@/features/ruleset/styles"; import { getPlayer } from "./playerDetail"; +import { ProfileRank } from "./ProfileRank"; +import { avatarSrc } from "@/features/players/avatarSrc"; export async function PlayerHeader({ steamid }: { steamid: string }) { const [result, me] = await Promise.all([ @@ -31,52 +45,200 @@ export async function PlayerHeader({ steamid }: { steamid: string }) { const isOwn = me?.steamid64 === player.steamid64; const banned = staffView?.bans?.some((ban) => ban.active) ?? false; - return ( -
    - ( + [key, styles.name(key)]), + )} + draft={profile.points_draft} + inline={inline} /> -
    -
    -

    {player.name}

    - + <> +
    + - {banned && Banned} -
    - - Steam profile - - -
    - {/* A player SourceJump hasn't seen has no profile to switch to. */} - {manager && profile && ( - - )} -
    +
    + {/* One line of text, so the flag sits at the middle of the name's letters (`vertical-align: middle`) + rather than the middle of its line box, which reads as high beside a lowercase name. */} +
    +

    {player.name}

    + + {banned && ( + + Banned + + )} +
    + {rank &&
    {rank(true)}
    } + {/* Facts about the player, then the way out to Steam. The run dates count 2.0 runs alone. */} +
    +
    + {country && ( +
    +
    Country
    +
    {country}
    +
    + )} + {firstRun && ( +
    +
    First 2.0 run
    +
    + +
    +
    + )} + {lastRun && ( +
    +
    Latest run
    +
    + +
    +
    + )} +
    + + Steam profile + + +
    +
    + {/* A player SourceJump hasn't seen has no profile to switch to. */} + {manager && profile && ( + + )} + {/* Their rank, the main thing a profile tells, for the style the profile below shows: large at the row's + end; on a phone, the line under the name. */} + {rank && ( +
    {rank()}
    + )} +

    + {/* What the picture is, on the picture: which run of theirs it's the map of. Outside the header, whose + entrance transform would make it the box this is placed in. */} + {image && featured && ( +
    + {/* The same frosted plate as a server row's labels on its map picture: the picture shows through, softened. */} +

    + {featured.label} + · + 0 ? `&track=${featured.pb.track}` : ""}`} + className="text-text hover:text-accent truncate font-bold" + > + {featured.pb.map} + + + {[ + featured.pb.track > 0 && trackName(featured.pb.track), + styles.name(featured.pb.style), + formatTime(featured.pb.time), + ] + .filter(Boolean) + .join(" · ")} + +

    +
    + )} + + ); } +/** + * The run whose map stands behind the header: their latest world record, or with none, their latest run. Asked of + * the API rather than picked from the profile, whose personal bests are only each style's first page. + */ +async function featuredRun( + profile: Schemas["PlayerProfile"], +): Promise<{ pb: Schemas["PersonalBest"]; label: string } | undefined> { + const records = profile.all_styles.world_records > 0; + const result = await api + .GET("/v1/players/{player}/personal-bests", { + params: { + path: { player: profile.steamid64 }, + // Without a style: every style, most recently finished first. + query: { records: records || undefined, limit: 1 }, + }, + }) + .catch(() => undefined); + const pb = result?.data?.personal_bests[0]; + if (!pb) return undefined; + return { + pb, + label: records ? "Latest world record" : "Latest personal best", + }; +} + +/** A map's cover picture; none when it has no pictures or can't be loaded, and the header goes without. */ +async function mapCover(map: string): Promise { + const result = await api + .GET("/v1/maps/{map}", { params: { path: { map } } }) + .catch(() => undefined); + const cover = result?.data?.images[0]; + return cover + ? { url: cover.url, thumbnailUrl: cover.thumbnail_url, focus: cover.focus } + : undefined; +} + +const countryNames = new Intl.DisplayNames(["en"], { type: "region" }); + /** Who sees the Manage view: staff who can act on players. The API checks each privilege again. */ export function managesPlayers( privileges: readonly Schemas["Privilege"][] | undefined, diff --git a/web/src/features/players/PlayerRows.tsx b/web/src/features/players/PlayerRows.tsx new file mode 100644 index 0000000..fcd6683 --- /dev/null +++ b/web/src/features/players/PlayerRows.tsx @@ -0,0 +1,89 @@ +// A list of players as the Players page shows them: two columns on wider screens, reading down each, a line +// between rows and between the columns. Each row is the player, their flag if they have one, and how long ago +// they last finished a run, in the accent within the hour. Rendered on the server for the first view and in +// the browser for searches as they're typed, so it holds no state of its own. +import type { CSSProperties } from "react"; +import type { Schemas } from "@/api/client"; +import { formatDate, formatSince } from "@/features/runs/time"; +import { Avatar } from "@/ui/Avatar"; +import { classNames } from "@/ui/classNames"; +import { Flag } from "@/ui/Flag"; +import { Link } from "@/ui/Link"; +import { avatarSrc } from "@/features/players/avatarSrc"; + +/** + * Players asked for per search, so a full answer can say there may be more. Here, in a module both sides import, + * as a client module's exports reach server code only as references. + */ +export const SEARCH_LIMIT = 20; + +export function PlayerRows({ + players, + now, + animate = true, +}: { + players: Schemas["PlayerSummary"][]; + /** One moment for every row's "ago". */ + now: Date; + /** Off for results that change as someone types: they should land at once, not fade in. */ + animate?: boolean; +}) { + const half = Math.ceil(players.length / 2); + return ( +
      + {players.map((player, index) => ( +
    • + + + {/* Most players have no country on Steam; a column of placeholders would only be noise. */} + + + {player.name} + + {player.country_code && } + + + {player.last_run_at ? ( + + ) : ( + // Search finds players with no 2.0 runs too. + No 2.0 runs + )} + + +
    • + ))} +
    + ); +} diff --git a/web/src/features/players/PlayerSearch.tsx b/web/src/features/players/PlayerSearch.tsx index 7126c01..61e9ab6 100644 --- a/web/src/features/players/PlayerSearch.tsx +++ b/web/src/features/players/PlayerSearch.tsx @@ -1,75 +1,56 @@ -// The Players page's search and results: players matching a name or SteamID, or recently active players. Staff -// who hold manage_bans also get a Banned tab, and staff who act on players can open a SteamID nobody has seen. -import { Search } from "lucide-react"; -import Form from "next/form"; -import type { CSSProperties } from "react"; +// The Players page's board: the search beside the title, and under it recently active players, or for staff who +// hold manage_bans a Banned tab. Loads what the first view shows; PlayerFinder answers searches as they're typed. +import type { ReactNode } from "react"; import { api } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; -import { formatDate } from "@/features/runs/time"; -import { Avatar } from "@/ui/Avatar"; import { BannedPlayers } from "@/features/staff/players/BannedPlayers"; -import { Button, ButtonLink } from "@/ui/Button"; -import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Input } from "@/ui/Input"; -import { Link } from "@/ui/Link"; import { LinkTabs } from "@/ui/LinkTabs"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeaderCell, - TableRow, -} from "@/ui/Table"; import { managesPlayers } from "./PlayerHeader"; -import { STEAMID } from "./steamId"; +import { PlayerFinder } from "./PlayerFinder"; +import { PlayerRows, SEARCH_LIMIT } from "./PlayerRows"; -export async function PlayerSearch({ - q, +export async function PlayersBoard({ + q: search, banned, + heading, }: { + /** The search in the address, trimmed; empty for recently active players. */ q: string; /** The Banned tab, for staff who hold manage_bans. */ banned: boolean; + heading: ReactNode; }) { - const search = q.trim(); - const [result, me] = await Promise.all([ + const recentPlayers = () => api - .GET("/v1/players", { params: { query: search ? { q: search } : {} } }) - .catch(() => undefined), + .GET("/v1/players", { params: { query: { limit: SEARCH_LIMIT } } }) + .then((result) => result.data?.players) + .catch(() => undefined); + const [recent, found, me] = await Promise.all([ + recentPlayers(), + search + ? api + .GET("/v1/players", { + params: { query: { q: search, limit: SEARCH_LIMIT } }, + }) + .then((result) => result.data?.players) + .catch(() => undefined) + : undefined, signedInPlayer(), ]); const seesBans = me?.privileges.includes("manage_bans") ?? false; - const showBans = banned && seesBans && !search; + const showBans = banned && seesBans; + const now = new Date(); return ( -
    - {/* The search and what the list below shows share one line, the tabs at its end. */} -
    - {/* Prefetching stays off here too, as for links (docs/design-system.md). */} -
    - - -
    - - {search ? ( -

    - Players matching “{search}” -

    - ) : seesBans ? ( + ) : ( -

    Recently active

    - )} -
    +

    Latest finished run

    + ) + } + > {showBans ? ( - - ) : !result ? ( -

    Players couldn't be loaded. Try again in a moment.

    - ) : !result.data ? ( -

    - {result.error?.error ?? "That search didn't work."} +

    + +
    + ) : !recent ? ( +

    + Players couldn't be loaded. Try again in a moment. +

    + ) : recent.length === 0 ? ( +

    + Nobody has finished a run in the last 30 days.

    - ) : result.data.players.length === 0 ? ( - - {search - ? "No player has that name or SteamID." - : "Nobody has finished a run in the last 30 days."} - {STEAMID.test(search) && managesPlayers(me?.privileges) && ( - - Manage {search} anyway - - )} - ) : ( - // Keyed by the search, so every row fades in on a new search, as on the Maps page. - - - - Player - Latest run - - - - {result.data.players.map((player, index) => ( - // The name link stretches over the whole row, so the row is one click target and still a - // plain link (middle-click, keyboard) rather than a row with a click handler. - - - - - {player.name} - - - - - {player.last_run_at ? ( - - ) : ( - "None yet" - )} - - - ))} - -
    + )} -
    + ); } diff --git a/web/src/features/players/PlayerStyles.tsx b/web/src/features/players/PlayerStyles.tsx index 3e97965..3e6bb03 100644 --- a/web/src/features/players/PlayerStyles.tsx +++ b/web/src/features/players/PlayerStyles.tsx @@ -7,6 +7,7 @@ import { useSearchParams } from "next/navigation"; import { type CSSProperties, type ReactNode, useEffect, useState } from "react"; import { api, type Schemas } from "@/api/client"; import { LegacyBadge } from "@/features/legacy/LegacyBadge"; +import { ReplayLink } from "@/features/replays/ReplayLink"; import { LEGACY_STYLE, type View, @@ -14,14 +15,29 @@ import { viewFrom, } from "@/features/legacy/views"; import { RunLink } from "@/features/runs/RunLink"; -import { formatDate, formatTime } from "@/features/runs/time"; +import { + formatAge, + formatDate, + formatGap, + formatTime, +} from "@/features/runs/time"; import { Badge } from "@/ui/Badge"; import { Button } from "@/ui/Button"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; +import { classNames } from "@/ui/classNames"; +import { CountUp } from "@/ui/CountUp"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; -import { StatCard } from "@/ui/StatCard"; +import { SortButton } from "@/ui/SortButton"; +import { TierBadge } from "@/ui/TierBadge"; +import { + gapOf, + type PbSort, + type PbSortKey, + sameSort, + sortedPbs, +} from "./personalBestOrder"; import { Table, TableBody, @@ -33,6 +49,7 @@ import { const PAGE_SIZE = 50; const numbers = new Intl.NumberFormat("en"); +const percent = new Intl.NumberFormat("en", { style: "percent" }); /** The Style and Track menus' choice of every style or every track. */ const ANY = "any"; @@ -79,8 +96,6 @@ export function PlayerStyles({ const view: View = withViews ? viewFrom(params.get("view"), current ? "current" : "legacy") : "current"; - const standing = - tracks === "bonuses" ? current?.bonus_standing : current?.main_standing; const bonuses = counts?.completed_bonuses ?? 0; const maps = counts?.completed_maps ?? 0; const shownTotal = @@ -111,141 +126,169 @@ export function PlayerStyles({ return ( <> - - ({ - value: key, - label: styleNames[key] ?? key, - quiet: !hasTimes(key), - startsGroup: index === 0, - })), - ]} - value={styleKey} - onChange={(style) => choose({ style })} - /> - - choose({ - tracks: value === "bonuses" || value === ANY ? value : "main", - }) - } - /> - choose({ records: value === "records" })} - /> - choose({ view: next })} - /> - - -
    - {/* Each card opens what its number comes from. The rank is the style's points leaderboard place, on - main tracks unless bonuses are shown; styles count apart, so any style has none. */} + {/* The style's progress, split into what each number opens: completed maps and world records, compact like the + home page's numbers. The rank leads the header above. */} +
    - - - - 0 ? ` · ${bonuses} ${bonuses === 1 ? "bonus" : "bonuses"}` : ""}`} - /> + + + + {" "} + / {numbers.format(player.map_count)} + + + + completed maps + {bonuses > 0 && ( + + {` · ${bonuses} ${bonuses === 1 ? "bonus" : "bonuses"}`} + + )} + + {player.map_count > 0 && ( + + {percent.format(maps / player.map_count)} + + )} + {/* How far through the map list they are, along the cell's foot; the numbers say it for screen readers. */} + + + - {/* Every world record, newest first: any style, any track, 2.0 runs. */} + {/* Every world record, newest first: any style, any track, 2.0 runs; pressed again, back to the opening view. A + player without one has nothing to open. */} - choose({ - style: ANY, - tracks: ANY, - records: true, - }) + pressed={records} + onClick={ + counts?.world_records || records + ? () => + records + ? choose({ + style: styleKeys.find(hasTimes) ?? styleKeys[0], + tracks: "main", + records: false, + }) + : choose({ style: ANY, tracks: ANY, records: true }) + : undefined } > - + + + + world records + {counts?.world_records ? ( + + {records ? "Showing all" : "Show all"} + + ) : null}
    - {records && !counts?.world_records ? ( -

    No {styleName}world records yet.

    - ) : view === "current" && !shownTotal ? ( -

    - No {styleName}personal bests - {tracks === "main" - ? " on main tracks" - : tracks === "bonuses" - ? " on bonuses" - : ""}{" "} - yet. -

    - ) : ( - styleNames[key] ?? key} - tracks={tracks === ANY ? undefined : tracks} - view={view} - records={records} - first={ - view === "current" && tracks === "main" && current && !records - ? { - personal_bests: current.personal_bests, - next_cursor: current.next_cursor, - } - : undefined - } - // The world record count covers main tracks and bonuses together, so it can't total one of them. - total={view === "current" && !records ? shownTotal : undefined} - /> - )} + {/* The choices sit with the list they narrow, under the overview. */} +
    + + ({ + value: key, + label: styleNames[key] ?? key, + quiet: !hasTimes(key), + startsGroup: index === 0, + })), + ]} + value={styleKey} + onChange={(style) => choose({ style })} + /> + + choose({ + tracks: value === "bonuses" || value === ANY ? value : "main", + }) + } + /> + Show} + options={[ + { value: "all", label: "All runs" }, + { + value: "records", + label: "World records", + quiet: !counts?.world_records, + }, + ]} + value={records ? "records" : "all"} + onChange={(value) => choose({ records: value === "records" })} + /> + choose({ view: next })} + /> + + {records && !counts?.world_records ? ( +

    No {styleName}world records yet.

    + ) : view === "current" && !shownTotal ? ( +

    + No {styleName}personal bests + {tracks === "main" + ? " on main tracks" + : tracks === "bonuses" + ? " on bonuses" + : ""}{" "} + yet. +

    + ) : ( + styleNames[key] ?? key} + tracks={tracks === ANY ? undefined : tracks} + view={view} + records={records} + first={ + view === "current" && tracks === "main" && current && !records + ? { + personal_bests: current.personal_bests, + next_cursor: current.next_cursor, + } + : undefined + } + tierCount={player.tier_count ?? undefined} + // The world record count covers main tracks and bonuses together, so it can't total one of them; across + // styles the counts are of maps, not of each style's personal best on them. + total={ + view === "current" && !records && !anyStyle + ? shownTotal + : undefined + } + /> + )} +
    ); } @@ -263,30 +306,84 @@ function withQuery( return text ? `${path}?${text}` : path; } -/** A stat card that opens a page or changes the view, entering with the cards beside it. */ +/** + * One cell of the standing panel: opens the page its number comes from, or changes the view. With neither, + * it's a plain cell. + */ function StatLink({ href, onClick, - index, + pressed, + className, children, }: { - index: number; + href?: string; + onClick?: () => void; + /** For a cell that switches a view: whether that view is showing. */ + pressed?: boolean; + className?: string; children: ReactNode; -} & ( - { href: string; onClick?: never } | { href?: never; onClick: () => void } -)) { - // Each card fills its grid cell, so a card whose detail wraps on a phone doesn't leave its neighbor shorter. - const className = - "motion-lift motion-enter flex flex-col rounded-lg text-left *:flex-1"; - const style = { "--motion-delay": `${index * 40}ms` } as CSSProperties; - return href ? ( - +}) { + // Number over its words on narrow screens, side by side from lg, as the home page's numbers. + const classes = classNames( + "group relative flex min-w-0 flex-col px-3 py-2 text-left sm:px-4 sm:py-3 lg:flex-row lg:items-baseline lg:gap-2", + className, + ); + // The panel clips its corners, so the focus ring is drawn inside the cell. + const clickable = classNames( + classes, + "hover:bg-text/4 transition-colors duration-(--duration-fast) focus-visible:-outline-offset-2", + // On, in the accent, as a pressed ghost button shows it. + pressed && "bg-accent-soft hover:bg-accent-soft", + ); + if (href) { + return ( + + {children} + + ); + } + if (onClick) { + return ( + + ); + } + return
    {children}
    ; +} + +/** A standing cell's number: in its own color (a medal, the record accent), or the accent on hover as at home. */ +function StatValue({ + color, + children, +}: { + color?: string; + children: ReactNode; +}) { + return ( + {children} - - ) : ( - + ); } @@ -300,6 +397,7 @@ function PersonalBests({ records, first, total, + tierCount, }: { steamid64: string; /** Left out for every style, listed most recently finished first. */ @@ -314,13 +412,27 @@ function PersonalBests({ first?: Pick; /** How many there are, when known up front (2.0's counts); the other views count what they've shown. */ total?: number; + /** Tiers in force, for the badges; undefined until the community sets tiers. */ + tierCount?: number; }) { - const [personalBests, setPersonalBests] = useState(first?.personal_bests); + // The API's own order: by map in one style, newest first across styles. + const apiOrder: PbSort = style + ? { key: "map", descending: false } + : { key: "date", descending: true }; + // Best place first, what a profile is read for. Pre-2.0 runs have no place, so their views keep the API's order. + const defaultSort: PbSort = + view === "current" ? { key: "place", descending: false } : apiOrder; + const sortsAll = !sameSort(defaultSort, apiOrder); + // A first page that isn't the whole list waits for the rest, so the table doesn't reorder under the reader. + const [personalBests, setPersonalBests] = useState( + sortsAll && first?.next_cursor ? undefined : first?.personal_bests, + ); const [cursor, setCursor] = useState(first?.next_cursor); const [loading, setLoading] = useState(false); const [failed, setFailed] = useState(false); + const [sort, setSort] = useState(defaultSort); - function fetchPage(after: string | undefined) { + function fetchPage(after: string | undefined, limit = PAGE_SIZE) { return api .GET("/v1/players/{player}/personal-bests", { params: { @@ -330,7 +442,7 @@ function PersonalBests({ tracks, view, records: records || undefined, - limit: PAGE_SIZE, + limit, cursor: after, }, }, @@ -361,9 +473,57 @@ function PersonalBests({ show(page, after); } - // Views other than 2.0's don't come with the profile; their first page loads once the view is chosen. + /** + * Any order but the API's needs every row: loads the rest after `shown`, `loading` being set already. False if a + * page failed. + * shortcut: loads every personal best in the browser, 100 a request; fine for the few hundred 2.0 runs a player has + * in a style, ask the API for a `sort` parameter if lists grow to thousands. + */ + async function loadAll( + shown: Schemas["PersonalBest"][], + after: string | null | undefined, + ) { + let all = shown; + while (after) { + const page = await fetchPage(after, FULL_PAGE_SIZE); + if (!page) { + setLoading(false); + setFailed(true); + return false; + } + all = [...all, ...page.personal_bests]; + after = page.next_cursor; + } + setPersonalBests(all); + setCursor(undefined); + setLoading(false); + return true; + } + + /** Sorts by a column; again on the same one turns it around. */ + async function sortBy(key: PbSortKey) { + const next: PbSort = + sort.key === key + ? { key, descending: !sort.descending } + : { key, descending: key === "date" }; + if (!sameSort(next, apiOrder) && cursor) { + setLoading(true); + setFailed(false); + if (!(await loadAll(personalBests ?? [], cursor))) return; + } + setSort(next); + } + + // Views other than 2.0's don't come with the profile; their first page loads once the view is chosen. An order + // the API doesn't give loads the rest straight away. useEffect(() => { - if (!first) void fetchPage(undefined).then((page) => show(page, undefined)); + const start = first ? Promise.resolve(first) : fetchPage(undefined); + void start.then((page) => { + if (sortsAll && page?.next_cursor) { + setLoading(true); + void loadAll(page.personal_bests, page.next_cursor); + } else show(page, undefined); + }); // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another style or view }, []); @@ -372,7 +532,12 @@ function PersonalBests({

    These personal bests couldn't be loaded. Try again.

    - ) : null; + ) : ( + // Held in the table's place, so choosing a view that wasn't loaded with the page doesn't leave a blank. +

    + Loading… +

    + ); } const count = total ?? personalBests.length; // World records count bonuses with main tracks, so one kind of track can have none while the count doesn't. @@ -390,23 +555,83 @@ function PersonalBests({ ); } + const heading = (key: PbSortKey, label: string) => ( + void sortBy(key)} + /> + ); + const ariaSort = (key: PbSortKey) => + sort.key === key + ? sort.descending + ? ("descending" as const) + : ("ascending" as const) + : undefined; + const rows = sameSort(sort, apiOrder) + ? personalBests + : sortedPbs(personalBests, sort, styleName); + return (
    - +
    - Place - Map - {!style && Style} - Time - Date + {/* As on a map's board: Place centered over its medals, the play button close beside the time. On a + phone the style goes under the map and the date becomes an age under the time, so the row fits + without scrolling. */} + + {heading("place", "Place")} + + + {heading("map", "Map")} + + {!style && ( + + {heading("style", "Style")} + + )} + + {heading("time", "Time")} + + + Replay + + + {heading("date", "Date")} + - {personalBests.map((pb, index) => ( + {rows.map((pb, index) => ( - + {/* A legacy run has no 2.0 placement. */} - {pb.rank == null ? ( - - – - - ) : ( - - )} + + {pb.rank == null ? ( + + – + + ) : ( + + )} + - - + + + {pb.tier != null && tierCount != null && ( + + )} 0 ? `&track=${pb.track}` : ""}` } - className="hover:text-accent" + title={pb.map} + className="hover:text-accent truncate" > {pb.map} @@ -441,26 +672,51 @@ function PersonalBests({ {pb.rank === 1 && WR} {pb.legacy && } + {!style && ( + + {styleName(pb.style)} + + )} {!style && ( - + {styleName(pb.style)} )} - - {/* Legacy runs have no run page: the old site kept no more than this row. */} - {pb.legacy ? ( - formatTime(pb.time) - ) : ( - - {formatTime(pb.time)} - - )} + + + + {/* Legacy runs have no run page: the old site kept no more than this row. */} + {pb.legacy ? ( + formatTime(pb.time) + ) : ( + + {formatTime(pb.time)} + + )} + {/* The gap to the board's record, beside the time at every width. */} + + + {pb.finished_at && ( + // Counted from now, which differs between the server's render and the browser's. + + )} + + + + {/* Replays open by 2.0 run ID; a pre-2.0 run's ID is the old site's. */} + {!pb.legacy && } - + {pb.finished_at ? (