Skip to content

Commit 81f14d7

Browse files
unhappychoiceclaude
andcommitted
feat(fetcher): add steam_charts
Global most-played games on Steam right now, ranked by 24-hour peak concurrent count. Reads the public ISteamChartsService/GetMostPlayedGames endpoint (no auth) and resolves appid -> game name via parallel store.steampowered.com/api/appdetails calls (the chart endpoint returns appid only); a failed lookup falls back to an "app/<id>" placeholder so a single 404 does not sink the chart. 10 shapes via the shared games.rs builders. The Steam slot in the *_trending family alongside crypto_trending / huggingface_trending / lastfm_charts. Catalog: #68 (steam_charts). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 503f2c0 commit 81f14d7

2 files changed

Lines changed: 308 additions & 3 deletions

File tree

‎src/fetcher/steam/charts.rs‎

Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
1+
//! `steam_charts` — global top-played games on Steam right now (concurrent-player count).
2+
//!
3+
//! Reads the public `ISteamChartsService/GetMostPlayedGames/v1` endpoint (no auth required).
4+
//! That endpoint returns appid + concurrent count but no name, so the fetcher fans out parallel
5+
//! `store.steampowered.com/api/appdetails?filters=basic` calls to resolve names; failures fall
6+
//! through to a `app/<appid>` placeholder so a single 404 doesn't sink the chart.
7+
//!
8+
//! The Steam slot in the `*_trending` family alongside `crypto_trending` /
9+
//! `huggingface_trending` / `lastfm_charts` — "what the world is playing right now".
10+
11+
use std::collections::HashMap;
12+
use std::sync::OnceLock;
13+
14+
use async_trait::async_trait;
15+
use serde::Deserialize;
16+
use tokio::sync::Semaphore;
17+
use tokio::task::JoinSet;
18+
19+
use crate::fetcher::github::common::{cache_key, parse_options, payload};
20+
use crate::fetcher::steam::client;
21+
use crate::fetcher::steam::common::format_count;
22+
use crate::fetcher::steam::games::{
23+
GameRow, badge_body, bars_body, entries_body, image_body, image_linked_body, linked_text_body,
24+
markdown_body, number_series_body, text_block_body, text_body,
25+
};
26+
use crate::fetcher::{FetchContext, FetchError, Fetcher, Safety};
27+
use crate::options::OptionSchema;
28+
use crate::payload::{Body, Payload};
29+
use crate::render::Shape;
30+
31+
const SHAPES: &[Shape] = &[
32+
Shape::Bars,
33+
Shape::Entries,
34+
Shape::TextBlock,
35+
Shape::MarkdownTextBlock,
36+
Shape::LinkedTextBlock,
37+
Shape::ImageLinkedList,
38+
Shape::Text,
39+
Shape::NumberSeries,
40+
Shape::Image,
41+
Shape::Badge,
42+
];
43+
44+
const OPTION_SCHEMAS: &[OptionSchema] = &[OptionSchema {
45+
name: "count",
46+
type_hint: "integer (1..=30)",
47+
required: false,
48+
default: Some("10"),
49+
description: "Number of chart entries to display.",
50+
}];
51+
52+
const DEFAULT_COUNT: u32 = 10;
53+
const MIN_COUNT: u32 = 1;
54+
const MAX_COUNT: u32 = 30;
55+
const APPDETAIL_CONCURRENCY: usize = 4;
56+
const EMPTY_LABEL: &str = "chart unavailable";
57+
58+
pub struct SteamCharts;
59+
60+
#[derive(Debug, Default, Deserialize)]
61+
#[serde(deny_unknown_fields)]
62+
pub struct Options {
63+
pub count: Option<u32>,
64+
}
65+
66+
#[async_trait]
67+
impl Fetcher for SteamCharts {
68+
fn name(&self) -> &str {
69+
"steam_charts"
70+
}
71+
fn safety(&self) -> Safety {
72+
Safety::Safe
73+
}
74+
fn description(&self) -> &'static str {
75+
"Global most-played games on Steam right now, ranked by concurrent in-game count. Reads the public `ISteamChartsService/GetMostPlayedGames` endpoint (no auth) and resolves game names via parallel `appdetails` calls — the Steam slot in the `*_trending` family."
76+
}
77+
fn refresh_interval(&self) -> u64 {
78+
60 * 60 * 6
79+
}
80+
fn shapes(&self) -> &[Shape] {
81+
SHAPES
82+
}
83+
fn option_schemas(&self) -> &[OptionSchema] {
84+
OPTION_SCHEMAS
85+
}
86+
fn cache_key(&self, ctx: &FetchContext) -> String {
87+
let extra = ctx
88+
.options
89+
.as_ref()
90+
.and_then(|v| toml::to_string(v).ok())
91+
.unwrap_or_default();
92+
cache_key(self.name(), ctx, &extra)
93+
}
94+
async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> {
95+
let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?;
96+
let count = opts
97+
.count
98+
.unwrap_or(DEFAULT_COUNT)
99+
.clamp(MIN_COUNT, MAX_COUNT) as usize;
100+
let shape = ctx.shape.unwrap_or(Shape::Bars);
101+
102+
let ranks = fetch_ranks(count).await?;
103+
let names = resolve_names(&ranks).await;
104+
let rows = rows_from_ranks(&ranks, &names);
105+
Ok(payload(render_body(&rows, shape).await))
106+
}
107+
}
108+
109+
async fn fetch_ranks(count: usize) -> Result<Vec<RawRank>, FetchError> {
110+
let raw: ChartsResponse =
111+
client::get_json_public("ISteamChartsService/GetMostPlayedGames/v1/", &[]).await?;
112+
let mut ranks = raw.response.ranks.unwrap_or_default();
113+
ranks.truncate(count);
114+
Ok(ranks)
115+
}
116+
117+
async fn resolve_names(ranks: &[RawRank]) -> HashMap<u32, String> {
118+
let sem = appdetail_semaphore();
119+
let mut set: JoinSet<(u32, Option<String>)> = JoinSet::new();
120+
for r in ranks {
121+
let appid = r.appid;
122+
let sem = sem.clone();
123+
set.spawn(async move {
124+
let _permit = sem.acquire_owned().await.ok();
125+
(appid, fetch_app_name(appid).await)
126+
});
127+
}
128+
let mut out = HashMap::new();
129+
while let Some(res) = set.join_next().await {
130+
if let Ok((appid, Some(name))) = res {
131+
out.insert(appid, name);
132+
}
133+
}
134+
out
135+
}
136+
137+
fn appdetail_semaphore() -> std::sync::Arc<Semaphore> {
138+
static SEM: OnceLock<std::sync::Arc<Semaphore>> = OnceLock::new();
139+
SEM.get_or_init(|| std::sync::Arc::new(Semaphore::new(APPDETAIL_CONCURRENCY)))
140+
.clone()
141+
}
142+
143+
async fn fetch_app_name(appid: u32) -> Option<String> {
144+
let appid_str = appid.to_string();
145+
let raw: AppDetailsResponse = client::get_store_json(
146+
"api/appdetails",
147+
&[
148+
("appids", &appid_str),
149+
("filters", "basic"),
150+
("cc", "us"),
151+
("l", "english"),
152+
],
153+
)
154+
.await
155+
.ok()?;
156+
raw.0
157+
.get(&appid_str)
158+
.and_then(|entry| entry.data.as_ref())
159+
.map(|data| data.name.clone())
160+
.filter(|n| !n.is_empty())
161+
}
162+
163+
fn rows_from_ranks(ranks: &[RawRank], names: &HashMap<u32, String>) -> Vec<GameRow> {
164+
ranks
165+
.iter()
166+
.map(|r| GameRow {
167+
rank: r.rank as usize,
168+
appid: r.appid,
169+
name: names
170+
.get(&r.appid)
171+
.cloned()
172+
.unwrap_or_else(|| format!("app/{}", r.appid)),
173+
value: r.peak_in_game,
174+
value_label: peak_label(r.peak_in_game),
175+
})
176+
.collect()
177+
}
178+
179+
/// `1.2M peak` — the chart endpoint reports 24-hour peak concurrent count rather than the
180+
/// live "right now" number (Valve doesn't expose the latter on this rollup), so the unit
181+
/// reads "peak" rather than "players" to stay honest about what's shown.
182+
fn peak_label(n: u64) -> String {
183+
format!("{} peak", format_count(n))
184+
}
185+
186+
async fn render_body(rows: &[GameRow], shape: Shape) -> Body {
187+
match shape {
188+
Shape::Bars => bars_body(rows),
189+
Shape::Entries => entries_body(rows, EMPTY_LABEL),
190+
Shape::TextBlock => text_block_body(rows, EMPTY_LABEL),
191+
Shape::MarkdownTextBlock => markdown_body(rows, EMPTY_LABEL),
192+
Shape::LinkedTextBlock => linked_text_body(rows, EMPTY_LABEL),
193+
Shape::ImageLinkedList => image_linked_body(rows).await,
194+
Shape::NumberSeries => number_series_body(rows),
195+
Shape::Image => image_body(rows).await,
196+
Shape::Badge => badge_body(rows, "today", "chart unavailable"),
197+
_ => text_body(rows, EMPTY_LABEL),
198+
}
199+
}
200+
201+
#[derive(Debug, Deserialize)]
202+
struct ChartsResponse {
203+
response: ChartsBody,
204+
}
205+
206+
#[derive(Debug, Default, Deserialize)]
207+
struct ChartsBody {
208+
#[serde(default)]
209+
ranks: Option<Vec<RawRank>>,
210+
}
211+
212+
#[derive(Debug, Deserialize)]
213+
struct RawRank {
214+
rank: u32,
215+
appid: u32,
216+
/// 24-hour peak concurrent players. `ISteamChartsService/GetMostPlayedGames/v1` omits the
217+
/// instantaneous "right now" count; this `peak_in_game` rollup is what the endpoint exposes
218+
/// and what SteamDB / steamcharts.com surface as their headline metric.
219+
#[serde(default)]
220+
peak_in_game: u64,
221+
}
222+
223+
/// Steam returns `appdetails` as a top-level map keyed by appid string. Each value carries a
224+
/// `success` flag plus an optional `data` block; failed lookups omit `data` entirely.
225+
#[derive(Debug, Deserialize)]
226+
struct AppDetailsResponse(HashMap<String, AppDetailsEntry>);
227+
228+
#[derive(Debug, Deserialize)]
229+
struct AppDetailsEntry {
230+
#[serde(default)]
231+
data: Option<AppDetailsData>,
232+
}
233+
234+
#[derive(Debug, Deserialize)]
235+
struct AppDetailsData {
236+
#[serde(default)]
237+
name: String,
238+
}
239+
240+
#[cfg(test)]
241+
mod tests {
242+
use super::*;
243+
244+
#[test]
245+
fn fetcher_metadata_is_in_steam_family_and_safe_for_public_endpoint() {
246+
let f = SteamCharts;
247+
assert_eq!(f.name(), "steam_charts");
248+
assert_eq!(f.safety(), Safety::Safe);
249+
assert!(f.refresh_interval() > 0);
250+
}
251+
252+
#[test]
253+
fn rows_from_ranks_fills_names_when_present_and_falls_back_otherwise() {
254+
let ranks = vec![
255+
RawRank {
256+
rank: 1,
257+
appid: 730,
258+
peak_in_game: 1_500_000,
259+
},
260+
RawRank {
261+
rank: 2,
262+
appid: 999_999,
263+
peak_in_game: 50_000,
264+
},
265+
];
266+
let mut names = HashMap::new();
267+
names.insert(730_u32, "Counter-Strike 2".into());
268+
269+
let rows = rows_from_ranks(&ranks, &names);
270+
assert_eq!(rows[0].name, "Counter-Strike 2");
271+
assert_eq!(rows[1].name, "app/999999");
272+
assert_eq!(rows[0].value, 1_500_000);
273+
assert_eq!(rows[0].value_label, "1.5M peak");
274+
}
275+
276+
#[test]
277+
fn peak_label_drops_player_unit_and_keeps_magnitude() {
278+
assert_eq!(peak_label(0), "0 peak");
279+
assert_eq!(peak_label(750), "750 peak");
280+
assert_eq!(peak_label(1_500_000), "1.5M peak");
281+
}
282+
283+
#[test]
284+
fn options_clamp_count_to_supported_range() {
285+
let opts = Options { count: Some(99) };
286+
let clamped = opts
287+
.count
288+
.unwrap_or(DEFAULT_COUNT)
289+
.clamp(MIN_COUNT, MAX_COUNT);
290+
assert_eq!(clamped, MAX_COUNT);
291+
}
292+
293+
#[test]
294+
fn options_struct_rejects_unknown_keys() {
295+
let raw = toml::Value::try_from(serde_json::json!({"unknown": 1})).unwrap();
296+
let err = parse_options::<Options>(Some(&raw)).unwrap_err();
297+
assert!(err.contains("invalid options"));
298+
}
299+
}

