Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
94 lines
2.4 KiB
Go
94 lines
2.4 KiB
Go
package services
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in
|
|
// minutes.
|
|
type SteamRecentGame struct {
|
|
AppID int `json:"appid"`
|
|
Name string `json:"name"`
|
|
Playtime2Weeks int `json:"playtime_2weeks"`
|
|
PlaytimeForever int `json:"playtime_forever"`
|
|
}
|
|
|
|
// SteamRecentGamesResponse mirrors Steam's envelope, which wraps everything
|
|
// in a "response" object.
|
|
type SteamRecentGamesResponse struct {
|
|
Response struct {
|
|
TotalCount int `json:"total_count"`
|
|
Games []SteamRecentGame `json:"games"`
|
|
} `json:"response"`
|
|
}
|
|
|
|
// PersonaState > 0 is some kind of online.
|
|
type SteamPlayerSummary struct {
|
|
PersonaState int `json:"personastate"`
|
|
}
|
|
|
|
// SteamPlayerSummariesResponse mirrors Steam's response envelope.
|
|
type SteamPlayerSummariesResponse struct {
|
|
Response struct {
|
|
Players []SteamPlayerSummary `json:"players"`
|
|
} `json:"response"`
|
|
}
|
|
|
|
// Steam answers 200 with nothing for a private profile or bad key, so empty
|
|
// is not an error.
|
|
func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) {
|
|
url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID)
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
resp, err := client.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var result SteamRecentGamesResponse
|
|
if err := json.Unmarshal(body, &result); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result.Response.Games, nil
|
|
}
|
|
|
|
// FetchPlayerSummary returns the profile's online status, or (nil, nil) when
|
|
// Steam returns no players (private or unknown profile).
|
|
func FetchPlayerSummary(apiKey, steamID string) (*SteamPlayerSummary, error) {
|
|
url := fmt.Sprintf("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=%s&steamids=%s", apiKey, steamID)
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
resp, err := client.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var result SteamPlayerSummariesResponse
|
|
if err := json.Unmarshal(body, &result); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(result.Response.Players) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
return &result.Response.Players[0], nil
|
|
}
|