|
| 1 | +//! Shared HTTP client + auth for the `steam_*` fetcher family. |
| 2 | +//! |
| 3 | +//! Targets `api.steampowered.com` (Web API) and `store.steampowered.com` (store appdetails |
| 4 | +//! used by `steam_charts` to resolve appid → game name). Both hosts are hardcoded — config |
| 5 | +//! can only change *which resource* on those hosts is queried, never the host itself, so the |
| 6 | +//! family stays `Safety::Safe`. |
| 7 | +//! |
| 8 | +//! Auth: `STEAM_API_KEY` (free, https://steamcommunity.com/dev/apikey). The chart endpoint |
| 9 | +//! [`get_json_public`] is open and skips the key entirely. |
| 10 | +
|
| 11 | +use std::sync::OnceLock; |
| 12 | +use std::time::Duration; |
| 13 | + |
| 14 | +use reqwest::Client; |
| 15 | +use serde::de::DeserializeOwned; |
| 16 | + |
| 17 | +use crate::fetcher::FetchError; |
| 18 | + |
| 19 | +const API_BASE: &str = "https://api.steampowered.com"; |
| 20 | +const STORE_BASE: &str = "https://store.steampowered.com"; |
| 21 | +const USER_AGENT: &str = concat!("splashboard/", env!("CARGO_PKG_VERSION")); |
| 22 | +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); |
| 23 | +const MAX_BYTES: usize = 5 * 1024 * 1024; |
| 24 | + |
| 25 | +pub fn http() -> &'static Client { |
| 26 | + static CLIENT: OnceLock<Client> = OnceLock::new(); |
| 27 | + CLIENT.get_or_init(|| { |
| 28 | + Client::builder() |
| 29 | + .user_agent(USER_AGENT) |
| 30 | + .timeout(REQUEST_TIMEOUT) |
| 31 | + .gzip(true) |
| 32 | + .build() |
| 33 | + .expect("reqwest client should build with default config") |
| 34 | + }) |
| 35 | +} |
| 36 | + |
| 37 | +pub fn resolve_api_key() -> Result<String, FetchError> { |
| 38 | + std::env::var("STEAM_API_KEY").map_err(|_| FetchError::Failed("STEAM_API_KEY not set".into())) |
| 39 | +} |
| 40 | + |
| 41 | +/// Resolve a Steam ID from explicit option or `STEAM_ID` env. Mirrors steamfetch's resolution |
| 42 | +/// order so the same env works across both tools. Returns a trimmed non-empty `String`. |
| 43 | +pub fn resolve_steam_id(explicit: Option<&str>) -> Result<String, FetchError> { |
| 44 | + let from_option = explicit.map(str::trim).filter(|s| !s.is_empty()); |
| 45 | + if let Some(id) = from_option { |
| 46 | + return Ok(id.to_string()); |
| 47 | + } |
| 48 | + std::env::var("STEAM_ID") |
| 49 | + .ok() |
| 50 | + .map(|s| s.trim().to_string()) |
| 51 | + .filter(|s| !s.is_empty()) |
| 52 | + .ok_or_else(|| { |
| 53 | + FetchError::Failed( |
| 54 | + "steam_id missing: set `steam_id = \"<id64>\"` or export STEAM_ID".into(), |
| 55 | + ) |
| 56 | + }) |
| 57 | +} |
| 58 | + |
| 59 | +/// Authenticated `GET https://api.steampowered.com/<path>?key=<key>&<params>`. |
| 60 | +pub async fn get_json<T: DeserializeOwned>( |
| 61 | + path: &str, |
| 62 | + params: &[(&str, &str)], |
| 63 | +) -> Result<T, FetchError> { |
| 64 | + let key = resolve_api_key()?; |
| 65 | + let mut url = url::Url::parse(&format!("{API_BASE}/{path}")) |
| 66 | + .map_err(|e| FetchError::Failed(format!("steam invalid path {path:?}: {e}")))?; |
| 67 | + { |
| 68 | + let mut q = url.query_pairs_mut(); |
| 69 | + q.append_pair("key", &key); |
| 70 | + for (k, v) in params { |
| 71 | + q.append_pair(k, v); |
| 72 | + } |
| 73 | + } |
| 74 | + request_json(url.as_str()).await |
| 75 | +} |
| 76 | + |
| 77 | +/// Unauthenticated `GET https://api.steampowered.com/<path>?<params>`. Used by `steam_charts` |
| 78 | +/// (`ISteamChartsService/GetMostPlayedGames`), which is public and rejects requests that carry |
| 79 | +/// a stray `key=` parameter on some shards. |
| 80 | +pub async fn get_json_public<T: DeserializeOwned>( |
| 81 | + path: &str, |
| 82 | + params: &[(&str, &str)], |
| 83 | +) -> Result<T, FetchError> { |
| 84 | + let mut url = url::Url::parse(&format!("{API_BASE}/{path}")) |
| 85 | + .map_err(|e| FetchError::Failed(format!("steam invalid path {path:?}: {e}")))?; |
| 86 | + { |
| 87 | + let mut q = url.query_pairs_mut(); |
| 88 | + for (k, v) in params { |
| 89 | + q.append_pair(k, v); |
| 90 | + } |
| 91 | + } |
| 92 | + request_json(url.as_str()).await |
| 93 | +} |
| 94 | + |
| 95 | +/// `GET https://store.steampowered.com/<path>?<params>`. Used to resolve appid → game name + |
| 96 | +/// header image for the chart fetcher. |
| 97 | +pub async fn get_store_json<T: DeserializeOwned>( |
| 98 | + path: &str, |
| 99 | + params: &[(&str, &str)], |
| 100 | +) -> Result<T, FetchError> { |
| 101 | + let mut url = url::Url::parse(&format!("{STORE_BASE}/{path}")) |
| 102 | + .map_err(|e| FetchError::Failed(format!("steam store invalid path {path:?}: {e}")))?; |
| 103 | + { |
| 104 | + let mut q = url.query_pairs_mut(); |
| 105 | + for (k, v) in params { |
| 106 | + q.append_pair(k, v); |
| 107 | + } |
| 108 | + } |
| 109 | + request_json(url.as_str()).await |
| 110 | +} |
| 111 | + |
| 112 | +async fn request_json<T: DeserializeOwned>(url: &str) -> Result<T, FetchError> { |
| 113 | + let res = http() |
| 114 | + .get(url) |
| 115 | + .send() |
| 116 | + .await |
| 117 | + .map_err(|e| FetchError::Failed(format!("steam request failed: {e}")))?; |
| 118 | + parse_json(res).await |
| 119 | +} |
| 120 | + |
| 121 | +async fn parse_json<T: DeserializeOwned>(res: reqwest::Response) -> Result<T, FetchError> { |
| 122 | + let status = res.status(); |
| 123 | + let bytes = res |
| 124 | + .bytes() |
| 125 | + .await |
| 126 | + .map_err(|e| FetchError::Failed(format!("steam read body: {e}")))?; |
| 127 | + if bytes.len() > MAX_BYTES { |
| 128 | + return Err(FetchError::Failed(format!( |
| 129 | + "steam response too large ({} bytes, cap {MAX_BYTES})", |
| 130 | + bytes.len() |
| 131 | + ))); |
| 132 | + } |
| 133 | + if !status.is_success() { |
| 134 | + return Err(FetchError::Failed(format!("steam {status}"))); |
| 135 | + } |
| 136 | + serde_json::from_slice(&bytes).map_err(|e| FetchError::Failed(format!("steam json parse: {e}"))) |
| 137 | +} |
| 138 | + |
| 139 | +#[cfg(test)] |
| 140 | +mod tests { |
| 141 | + use super::*; |
| 142 | + |
| 143 | + #[test] |
| 144 | + fn resolve_api_key_fails_with_clear_message_when_unset() { |
| 145 | + let _lock = crate::paths::TEST_ENV_LOCK |
| 146 | + .lock() |
| 147 | + .unwrap_or_else(|e| e.into_inner()); |
| 148 | + let prev = std::env::var("STEAM_API_KEY").ok(); |
| 149 | + unsafe { std::env::remove_var("STEAM_API_KEY") }; |
| 150 | + let err = resolve_api_key().unwrap_err(); |
| 151 | + assert!(matches!(err, FetchError::Failed(m) if m == "STEAM_API_KEY not set")); |
| 152 | + if let Some(v) = prev { |
| 153 | + unsafe { std::env::set_var("STEAM_API_KEY", v) }; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn resolve_api_key_reads_env() { |
| 159 | + let _lock = crate::paths::TEST_ENV_LOCK |
| 160 | + .lock() |
| 161 | + .unwrap_or_else(|e| e.into_inner()); |
| 162 | + let prev = std::env::var("STEAM_API_KEY").ok(); |
| 163 | + unsafe { std::env::set_var("STEAM_API_KEY", "abc123") }; |
| 164 | + assert_eq!(resolve_api_key().unwrap(), "abc123"); |
| 165 | + match prev { |
| 166 | + Some(v) => unsafe { std::env::set_var("STEAM_API_KEY", v) }, |
| 167 | + None => unsafe { std::env::remove_var("STEAM_API_KEY") }, |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn resolve_steam_id_prefers_explicit_option_over_env() { |
| 173 | + let _lock = crate::paths::TEST_ENV_LOCK |
| 174 | + .lock() |
| 175 | + .unwrap_or_else(|e| e.into_inner()); |
| 176 | + let prev = std::env::var("STEAM_ID").ok(); |
| 177 | + unsafe { std::env::set_var("STEAM_ID", "env-id") }; |
| 178 | + assert_eq!(resolve_steam_id(Some("option-id")).unwrap(), "option-id"); |
| 179 | + match prev { |
| 180 | + Some(v) => unsafe { std::env::set_var("STEAM_ID", v) }, |
| 181 | + None => unsafe { std::env::remove_var("STEAM_ID") }, |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn resolve_steam_id_falls_back_to_env_when_option_missing_or_blank() { |
| 187 | + let _lock = crate::paths::TEST_ENV_LOCK |
| 188 | + .lock() |
| 189 | + .unwrap_or_else(|e| e.into_inner()); |
| 190 | + let prev = std::env::var("STEAM_ID").ok(); |
| 191 | + unsafe { std::env::set_var("STEAM_ID", "env-id") }; |
| 192 | + assert_eq!(resolve_steam_id(None).unwrap(), "env-id"); |
| 193 | + assert_eq!(resolve_steam_id(Some(" ")).unwrap(), "env-id"); |
| 194 | + match prev { |
| 195 | + Some(v) => unsafe { std::env::set_var("STEAM_ID", v) }, |
| 196 | + None => unsafe { std::env::remove_var("STEAM_ID") }, |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + #[test] |
| 201 | + fn resolve_steam_id_errors_when_neither_set() { |
| 202 | + let _lock = crate::paths::TEST_ENV_LOCK |
| 203 | + .lock() |
| 204 | + .unwrap_or_else(|e| e.into_inner()); |
| 205 | + let prev = std::env::var("STEAM_ID").ok(); |
| 206 | + unsafe { std::env::remove_var("STEAM_ID") }; |
| 207 | + let err = resolve_steam_id(None).unwrap_err(); |
| 208 | + let FetchError::Failed(msg) = err else { |
| 209 | + panic!("expected FetchError::Failed"); |
| 210 | + }; |
| 211 | + assert!(msg.contains("steam_id")); |
| 212 | + if let Some(v) = prev { |
| 213 | + unsafe { std::env::set_var("STEAM_ID", v) }; |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + #[test] |
| 218 | + fn http_reuses_the_same_client() { |
| 219 | + assert!(std::ptr::eq(http(), http())); |
| 220 | + } |
| 221 | +} |
0 commit comments