golang project
This commit is contained in:
@@ -0,0 +1,238 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"builder/db"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
var (
|
||||
httpClient = &http.Client{Timeout: 20 * time.Second}
|
||||
// ~1 request every 1.6s keeps you under appdetails' ~200 per 5 min
|
||||
limiter = rate.NewLimiter(rate.Every(1600*time.Millisecond), 1)
|
||||
)
|
||||
|
||||
func getJSON(ctx context.Context, url string, out any) error {
|
||||
const maxAttempts = 5
|
||||
|
||||
for attempt := 1; ; attempt++ {
|
||||
if err := limiter.Wait(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; my-game-fetcher/1.0)")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
|
||||
// Rate limited or temporary server trouble: back off and retry
|
||||
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
|
||||
if attempt >= maxAttempts {
|
||||
return fmt.Errorf("GET %s: status %d after %d attempts", url, resp.StatusCode, attempt)
|
||||
}
|
||||
wait := time.Duration(attempt) * 30 * time.Second
|
||||
if s, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
|
||||
wait = time.Duration(s) * time.Second
|
||||
}
|
||||
log.Printf("status %d, sleeping %s", resp.StatusCode, wait)
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
continue
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("GET %s: status %d, body: %.200s", url, resp.StatusCode, body)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return fmt.Errorf("GET %s: decode: %w (body: %.200s)", url, err, body)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
storeBase = "https://store.steampowered.com"
|
||||
country = "de" // "de" => prices in EUR
|
||||
)
|
||||
|
||||
var client = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
func today() string { return time.Now().UTC().Format("2006-01-02") }
|
||||
|
||||
// ---------- raw Steam calls ----------
|
||||
|
||||
type reviewTotals struct {
|
||||
Positive int64
|
||||
Negative int64
|
||||
}
|
||||
|
||||
func fetchReviewTotals(ctx context.Context, gameID int64) (reviewTotals, error) {
|
||||
var res struct {
|
||||
Success int `json:"success"`
|
||||
Summary struct {
|
||||
TotalPositive int64 `json:"total_positive"`
|
||||
TotalNegative int64 `json:"total_negative"`
|
||||
} `json:"query_summary"`
|
||||
}
|
||||
url := fmt.Sprintf("%s/appreviews/%d?json=1&language=all&purchase_type=all&num_per_page=0",
|
||||
storeBase, gameID)
|
||||
if err := getJSON(ctx, url, &res); err != nil {
|
||||
return reviewTotals{}, err
|
||||
}
|
||||
if res.Success != 1 {
|
||||
return reviewTotals{}, fmt.Errorf("appreviews %d: success=%d", gameID, res.Success)
|
||||
}
|
||||
return reviewTotals{res.Summary.TotalPositive, res.Summary.TotalNegative}, nil
|
||||
}
|
||||
|
||||
type appDetails struct {
|
||||
Name string
|
||||
Release string
|
||||
Price int64 // cents, 0 if free / no price
|
||||
Discount int64 // percent
|
||||
Currency string
|
||||
}
|
||||
|
||||
func fetchAppDetails(ctx context.Context, gameID int64) (*appDetails, error) {
|
||||
var res map[string]struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Name string `json:"name"`
|
||||
ReleaseDate struct {
|
||||
Date string `json:"date"`
|
||||
} `json:"release_date"`
|
||||
PriceOverview *struct {
|
||||
Currency string `json:"currency"`
|
||||
Final int64 `json:"final"`
|
||||
DiscountPercent int64 `json:"discount_percent"`
|
||||
} `json:"price_overview"`
|
||||
} `json:"data"`
|
||||
}
|
||||
url := fmt.Sprintf("%s/api/appdetails?appids=%d&cc=%s&l=english", storeBase, gameID, country)
|
||||
if err := getJSON(ctx, url, &res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entry, ok := res[fmt.Sprint(gameID)]
|
||||
if !ok || !entry.Success {
|
||||
return nil, fmt.Errorf("appdetails %d: not found", gameID)
|
||||
}
|
||||
|
||||
d := &appDetails{
|
||||
Name: entry.Data.Name,
|
||||
Release: parseRelease(entry.Data.ReleaseDate.Date),
|
||||
Currency: "EUR",
|
||||
}
|
||||
if po := entry.Data.PriceOverview; po != nil {
|
||||
d.Price = po.Final
|
||||
d.Discount = po.DiscountPercent
|
||||
d.Currency = po.Currency
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// parseRelease turns Steam's "27 Sep, 2007" into "2007-09-27".
|
||||
// Unknown formats ("Coming soon") are returned unchanged.
|
||||
func parseRelease(s string) string {
|
||||
for _, layout := range []string{"2 Jan, 2006", "Jan 2, 2006", "2 Jan 2006", "Jan 2006"} {
|
||||
if t, err := time.Parse(layout, s); err == nil {
|
||||
return t.Format("2006-01-02")
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---------- public API ----------
|
||||
|
||||
// FetchGameMetadata returns the name, total review count and positive
|
||||
// score (0..100) straight from Steam, without touching the db.
|
||||
func FetchGameMetadata(ctx context.Context, GameID int64) (name string, reviews int, score float64, err error) {
|
||||
details, err := fetchAppDetails(ctx, GameID)
|
||||
if err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
totals, err := fetchReviewTotals(ctx, GameID)
|
||||
if err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
|
||||
total := totals.Positive + totals.Negative
|
||||
if total > 0 {
|
||||
score = float64(totals.Positive) * 100 / float64(total)
|
||||
}
|
||||
return details.Name, int(total), score, nil
|
||||
}
|
||||
|
||||
// FetchGame fetches name + release date and stores the game row.
|
||||
// Call this once before FetchReviews / FetchPriceHist (foreign keys).
|
||||
func FetchGame(ctx context.Context, d *db.DB, GameID int64) error {
|
||||
details, err := fetchAppDetails(ctx, GameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.CreateGame(ctx, db.Game{ID: GameID, Name: details.Name, Release: details.Release})
|
||||
}
|
||||
|
||||
// FetchReviews stores today's review row. Steam only gives all-time totals,
|
||||
// so today's numbers are the totals minus the sums stored before today.
|
||||
func FetchReviews(ctx context.Context, d *db.DB, gameID int64) error {
|
||||
totals, err := fetchReviewTotals(ctx, gameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
date := today()
|
||||
prevPos, prevNeg, err := d.SumsBefore(ctx, gameID, date)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = d.AddReviewDay(ctx, db.ReviewDay{
|
||||
GameID: gameID,
|
||||
Date: date,
|
||||
Positive: max(totals.Positive-prevPos, 0), // Steam can remove reviews
|
||||
Negative: max(totals.Negative-prevNeg, 0),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// FetchPriceHist stores today's price. Steam has no price history endpoint,
|
||||
// so the history is built by running this once a day.
|
||||
func FetchPriceHist(ctx context.Context, d *db.DB, gameID int64) error {
|
||||
details, err := fetchAppDetails(ctx, gameID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.AddPriceDay(ctx, db.PriceDay{
|
||||
GameID: gameID,
|
||||
Date: today(),
|
||||
Price: details.Price,
|
||||
Discount: details.Discount,
|
||||
Currency: details.Currency,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user