‎src/fetcher/steam/mod.rs‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,16 @@
33
//!
44
//! Every authenticated request targets the fixed host `api.steampowered.com`. Config-provided
55
//! fields (`steam_id`, `count`, …) only change which resource on that host is queried; the API
6-
//! key never leaves to an attacker-controlled origin. Classified as `Safety::Safe`, same model
7-
//! as the `github_*` and `lastfm_*` families.
6+
//! key never leaves to an attacker-controlled origin. The `steam_charts` fetcher also calls the
7+
//! `store.steampowered.com/api/appdetails` store endpoint to resolve appid → game name (the
8+
//! chart endpoint itself returns appid-only), again with a fixed host. Both are classified as
9+
//! `Safety::Safe`, same model as the `github_*` and `lastfm_*` families.
810
//!
911
//! Auth: `STEAM_API_KEY` — create one at https://steamcommunity.com/dev/apikey and put it in
10-
//! `$HOME/.splashboard/secrets.toml`.
12+
//! `$HOME/.splashboard/secrets.toml`. `steam_charts` is the only family member that needs no
13+
//! key (the chart endpoint is public).
1114
15+
mod charts;
1216
mod client;
1317
mod common;
1418
mod games;
@@ -25,6 +29,7 @@ pub fn fetchers() -> Vec<Arc<dyn Fetcher>> {
2529
Arc::new(player_summary::SteamPlayerSummary),
2630
Arc::new(recently_played::SteamRecentlyPlayed),
2731
Arc::new(owned_games::SteamOwnedGames),
32+
Arc::new(charts::SteamCharts),
2833
]
2934
}
3035

@@ -44,5 +49,6 @@ mod tests {
4449
assert!(names.contains(&"steam_player_summary".to_string()));
4550
assert!(names.contains(&"steam_recently_played".to_string()));
4651
assert!(names.contains(&"steam_owned_games".to_string()));
52+
assert!(names.contains(&"steam_charts".to_string()));
4753
}
4854
}

0 commit comments

Comments
 (0)