|
| 1 | +package models |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "regexp" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +var steamID64XMLRe = regexp.MustCompile(`(?i)<steamID64>\s*(\d+)\s*</steamID64>`) |
| 15 | + |
| 16 | +const maxVanityLen = 64 |
| 17 | +const maxSteamXMLBytes = 1 << 20 |
| 18 | +const maxSteamAPIBodyBytes = 64 << 10 |
| 19 | + |
| 20 | +// SteamUserInputOpts tweaks how vanity URLs (/id/{name}) are turned into a SteamID. |
| 21 | +// Zero value: same as ParseSteamUserInput — uses the community profile ?xml=1 fetch. |
| 22 | +type SteamUserInputOpts struct { |
| 23 | + // UseWebAPIForVanity calls ISteamUser/ResolveVanityURL instead of scraping ?xml=1. |
| 24 | + UseWebAPIForVanity bool |
| 25 | + // SteamWebAPIKey from https://steamcommunity.com/dev/apikey — required when UseWebAPIForVanity is true. |
| 26 | + SteamWebAPIKey string |
| 27 | +} |
| 28 | + |
| 29 | +// ParseSteamUserInput resolves a SteamID from a decimal 64-bit ID string, a |
| 30 | +// steamcommunity.com /profiles/{id} URL, or /id/{vanity} URL (via Valve's ?xml=1 profile feed). |
| 31 | +func ParseSteamUserInput(ctx context.Context, httpClient *http.Client, raw string) (*SteamID, error) { |
| 32 | + return ParseSteamUserInputWithOpts(ctx, httpClient, raw, nil) |
| 33 | +} |
| 34 | + |
| 35 | +// ParseSteamUserInputWithOpts is like ParseSteamUserInput but can resolve custom URLs via the Steam Web API. |
| 36 | +func ParseSteamUserInputWithOpts(ctx context.Context, httpClient *http.Client, raw string, opts *SteamUserInputOpts) (*SteamID, error) { |
| 37 | + if httpClient == nil { |
| 38 | + httpClient = http.DefaultClient |
| 39 | + } |
| 40 | + s := strings.TrimSpace(raw) |
| 41 | + if s == "" { |
| 42 | + return nil, fmt.Errorf("empty steam identifier") |
| 43 | + } |
| 44 | + if id, err := ToSteamID(s); err == nil { |
| 45 | + return id, nil |
| 46 | + } |
| 47 | + normalized := normalizeSteamProfileURL(s) |
| 48 | + u, err := url.Parse(normalized) |
| 49 | + if err != nil { |
| 50 | + return nil, fmt.Errorf("parse url: %w", err) |
| 51 | + } |
| 52 | + host := strings.ToLower(strings.TrimPrefix(u.Hostname(), "www.")) |
| 53 | + if host != "steamcommunity.com" { |
| 54 | + return nil, fmt.Errorf("not a steam community url") |
| 55 | + } |
| 56 | + path := strings.Trim(u.Path, "/") |
| 57 | + segments := strings.Split(path, "/") |
| 58 | + if len(segments) >= 2 && strings.EqualFold(segments[0], "profiles") { |
| 59 | + idStr := segments[1] |
| 60 | + if idStr == "" { |
| 61 | + return nil, fmt.Errorf("missing profile id") |
| 62 | + } |
| 63 | + return ToSteamID(idStr) |
| 64 | + } |
| 65 | + if len(segments) >= 2 && strings.EqualFold(segments[0], "id") { |
| 66 | + vanity := segments[1] |
| 67 | + if vanity == "" { |
| 68 | + return nil, fmt.Errorf("missing vanity url") |
| 69 | + } |
| 70 | + if len(vanity) > maxVanityLen { |
| 71 | + return nil, fmt.Errorf("vanity too long") |
| 72 | + } |
| 73 | + if opts != nil && opts.UseWebAPIForVanity { |
| 74 | + key := strings.TrimSpace(opts.SteamWebAPIKey) |
| 75 | + if key == "" { |
| 76 | + return nil, fmt.Errorf("steam web api key is required for web api vanity resolution") |
| 77 | + } |
| 78 | + return ResolveVanitySteamWebAPI(ctx, httpClient, key, vanity) |
| 79 | + } |
| 80 | + return resolveSteamVanityXML(ctx, httpClient, vanity) |
| 81 | + } |
| 82 | + return nil, fmt.Errorf("unrecognized steam profile path") |
| 83 | +} |
| 84 | + |
| 85 | +func normalizeSteamProfileURL(s string) string { |
| 86 | + s = strings.TrimSpace(s) |
| 87 | + lower := strings.ToLower(s) |
| 88 | + if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { |
| 89 | + return s |
| 90 | + } |
| 91 | + if strings.HasPrefix(lower, "steamcommunity.com") || strings.HasPrefix(lower, "www.steamcommunity.com") { |
| 92 | + return "https://" + s |
| 93 | + } |
| 94 | + return s |
| 95 | +} |
| 96 | + |
| 97 | +// resolveSteamVanityXML hits steamcommunity.com/id/{vanity}?xml=1 and pulls the 64-bit ID |
| 98 | +// from the response. Fine for the odd manual lookup; don’t use this for bulk scraping—Steam |
| 99 | +// will rate-limit or block you. For high volume, cache results, throttle requests, or use |
| 100 | +// the Web API ResolveVanityURL instead. |
| 101 | +func resolveSteamVanityXML(ctx context.Context, client *http.Client, vanity string) (*SteamID, error) { |
| 102 | + reqURL := "https://steamcommunity.com/id/" + url.PathEscape(vanity) + "?xml=1" |
| 103 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) |
| 104 | + if err != nil { |
| 105 | + return nil, err |
| 106 | + } |
| 107 | + req.Header.Set("User-Agent", "reverse-watch/1.0") |
| 108 | + resp, err := client.Do(req) |
| 109 | + if err != nil { |
| 110 | + return nil, err |
| 111 | + } |
| 112 | + defer resp.Body.Close() |
| 113 | + if resp.StatusCode != http.StatusOK { |
| 114 | + return nil, fmt.Errorf("steam profile returned status %d", resp.StatusCode) |
| 115 | + } |
| 116 | + body, err := io.ReadAll(io.LimitReader(resp.Body, maxSteamXMLBytes)) |
| 117 | + if err != nil { |
| 118 | + return nil, err |
| 119 | + } |
| 120 | + m := steamID64XMLRe.FindSubmatch(body) |
| 121 | + if m == nil { |
| 122 | + return nil, fmt.Errorf("steam id not found in profile response") |
| 123 | + } |
| 124 | + return ToSteamID(string(m[1])) |
| 125 | +} |
| 126 | + |
| 127 | +// ResolveVanitySteamWebAPI turns a custom profile slug into SteamID64 using |
| 128 | +// ISteamUser/ResolveVanityURL. You need an API key from https://steamcommunity.com/dev/apikey. |
| 129 | +func ResolveVanitySteamWebAPI(ctx context.Context, client *http.Client, apiKey, vanity string) (*SteamID, error) { |
| 130 | + if client == nil { |
| 131 | + client = http.DefaultClient |
| 132 | + } |
| 133 | + apiKey = strings.TrimSpace(apiKey) |
| 134 | + if apiKey == "" { |
| 135 | + return nil, fmt.Errorf("empty steam web api key") |
| 136 | + } |
| 137 | + vanity = strings.TrimSpace(vanity) |
| 138 | + if vanity == "" { |
| 139 | + return nil, fmt.Errorf("empty vanity") |
| 140 | + } |
| 141 | + |
| 142 | + q := url.Values{} |
| 143 | + q.Set("key", apiKey) |
| 144 | + q.Set("vanityurl", vanity) |
| 145 | + q.Set("url_type", "1") |
| 146 | + reqURL := "https://api.steampowered.com/ISteamUser/ResolveVanityURL/v1/?" + q.Encode() |
| 147 | + |
| 148 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) |
| 149 | + if err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + req.Header.Set("User-Agent", "reverse-watch/1.0") |
| 153 | + |
| 154 | + resp, err := client.Do(req) |
| 155 | + if err != nil { |
| 156 | + return nil, err |
| 157 | + } |
| 158 | + defer resp.Body.Close() |
| 159 | + |
| 160 | + body, err := io.ReadAll(io.LimitReader(resp.Body, maxSteamAPIBodyBytes)) |
| 161 | + if err != nil { |
| 162 | + return nil, err |
| 163 | + } |
| 164 | + if resp.StatusCode != http.StatusOK { |
| 165 | + return nil, fmt.Errorf("steam api returned status %d", resp.StatusCode) |
| 166 | + } |
| 167 | + |
| 168 | + var envelope struct { |
| 169 | + Response struct { |
| 170 | + Success int `json:"success"` |
| 171 | + SteamID string `json:"steamid"` |
| 172 | + Message string `json:"message"` |
| 173 | + } `json:"response"` |
| 174 | + } |
| 175 | + if err := json.Unmarshal(body, &envelope); err != nil { |
| 176 | + return nil, fmt.Errorf("decode steam api json: %w", err) |
| 177 | + } |
| 178 | + // success 1 = OK; 42 is the usual "no match" code. |
| 179 | + if envelope.Response.Success != 1 { |
| 180 | + msg := strings.TrimSpace(envelope.Response.Message) |
| 181 | + if msg == "" { |
| 182 | + return nil, fmt.Errorf("steam api could not resolve vanity (success=%d)", envelope.Response.Success) |
| 183 | + } |
| 184 | + return nil, fmt.Errorf("steam api: %s", msg) |
| 185 | + } |
| 186 | + if envelope.Response.SteamID == "" { |
| 187 | + return nil, fmt.Errorf("steam api returned empty steamid") |
| 188 | + } |
| 189 | + return ToSteamID(envelope.Response.SteamID) |
| 190 | +} |
0 commit comments