CI / test (push) Successful in 37s
Add GET /api/steam/friends and /api/steam/friends/{steamid}, a Friends tab with manual SteamID entry for private profiles, and one-hour caching for friend lists and owned games.
195 lines
6.1 KiB
Python
195 lines
6.1 KiB
Python
"""Optional Steam Web API client.
|
|
|
|
Key resolution (first match wins):
|
|
1. STEAMBASE_STEAM_API_KEY environment variable
|
|
2. data/steam_api_key.txt (gitignored, one line)
|
|
|
|
The key is read only on the server/CLI side. It is never logged or returned
|
|
to the browser. Without a key every helper reports "not configured" and the
|
|
rest of SteamBase keeps working.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
KEY_ENV = "STEAMBASE_STEAM_API_KEY"
|
|
STEAM_ID_ENV = "STEAMBASE_STEAM_ID"
|
|
KEY_FILE = os.path.join(BASE_DIR, "data", "steam_api_key.txt")
|
|
API_ROOT = "https://api.steampowered.com"
|
|
USER_AGENT = "SteamBase/1.0"
|
|
DEFAULT_TIMEOUT = 15
|
|
CACHE_TTL = 900
|
|
FRIEND_CACHE_TTL = 3600
|
|
|
|
_cache = {}
|
|
|
|
|
|
class SteamApiError(RuntimeError):
|
|
"""Raised for Steam API failures without exposing the key."""
|
|
|
|
def __init__(self, message, status=None):
|
|
super().__init__(message)
|
|
self.status = status
|
|
|
|
|
|
def load_key():
|
|
key = (os.environ.get(KEY_ENV) or "").strip()
|
|
if key:
|
|
return key
|
|
try:
|
|
with open(KEY_FILE, encoding="utf-8") as handle:
|
|
return handle.read().strip() or None
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def has_key():
|
|
return bool(load_key())
|
|
|
|
|
|
def steam_id(con=None):
|
|
value = (os.environ.get(STEAM_ID_ENV) or "").strip()
|
|
if value:
|
|
return value
|
|
if con is not None:
|
|
try:
|
|
row = con.execute(
|
|
"SELECT value FROM schema_meta WHERE key = 'steamid'").fetchone()
|
|
except Exception:
|
|
row = None
|
|
if row and row[0]:
|
|
return str(row[0])
|
|
return None
|
|
|
|
|
|
def _get_json(path, params):
|
|
key = load_key()
|
|
if not key:
|
|
raise SteamApiError("Steam API key is not configured")
|
|
query = dict(params)
|
|
query["key"] = key
|
|
url = f"{API_ROOT}/{path}/?{urllib.parse.urlencode(query)}"
|
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=DEFAULT_TIMEOUT) as response:
|
|
return json.load(response)
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code in (401, 403):
|
|
message = "Steam profile is private or access is denied"
|
|
elif exc.code == 429:
|
|
message = "Steam API rate limit exceeded"
|
|
else:
|
|
message = f"Steam API HTTP {exc.code}"
|
|
raise SteamApiError(message, status=exc.code) from None
|
|
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
raise SteamApiError(f"Steam API request failed: {type(exc).__name__}") from None
|
|
|
|
|
|
def player_achievements(appid, steamid):
|
|
"""Raw player achievements, or None when the game has no stats."""
|
|
data = _get_json(
|
|
"ISteamUserStats/GetPlayerAchievements/v0001",
|
|
{"appid": appid, "steamid": steamid, "l": "english"})
|
|
stats = data.get("playerstats") or {}
|
|
if not stats.get("success"):
|
|
return None
|
|
return stats.get("achievements") or []
|
|
|
|
|
|
def schema_achievements(appid):
|
|
"""Achievement metadata (titles, descriptions, icons)."""
|
|
data = _get_json(
|
|
"ISteamUserStats/GetSchemaForGame/v2",
|
|
{"appid": appid, "l": "english"})
|
|
stats = (data.get("game") or {}).get("availableGameStats") or {}
|
|
return stats.get("achievements") or []
|
|
|
|
|
|
def achievements(appid, steamid, ttl=CACHE_TTL):
|
|
"""Combined achievement progress, cached in memory for ``ttl`` seconds."""
|
|
cache_key = (int(appid), str(steamid))
|
|
now = time.time()
|
|
cached = _cache.get(cache_key)
|
|
if cached and now - cached[0] < ttl:
|
|
return cached[1]
|
|
|
|
player = player_achievements(appid, steamid)
|
|
if player is None:
|
|
result = None
|
|
else:
|
|
schema = {item.get("name"): item for item in schema_achievements(appid)}
|
|
items = []
|
|
for entry in player:
|
|
meta = schema.get(entry.get("apiname")) or {}
|
|
items.append({
|
|
"name": entry.get("apiname"),
|
|
"title": meta.get("displayName") or entry.get("name") or entry.get("apiname"),
|
|
"description": meta.get("description") or entry.get("description") or "",
|
|
"icon": meta.get("icon") or "",
|
|
"hidden": bool(meta.get("hidden", 0)),
|
|
"achieved": bool(entry.get("achieved")),
|
|
"unlocktime": entry.get("unlocktime") or 0,
|
|
})
|
|
total = len(items)
|
|
achieved = sum(1 for item in items if item["achieved"])
|
|
result = {
|
|
"total": total,
|
|
"achieved": achieved,
|
|
"percent": round(100 * achieved / total, 1) if total else 0.0,
|
|
"achievements": items,
|
|
}
|
|
_cache[cache_key] = (now, result)
|
|
return result
|
|
|
|
|
|
def _cached(key, ttl, loader):
|
|
now = time.time()
|
|
cached = _cache.get(key)
|
|
if cached and now - cached[0] < ttl:
|
|
return cached[1]
|
|
value = loader()
|
|
_cache[key] = (now, value)
|
|
return value
|
|
|
|
|
|
def friends(steamid, ttl=FRIEND_CACHE_TTL):
|
|
"""Friend list, or [] when the profile is private/unavailable."""
|
|
def load():
|
|
data = _get_json(
|
|
"ISteamUser/GetFriendList/v0001",
|
|
{"steamid": steamid, "relationship": "friend"})
|
|
return (data.get("friendslist") or {}).get("friends") or []
|
|
return _cached(("friends", str(steamid)), ttl, load)
|
|
|
|
|
|
def player_summaries(steamids, ttl=FRIEND_CACHE_TTL):
|
|
ids = [str(value) for value in steamids if str(value).isdigit()][:100]
|
|
if not ids:
|
|
return []
|
|
|
|
def load():
|
|
data = _get_json(
|
|
"ISteamUser/GetPlayerSummaries/v0002",
|
|
{"steamids": ",".join(ids)})
|
|
return (data.get("response") or {}).get("players") or []
|
|
return _cached(("summaries", ",".join(ids)), ttl, load)
|
|
|
|
|
|
def owned_games(steamid, ttl=FRIEND_CACHE_TTL):
|
|
def load():
|
|
data = _get_json(
|
|
"IPlayerService/GetOwnedGames/v0001",
|
|
{"steamid": steamid, "include_appinfo": 1,
|
|
"include_played_free_games": 1})
|
|
return (data.get("response") or {}).get("games") or []
|
|
return _cached(("owned", str(steamid)), ttl, load)
|
|
|
|
|
|
def clear_cache():
|
|
_cache.clear()
|