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-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-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/crates/api/src/players.rs b/api/crates/api/src/players.rs index fc1f7be..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)) 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/steam_profile.rs b/api/crates/api/src/players/steam_profile.rs index 4079863..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"); @@ -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. @@ -222,12 +310,28 @@ mod tests { /// A stand-in for Steam that answers every profile with `PUBLIC`. async fn fake_steam() -> Steam { - let app = - axum::Router::new().route("/profiles/{id}/", axum::routing::get(|| async { PUBLIC })); + 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() }); - Steam::with_base(&url::Url::parse(&format!("http://{address}/")).unwrap()) + let steam = Steam::with_base(&url::Url::parse(&format!("http://{address}/")).unwrap()); + (steam, requests) } #[sqlx::test] 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 679725f..3097d0a 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -1189,6 +1189,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": [ diff --git a/docs/site-api.md b/docs/site-api.md index 2168dae..e8a8454 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -1,55 +1,56 @@ # Site API -The website's endpoints: sign-in, players, maps, server list, community posts; staff tools: `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 (errors, retries, SteamIDs) 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. +Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirects, cookies) via the site's origin (Caddy, or 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, 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 needs 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 also needs our `Origin` header; 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 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 personal bests 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). Personal bests have a placement (ties share one), `tier` and `world_record_time`; profiles `tier_count`. +- 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 their public Steam profile XML, fetched at sign-in, and when a day old after a run or a view (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, never numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. +- 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, 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, so a map page switches between them locally. `…/leaderboard?cursor=` pages on from there; cursors are opaque. -- WR history: every run faster than all runs finished before it on that board, by `finished_at`. Ties don't count. +- 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 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 CLI's `tiers count` publishes the tier 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`, 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=&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 personal best), `world_record` (as in WR history) and `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). 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, and `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, toggles for listing and whitelist, 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. +- 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`, 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`, 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 as a watch link. -- Pages link to `/community/{id}-{slug}`; only the ID counts, so retitling keeps links. Removal hides a post, keeping 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/src/api/schema.ts b/web/src/api/schema.ts index 3444987..c54cb25 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -353,6 +353,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; @@ -4195,6 +4215,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; diff --git a/web/src/features/activity/RecentRunTable.tsx b/web/src/features/activity/RecentRunTable.tsx index 5d2ffae..c1c72bb 100644 --- a/web/src/features/activity/RecentRunTable.tsx +++ b/web/src/features/activity/RecentRunTable.tsx @@ -32,6 +32,7 @@ import { TableRow, } from "@/ui/Table"; import { TierBadge } from "@/ui/TierBadge"; +import { avatarSrc } from "@/features/players/avatarSrc"; type Run = Schemas["RecentRun"]; type Query = { @@ -378,7 +379,7 @@ export function RecentRunTable({ > {run.player.name} diff --git a/web/src/features/community/PostByline.tsx b/web/src/features/community/PostByline.tsx index 36ca2f3..a8b467b 100644 --- a/web/src/features/community/PostByline.tsx +++ b/web/src/features/community/PostByline.tsx @@ -3,6 +3,7 @@ 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"; export function PostByline({ post }: { post: Schemas["PostSummary"] }) { const edited = post.updated_at.slice(0, 10) !== post.created_at.slice(0, 10); @@ -14,7 +15,7 @@ export function PostByline({ post }: { post: Schemas["PostSummary"] }) { > {post.author.name} diff --git a/web/src/features/home/LiveNow.tsx b/web/src/features/home/LiveNow.tsx index f031dfb..9633fb7 100644 --- a/web/src/features/home/LiveNow.tsx +++ b/web/src/features/home/LiveNow.tsx @@ -22,6 +22,7 @@ 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 = 8; /** @@ -282,7 +283,7 @@ function Records({ {/* Most players have no country on Steam; a placeholder on every row would only be noise. */} @@ -357,7 +358,7 @@ function Leaders({ standings }: { standings: Schemas["Standing"][] }) { diff --git a/web/src/features/leaderboards/StandingsPanel.tsx b/web/src/features/leaderboards/StandingsPanel.tsx index 96842e9..61cda8c 100644 --- a/web/src/features/leaderboards/StandingsPanel.tsx +++ b/web/src/features/leaderboards/StandingsPanel.tsx @@ -9,6 +9,7 @@ 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"]; @@ -177,10 +178,7 @@ function Row({ className="group hover:bg-surface-raised flex h-14 items-center gap-3 px-5 transition-colors duration-(--duration-fast) focus-visible:-outline-offset-2" > - + {/* 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. */} diff --git a/web/src/features/leaderboards/StandingsTable.tsx b/web/src/features/leaderboards/StandingsTable.tsx index 8e572d2..062de1c 100644 --- a/web/src/features/leaderboards/StandingsTable.tsx +++ b/web/src/features/leaderboards/StandingsTable.tsx @@ -18,6 +18,7 @@ import { } 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" }); @@ -154,7 +155,7 @@ export function StandingsTable({ > {standing.player.name} diff --git a/web/src/features/legacy/LegacyRunDetailList.tsx b/web/src/features/legacy/LegacyRunDetailList.tsx index 1e05138..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, @@ -51,7 +52,7 @@ export function LegacyRunDetailList({ > diff --git a/web/src/features/maps/Leaderboard.tsx b/web/src/features/maps/Leaderboard.tsx index d4cf645..d82c952 100644 --- a/web/src/features/maps/Leaderboard.tsx +++ b/web/src/features/maps/Leaderboard.tsx @@ -31,6 +31,7 @@ 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. */ @@ -309,7 +310,7 @@ export function Leaderboard({ > {entry.player.name} diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index b047e24..3fc9f5a 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -28,6 +28,7 @@ import { managesMaps } from "./MapHeader"; import { MapImage } from "./MapImage"; 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. */ @@ -527,11 +528,7 @@ function FilterPlayer({ href={`/players/${player.steamid64}`} className="hover:text-accent flex items-center gap-2" > - + {player.name} ) : ( diff --git a/web/src/features/players/PlayerHeader.tsx b/web/src/features/players/PlayerHeader.tsx index 70264b1..466b670 100644 --- a/web/src/features/players/PlayerHeader.tsx +++ b/web/src/features/players/PlayerHeader.tsx @@ -17,6 +17,7 @@ import { Masthead, type MastheadImage } from "@/ui/Masthead"; import { Medal } from "@/ui/Medal"; import { currentStyles } from "@/features/ruleset/styles"; import { getPlayer } from "./playerDetail"; +import { avatarSrc } from "@/features/players/avatarSrc"; export async function PlayerHeader({ steamid }: { steamid: string }) { const [result, me] = await Promise.all([ @@ -59,7 +60,7 @@ export async function PlayerHeader({ steamid }: { steamid: string }) {
- + {/* Most players have no country on Steam; a column of placeholders would only be noise. */} diff --git a/web/src/features/players/avatarSrc.ts b/web/src/features/players/avatarSrc.ts new file mode 100644 index 0000000..b2f2870 --- /dev/null +++ b/web/src/features/players/avatarSrc.ts @@ -0,0 +1,12 @@ +// Where a player's avatar comes from: the one the API has stored, or, when it has none yet, the API's avatar +// route, which fetches it from Steam on the spot (or draws a placeholder). So a player shown anywhere gets their +// picture even if they never signed in, as on ok-website. +export function avatarSrc(player: { + steamid64: string; + avatar_url?: string | null; +}): string { + return ( + player.avatar_url ?? + `/v1/players/${encodeURIComponent(player.steamid64)}/avatar` + ); +} diff --git a/web/src/features/runs/CommentForm.tsx b/web/src/features/runs/CommentForm.tsx index 10ab58b..a43900c 100644 --- a/web/src/features/runs/CommentForm.tsx +++ b/web/src/features/runs/CommentForm.tsx @@ -6,6 +6,7 @@ import { api, failureMessage, type Schemas } from "@/api/client"; import { Avatar } from "@/ui/Avatar"; import { Button } from "@/ui/Button"; import { Textarea } from "@/ui/Textarea"; +import { avatarSrc } from "@/features/players/avatarSrc"; const MAX_CHARS = 1000; @@ -59,11 +60,7 @@ export function CommentForm({ return (
- +