golang project

This commit is contained in:
zipfriis
2026-11-19 14:06:28 +01:00
parent 646c634f54
commit d45e8e8738
12 changed files with 9745 additions and 0 deletions
+238
View File
@@ -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,
})
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+241
View File
@@ -0,0 +1,241 @@
package db
import (
"context"
"database/sql"
"errors"
"time"
_ "modernc.org/sqlite" // pure-Go driver, no CGO needed
)
// Dates are ISO text "2006-01-02". Prices are int cents (EUR).
// Score is an int 0..10000 (10000 = 100.00%).
const schema = `
CREATE TABLE IF NOT EXISTS game (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
release TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS reviews (
game_id INTEGER NOT NULL REFERENCES game(id) ON DELETE CASCADE,
date TEXT NOT NULL,
positive INTEGER NOT NULL,
negative INTEGER NOT NULL,
positive_sum INTEGER NOT NULL,
negative_sum INTEGER NOT NULL,
score INTEGER NOT NULL,
label TEXT NOT NULL,
PRIMARY KEY (game_id, date)
);
CREATE TABLE IF NOT EXISTS prices (
game_id INTEGER NOT NULL REFERENCES game(id) ON DELETE CASCADE,
date TEXT NOT NULL,
price INTEGER NOT NULL,
discount INTEGER NOT NULL,
currency TEXT NOT NULL DEFAULT 'EUR',
PRIMARY KEY (game_id, date)
);
`
// ---------- enum ----------
type ScoreLabel string
const (
NoReviews ScoreLabel = "No user reviews"
OverwhelminglyNegative ScoreLabel = "Overwhelmingly Negative"
VeryNegative ScoreLabel = "Very Negative"
Negative ScoreLabel = "Negative"
MostlyNegative ScoreLabel = "Mostly Negative"
Mixed ScoreLabel = "Mixed"
MostlyPositive ScoreLabel = "Mostly Positive"
Positive ScoreLabel = "Positive"
VeryPositive ScoreLabel = "Very Positive"
OverwhelminglyPositive ScoreLabel = "Overwhelmingly Positive"
)
// ---------- types ----------
type Game struct {
ID int64
Name string
Release string
}
type ReviewDay struct {
GameID int64
Date string
Positive int64 // that day
Negative int64
// calculated
PositiveSum int64 // cumulative incl. this day
NegativeSum int64
Score int // 0..10000
Label ScoreLabel
}
type PriceDay struct {
GameID int64
Date string
Price int64 // cents
Discount int64 // percent
Currency string
}
func (r *ReviewDay) SolveScore() {
total := r.PositiveSum + r.NegativeSum
if total == 0 {
r.Score = 0
return
}
r.Score = int(r.PositiveSum * 10000 / total)
}
func (r *ReviewDay) ResolveLabel() {
total := r.PositiveSum + r.NegativeSum
pct := r.Score / 100
switch {
case total < 10:
r.Label = NoReviews
case pct >= 95 && total >= 500:
r.Label = OverwhelminglyPositive
case pct >= 80 && total >= 50:
r.Label = VeryPositive
case pct >= 80:
r.Label = Positive
case pct >= 70:
r.Label = MostlyPositive
case pct >= 40:
r.Label = Mixed
case pct >= 20:
r.Label = MostlyNegative
case total >= 500:
r.Label = OverwhelminglyNegative
case total >= 50:
r.Label = VeryNegative
default:
r.Label = Negative
}
}
// ---------- db ----------
type DB struct {
*sql.DB
}
// Open opens (or creates) the SQLite file and applies the schema.
func Open(path string) (*DB, error) {
sqlDB, err := sql.Open("sqlite", path+"?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
if err != nil {
return nil, err
}
sqlDB.SetMaxOpenConns(1)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := sqlDB.PingContext(ctx); err != nil {
return nil, err
}
if _, err := sqlDB.ExecContext(ctx, schema); err != nil {
return nil, err
}
return &DB{sqlDB}, nil
}
func (d *DB) CreateGame(ctx context.Context, g Game) error {
_, err := d.ExecContext(ctx,
`INSERT INTO game (id, name, release) VALUES (?, ?, ?)
ON CONFLICT(id) DO UPDATE SET name = excluded.name, release = excluded.release`,
g.ID, g.Name, g.Release)
return err
}
func (d *DB) ListGames(ctx context.Context) ([]Game, error) {
rows, err := d.QueryContext(ctx, `SELECT id, name, release FROM game ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var games []Game
for rows.Next() {
var g Game
if err := rows.Scan(&g.ID, &g.Name, &g.Release); err != nil {
return nil, err
}
games = append(games, g)
}
return games, rows.Err()
}
// SumsBefore returns the cumulative review sums of the last day before date.
// Returns zeros if there is none.
func (d *DB) SumsBefore(ctx context.Context, gameID int64, date string) (pos, neg int64, err error) {
err = d.QueryRowContext(ctx,
`SELECT positive_sum, negative_sum FROM reviews
WHERE game_id = ? AND date < ?
ORDER BY date DESC LIMIT 1`, gameID, date).Scan(&pos, &neg)
if errors.Is(err, sql.ErrNoRows) {
return 0, 0, nil
}
return pos, neg, err
}
// AddReviewDay adds the previous cumulative sums, computes score + label, upserts.
func (d *DB) AddReviewDay(ctx context.Context, r ReviewDay) (*ReviewDay, error) {
prevPos, prevNeg, err := d.SumsBefore(ctx, r.GameID, r.Date)
if err != nil {
return nil, err
}
r.PositiveSum = prevPos + r.Positive
r.NegativeSum = prevNeg + r.Negative
r.SolveScore()
r.ResolveLabel()
_, err = d.ExecContext(ctx,
`INSERT INTO reviews (game_id, date, positive, negative, positive_sum, negative_sum, score, label)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(game_id, date) DO UPDATE SET
positive = excluded.positive, negative = excluded.negative,
positive_sum = excluded.positive_sum, negative_sum = excluded.negative_sum,
score = excluded.score, label = excluded.label`,
r.GameID, r.Date, r.Positive, r.Negative, r.PositiveSum, r.NegativeSum, r.Score, string(r.Label))
if err != nil {
return nil, err
}
return &r, nil
}
func (d *DB) AddPriceDay(ctx context.Context, p PriceDay) error {
if p.Currency == "" {
p.Currency = "EUR"
}
_, err := d.ExecContext(ctx,
`INSERT INTO prices (game_id, date, price, discount, currency)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(game_id, date) DO UPDATE SET
price = excluded.price, discount = excluded.discount, currency = excluded.currency`,
p.GameID, p.Date, p.Price, p.Discount, p.Currency)
return err
}
func (d *DB) LatestReview(ctx context.Context, gameID int64) (*ReviewDay, error) {
var r ReviewDay
var label string
err := d.QueryRowContext(ctx,
`SELECT game_id, date, positive, negative, positive_sum, negative_sum, score, label
FROM reviews WHERE game_id = ? ORDER BY date DESC LIMIT 1`, gameID).
Scan(&r.GameID, &r.Date, &r.Positive, &r.Negative, &r.PositiveSum, &r.NegativeSum, &r.Score, &label)
if err != nil {
return nil, err
}
r.Label = ScoreLabel(label)
return &r, nil
}
+17
View File
@@ -0,0 +1,17 @@
module builder
go 1.26.0
require (
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/time v0.16.0 // indirect
modernc.org/libc v1.80.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.62.0 // indirect
)
+22
View File
@@ -0,0 +1,22 @@
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4=
modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"context"
"fmt"
"log"
"builder/api"
"builder/db"
)
func main() {
d, err := db.Open("data.db")
if err != nil {
log.Fatal(err)
}
defer d.Close()
ctx := context.Background()
gameIDs := []int64{1245620} // Steam app ids
for _, id := range gameIDs {
if err := api.FetchGame(ctx, d, id); err != nil {
log.Fatal(err)
}
if err := api.FetchReviews(ctx, d, id); err != nil {
log.Fatal(err)
}
if err := api.FetchPriceHist(ctx, d, id); err != nil {
log.Fatal(err)
}
}
games, err := d.ListGames(ctx)
if err != nil {
log.Fatal(err)
}
for _, g := range games {
r, err := d.LatestReview(ctx, g.ID)
if err != nil {
log.Printf("%d %s: no reviews", g.ID, g.Name)
continue
}
fmt.Printf("%d %s released %s score %.2f%% %s\n",
g.ID, g.Name, g.Release, float64(r.Score)/100, r.Label)
}
for i := range 20000 { // Go 1.22+; range over an int yields one value
id := i + 10000
_, reviews, _, err := api.FetchGameMetadata(ctx, int64(id))
if err != nil {
log.Printf("metadata for id %d: %v", id, err)
continue
}
if reviews < 500 {
continue
}
if err := api.FetchGame(ctx, d, int64(id)); err != nil {
log.Printf("game for id %d: %v", id, err)
}
}
}